How to use the tornado.web function in tornado

To help you get started, we’ve selected a few tornado examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github python-provy / provy / tests / end_to_end / files / website.py View on Github external
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")


application = tornado.web.Application([
    (r"/", MainHandler),
])


if __name__ == "__main__":
    port = int(sys.argv[1])
    application.listen(port, '0.0.0.0')
    print ">> Website running at http://0.0.0.0:%d" % port
    tornado.ioloop.IOLoop.instance().start()
github mopidy / mopidy / mopidy / http / handlers.py View on Github external
return os.path.dirname(__file__)

    def get(self):
        set_mopidy_headers(self)

        names = set()
        for app in self.apps:
            names.add(app['name'])
        for static in self.statics:
            names.add(static['name'])
        names.discard('mopidy')

        self.render('data/clients.html', apps=sorted(list(names)))


class StaticFileHandler(tornado.web.StaticFileHandler):

    def set_extra_headers(self, path):
        set_mopidy_headers(self)


class AddSlashHandler(tornado.web.RequestHandler):

    @tornado.web.addslash
    def prepare(self):
        return super(AddSlashHandler, self).prepare()
github scgupta / tutorial-python-microservice-tornado / addrservice / tornado / app.py View on Github external
def make_addrservice_app(
    config: Dict,
    debug: bool,
    logger: logging.Logger
) -> Tuple[AddressBookService, tornado.web.Application]:
    service = AddressBookService(config, logger)

    app = tornado.web.Application(
        [
            # Address Book endpoints
            (ADDRESSBOOK_REGEX, AddressBookRequestHandler,
                dict(service=service, config=config, logger=logger)),
            (ADDRESSBOOK_ENTRY_REGEX, AddressBookEntryRequestHandler,
                dict(service=service, config=config, logger=logger))
        ],
        compress_response=True,  # compress textual responses
        log_function=log_function,  # log_request() uses it to log results
        serve_traceback=debug,  # it is passed on as setting to write_error()
        default_handler_class=DefaultRequestHandler,
        default_handler_args={
            'status_code': 404,
            'message': 'Unknown Endpoint',
            'logger': logger
        }
github VOLTTRON / volttron / services / core / VolttronCentral / volttroncentral / webserver.py View on Github external
def open(self):
        print("Opened!")
        #self.application.shoppingCart.register(self.callback)

    def on_close(self):
        print("Closed")
        #self.application.shoppingCart.unregister(self.callback)

    def on_message(self, message):
        self.write_message("write from server: "+message)

#     def callback(self, count):
#         self.write_message('{"inventoryCount":"%d"}' % count)

@tornado.web.stream_request_body
class ManagerRequestHandler(tornado.web.RequestHandler):
    '''The main RequestHanlder for the platform manager.

    The manager only accepts posted RpcParser methods.  The manager will parse
    the request body for valid json RpcParser.  The first call to this request
    handler must be a getAuthorization request.  The call will return an
    authorization token that will be valid for the current session.  The token
    must be passed to any other calls to the handler or a 401 Unauhthorized
    code will be returned.
    '''
    def prepare(self):
        self.tmp = TemporaryFile()

    def data_received(self, chunk):
        self.tmp.write(chunk)

    def _route(self, rpcRequest):
github yandex-load / volta / volta / ui / handlers / barplot.py View on Github external
import tornado.web
import logging
import seaborn as sns
import datetime
import matplotlib.pyplot as plt
import pandas as pd
import os
import base64

from pkg_resources import resource_filename


class BarplotBuilder(tornado.web.RequestHandler):
    def get(self):
        """ Helper barplot page w/ list of logs

        Returns:
            barplot template, fills it with logs found at 'logs'
        """
        dir_files = os.listdir('logs')
        # use any files in './logs' that endswith 'log'
        items = ['./logs/{filename}'.format(filename=filename) for filename in dir_files if filename.endswith('log')]
        self.render(
            resource_filename(__name__, 'barplot.html'),
            title="Barplot builder",
            items=items
        )

    def post(self):
github cyclozzo / cyclozzo / cyclozzo-sdk / cyclozzo / apps / tools / appserver_channel.py View on Github external
class ChannelJSAPIHandler(tornado.web.RequestHandler):
    """Channel JSAPI handler.
    """
    def get(self):
        """Returns the JSAPI script.
        """
        js_file = open(
            os.path.join(os.path.dirname(__file__), 'cyclozzo-channel-js.js'), 'rb')
        js_data = js_file.read()
        js_file.close()
        self.set_header('Content-Type', 'application/javascript')
        self.write(js_data)


class ChannelDevNullHandler(tornado.web.RequestHandler):
    """Dev null handler
    """
    def get(self):
        pass

    def post(self):
        pass


def main():
    logging.basicConfig(level=logging.DEBUG)
    application = tornado.web.Application([
        (CHANNEL_SUBSCRIBE_PATTERN, ChannelSubscribeHandler),
        (CHANNEL_PUBLISH_PATTERN, ChannelPublishHandler),
        (CHANNEL_JSAPI_PATTERN, ChannelJSAPIHandler),
        (CHANNEL_DEVNULL_PATTERN, ChannelDevNullHandler)
github v3aqb / fwlite / fgfw-lite / fgfw-lite.py View on Github external
    @tornado.web.asynchronous
    def get(self):
        yield self.get_remote_conn()

        if self._finished:
            return
        logging.debug('GET')
        self._state = 'get'
        client = self.request.connection.stream
        self._client_write_buffer = []

        def _do_client_write(data):
            self.remove_timeout()
            if not client.closed():
                client.write(data)
                self._headers_written = True
                self._no_retry = True
github mandatoryprogrammer / xsshunter / gui / guiserver.py View on Github external
def make_app():
    return tornado.web.Application([
        (r"/", HomepageHandler),
        (r"/app", XSSHunterApplicationHandler),
        (r"/features", FeaturesHandler),
        (r"/signup", SignUpHandler),
        (r"/contact", ContactHandler),
        (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "static/"}),
    ])
github mozilla / openwebapps / server / server.py View on Github external
class AppDetailHandler(tornado.web.RequestHandler):
  def get(self):
    if not 'id' in self.request.arguments:
      return self.redirect("/")

    id = self.request.arguments["id"][0].strip()
    appData = db.select_app(id)
    if not appData:
      return self.render("error.html", error="Illegal or missing application ID", user=getUserObject(self))

    app = Application(appData)
    app.releaseDateObj = datetime.date.fromtimestamp(app.releaseDate)
    dev = Developer(db.select_developer(app.developer))
    self.render("app_detail.html", app=app, dev=dev, user=getUserObject(self))

class AppRegisterHandler(tornado.web.RequestHandler):
  def do_render(self, user, error=None):
    userDevIDs = db.select_user_developer_memberships(user.id)
    devs = [Developer(db.select_developer(DeveloperUser(ud).devid)) for ud in userDevIDs]
    self.render("app_register.html", user=user, devs=devs, error=error)

  def post(self):
    user = getUserObject(self)
    if not user:
      return self.do_render(error="You must be signed in (to a developer account) to register an app.", user=None)
    logging.debug(self.request.arguments)
    if not 'appname' in self.request.arguments:
      return self.do_render(error="Missing required application name", user=user)
    if not 'domain' in self.request.arguments:
      return self.do_render(error="Missing required application domain", user=user)
    if not 'category' in self.request.arguments:
      return self.do_render(error="Missing required application category", user=user)
github chrislgarry / HarkVisualizer / harkvisualizer.py View on Github external
    @tornado.web.asynchronous
    def get(self):
        self.render('index.html')