How to use the tornado.web.Application 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 wellcometrust / reach / test_target / target_server.py View on Github external
def make_app():
    basedir = "/".join(os.path.abspath(__file__).split("/")[:-1])
    return tornado.web.Application([
        (r"/", MainHandler,),
        (r"/robots.txt", RobotHandler,),
        (r"/page", PageHandler,),
        (r"/page2", PageHandler,),
        (r"/page3", PageHandler,),
        (r"/static/(.*)", tornado.web.StaticFileHandler, {'path': basedir}),
    ])
github 1stvamp / trequests / trequests_tests.py View on Github external
def get_app(self):
        if not self.application:
            self.application = Application(
                [(r'/', TestHandler)]
            )

        return self.application
github FRCDashboard / FRCDashboard / server.py View on Github external
# Setup NetworkTables
    init_networktables(options)

    # setup tornado application with static handler + networktables support
    www_dir = abspath(dirname(__file__))
    index_html = join(www_dir, 'index.html')

    if not exists(www_dir):
        logger.error('Directory \'%s\' does not exist!', www_dir)
        exit(1)

    if not exists(index_html):
        logger.warn('%s not found' % index_html)

    app = tornado.web.Application(
        get_handlers() + [
            (r'/()', NonCachingStaticFileHandler, {'path': index_html}),
            (r'/(.*)', NonCachingStaticFileHandler, {'path': www_dir})
        ]
    )

    # Start the app
    logger.info('Listening on http://localhost:%s/', options.port)

    app.listen(options.port)
    IOLoop.current().start()
github patrickfuller / imolecule / imolecule / server / server.py View on Github external
"time, in seconds, allowed for a process to run "
                        "before returning an error.")
    parser.add_argument('--workers', type=int, default=2, help="The number of "
                        "worker processes to use with the server.")
    parser.add_argument('--no-browser', action="store_true", help="Disables "
                        "opening a browser window on startup.")
    global args
    args = parser.parse_args()

    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)

    handlers = [(r'/', IndexHandler), (r'/websocket', WebSocket),
                (r'/static/(.*)', tornado.web.StaticFileHandler,
                 {'path': os.path.normpath(os.path.dirname(__file__))})]
    application = tornado.web.Application(handlers)
    application.listen(args.port)

    if not args.no_browser:
        webbrowser.open('http://localhost:%d/' % args.port, new=2)

    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        sys.stderr.write("Received keyboard interrupt. Stopping server.\n")
        tornado.ioloop.IOLoop.instance().stop()
        sys.exit(1)
github guardian / ganglia-api / ganglia / ganglia_api.py View on Github external
sys.exit(1)
        except OSError:
            pass
    file(PIDFILE, 'w').write(str(os.getpid()))

    global ganglia_config
    ganglia_config = GangliaConfig()

    global ganglia_data
    ganglia_data = GmetadData()
    poll_thread = GangliaPollThread()
    poll_thread.daemon = True
    poll_thread.start()

    tornado.options.parse_command_line()
    application = tornado.web.Application([
        (r"/ganglia/api/v1/metrics", ApiHandler),
    ])
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
github aiannacc / goko-dominion-tools / start_automatch_server.py View on Github external
def __init__(self):
        handlers = [
            (r"/automatch", AutomatchWSH),
        ]
        tornado.web.Application.__init__(
            self, handlers,
            static_path='web/static',
            ssl_options={
                "certfile": "cert.cer",
                "keyfile":  "key.key",
            }
github ayeowch / bitnodes-hardware / poll.py View on Github external
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
from collections import deque
from psutil import net_io_counters
from tornado.options import define, options

from django.conf import settings

define('address', type=str, default=settings.WEBSOCKET_HOST)
define('port', type=int, default=settings.WEBSOCKET_PORT)


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/poll', PollHandler),
        ]
        tornado.web.Application.__init__(self, handlers)


class PollHandler(tornado.websocket.WebSocketHandler):
    clients = []
    ticks = deque([], maxlen=180)

    def open(self):
        if self not in PollHandler.clients:
            PollHandler.clients.append(self)
            self.write_ticks()
github caomike / ppmessage / ppmessage / ppauth / ppauthapp.py View on Github external
def __init__(self):
        self.redis = redis.Redis(REDIS_HOST, REDIS_PORT, db=1)
        settings = {
            "debug": True,
            "static_path": os.path.abspath(os.path.dirname(__file__)) + "/static"
        }
        handlers = [
            ("/auth/?.*", AuthHandler),
            ("/token/?.*", TokenHandler),
        ]
        Application.__init__(self, handlers, **settings)
github TechEmpower / FrameworkBenchmarks / frameworks / Python / tornado / server.py View on Github external
sql = "SELECT id, randomNumber FROM World WHERE id=%s"

        worlds = []
        for i in xrange(int(queries)):
            random_id = randint(1, 10000)
            cursor = yield momoko.Op(
                self.application.db.execute, sql, (random_id,)
            )
            row = cursor.fetchone()
            worlds.append({"id": row[0], "randomNumber": row[1]})
        response = json.dumps(worlds)
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        self.write(response)

application = tornado.web.Application([
    (r"/json", JsonSerializeTestHandler),
    (r"/plaintext", PlaintextHandler),
    (r"/db", DBTestHandler),
    (r"/queries", QueryTestHandler),
    (r"/dbraw", QueryPostgresRawTestHandler),
    (r"/queriesraw", MultipleQueriesPostgresRawTestHandler)
])


if __name__ == "__main__":
    tornado.options.parse_command_line()
    server = tornado.httpserver.HTTPServer(application)
    server.bind(options.port)
    server.start(0)
    if options.postgres:
        dsn = "user=benchmarkdbuser password=benchmarkdbpass dbname=hello_world host=%s" % options.postgres
github danielballan / jupyterhub-share-link / jupyterhub_share_link / run.py View on Github external
def main():
    app = Application(
        [
            (os.environ['JUPYTERHUB_SERVICE_PREFIX'] + r'create/?', CreateSharedLink),
            (os.environ['JUPYTERHUB_SERVICE_PREFIX'] + r'open/?', OpenSharedLink),
            (os.environ['JUPYTERHUB_SERVICE_PREFIX'] + r'inspect/?', InspectSharedLink),
            (os.environ['JUPYTERHUB_SERVICE_PREFIX'] + r'/?', Info),
        ]
    )

    http_server = HTTPServer(app)
    url = urlparse(os.environ['JUPYTERHUB_SERVICE_URL'])

    http_server.listen(url.port, url.hostname)
    tornado.options.parse_command_line(sys.argv)

    IOLoop.current().start()