def __init__(self, handlers=None, default_host="", transforms=None, wsgi=False, **settings): if not handlers: handlers = [ (r"/_/api/changes", ChangeRequestHandler), (r"/_/api/?(.*)", APIRequestHandler), (r"/_/?(.*)", AssetsHandler, {"path": os.path.join(module_path(), '_')}), (r"/", RedirectHandler, {'url': '/_/index.html'}), ] if not settings: settings = { 'debug': True, 'template_path': os.path.join(module_path(), '_'), } if not default_host: default_host = '.*$' Application.__init__(self, handlers, default_host, transforms, wsgi, **settings) self.internal_handler_count = len(handlers) self.change_request_handlers = set() self.observer = ChangesObserver(changes_handler=self.change_happened) self.config_path = config_path() self.config = self.load_config() self.project = None for project in self.config.get('projects', []): if project.get('isCurrent'): self.project = project self.set_project(project) break
class TornadoWebServer(quick2web.webserver.WebServer): def __init__(self, port, debug = False, quick2web_resources = os.path.join(os.path.dirname(__file__), 'resources'), ioloop = IOLoop.instance()): self.handlers = [] self.application = None self.ioloop = ioloop self.port = port self.url = 'http://%s:%d/' % (gethostname(), self.port) self.settings = dict( debug = debug # Auto reload app when Python code changes on disk, stack traces on error pages ) if quick2web_resources: self.static_files('/quick2web/', quick2web_resources) def static_files(self, path, directory_on_disk, default_filename='index.html'): self.handlers.append((path + '(.*)', StaticFileHandler, dict(path=directory_on_disk, default_filename=default_filename))) def websocket(self, path, handler): self.handlers.append((path, TornadoWebSocketAdapter, dict(handler=handler))) def run(self, **kwargs): self.application = Application(self.handlers, **self.settings) self.application.listen(self.port) self.ioloop.start()
def init_websocket_server(): '''Initialize websocket server.''' app = Application([ (r'/judge', JudgeHandler), ]) app.listen(2501)
def main(urls_map): settings = {"auto_reload": True, "debug": True} application = Application(urls_map, **settings) application.listen(9999) logging.info("API server is running on port 9999") ioloop_instance = tornado.ioloop.IOLoop.instance() ioloop_instance.start()
def __init__(self): settings = {} settings["debug"] = True handlers = [] handlers.extend(UploadWebService.get_handlers()) self.redis = redis.Redis(REDIS_HOST, REDIS_PORT, db=1) Application.__init__(self, handlers, **settings)
class WebServerThread(QThread): # signals running = pyqtSignal() def __init__(self, parent=None): QThread.__init__(self, parent) self.fApplication = Application( [ (r"/effect/get/?", EffectGet), (r"/effect/(icon|settings).html", EffectHTML), (r"/effect/stylesheet.css", EffectStylesheet), (r"/effect/gui.js", EffectJavascript), (r"/resources/(.*)", EffectResource), (r"/(.*)", StaticFileHandler, {"path": HTML_DIR}), ], debug=True) self.fPrepareWasCalled = False def run(self): if not self.fPrepareWasCalled: self.fPrepareWasCalled = True self.fApplication.listen(PORT, address="0.0.0.0") enable_pretty_logging() self.running.emit() IOLoop.instance().start() def stopWait(self): IOLoop.instance().stop() return self.wait(5000)
def __init__(self): # handlers = [ # (r'/', IndexHandler), # # # 所有html静态文件都默认被StaticFileHandler处理 # # (r'/tpl/(.*)', StaticFileHandler, { # # 'path': os.path.join(os.path.dirname(__file__), 'templates') # # }), # # PC端网页 # # (r'/f/', RedirectHandler, {'url': '/f/index.html'}), # # (r'/f/(.*)', StaticFileHandler, { # # 'path': os.path.join(os.path.dirname(__file__), 'front') # # }), # ] handlers = [] handlers.extend(nui.routes) handlers.extend(service.routes) handlers.extend(stock.routes) handlers.extend(smscenter.routes) handlers.extend(weui.routes) handlers.extend(routes) site_url_prefix = settings.get(constant.SITE_URL_PREFIX, "") if site_url_prefix: # 构建新的URL handlers = map( lambda x: url(site_url_prefix + x.regex.pattern, x.handler_class, x.kwargs, x.name), handlers ) # handlers = get_handlers() # 配置默认的错误处理类 settings.update({"default_handler_class": ErrorHandler, "default_handler_args": dict(status_code=404)}) Application.__init__(self, handlers=handlers, **settings)
def main(): define('listen', metavar='IP', default='127.0.0.1', help='listen on IP address (default 127.0.0.1)') define('port', metavar='PORT', default=8888, type=int, help='listen on PORT (default 8888)') define('debug', metavar='True|False', default=False, type=bool, help='enable Tornado debug mode: templates will not be cached ' 'and the app will watch for changes to its source files ' 'and reload itself when anything changes') options.parse_command_line() settings = dict( template_path=rel('templates'), static_path=rel('static'), debug=options.debug ) application = Application([ (r'/', MainHandler), (r'/ws', EchoWebSocket), (r'/websocket', SignallingHandler), (r'/webrtc', WebRTCHandler) ], **settings) #application.listen(address=options.listen, port=options.port) application.listen(7080) IOLoop.instance().start()
def main(): root_dir = os.path.abspath(os.path.split(__file__)[0]) print(root_dir) app = Application([(r'/gfxtablet', GfxTabletHandler), #(r'/(index.js|src/.*\.js|node_modules/.*\.js)', StaticFileHandler, {}), (r'/', MainHandler)], debug=config.get('DEBUG', False), static_path=root_dir, static_url_prefix='/static/') _logger.info("app.settings:\n%s" % '\n'.join(['%s: %s' % (k, str(v)) for k, v in sorted(app.settings.items(), key=itemgetter(0))])) port = config.get('PORT', 5000) app.listen(port) _logger.info("listening on port %d" % port) _logger.info("press CTRL-C to terminate the server") _logger.info(""" ----------- G f x T a b l e t ************************* ********************************* STARTING TORNADO APP!!!!!!!!!!!!! ********************************* ************************* G f x T a b l e t ----------- """) IOLoop.instance().start()
def start(current_info): ''' Start an instance of the server. ''' io_utilities.safe_make_dirs(os.path.dirname(TORNADO_LOG_FILE_PREFIX)) tornado.options.options.log_file_prefix = TORNADO_LOG_FILE_PREFIX tornado.options.parse_command_line() logging.info("Starting up server on machine %s and port %s at %s." % (current_info[MACHINE], current_info[PORT_HEADER], time.strftime("%I:%M:%S"))) tr = WSGIContainer(app) application = Application([ (r"/tornado", MainHandler), (r".*", FallbackHandler, dict(fallback=tr)), ]) application.listen(PORT) # Gracefully handle server shutdown. signal.signal(signal.SIGTERM, sig_handler) signal.signal(signal.SIGINT, sig_handler) signal.signal(signal.SIGQUIT, sig_handler) # Add the current info to the running info file. write_running_info([current_info]) IOLoop.instance().start()
def main(): global http_server try: signal(SIGTERM, on_signal) parse_command_line() if options.config != None: parse_config_file(options.config) path = join(dirname(__file__), "templates") application = Application( [(r"/", IndexHandler), (r"/stock", StockHandler)], template_path=path, static_path=join(dirname(__file__), "static"), ) application.db = motor.MotorClient(options.db_host, options.db_port).open_sync()[options.db_name] http_server = HTTPServer(application) http_server.listen(options.port, options.address) log().info("server listening on port %s:%d" % (options.address, options.port)) if log().isEnabledFor(DEBUG): log().debug("autoreload enabled") tornado.autoreload.start() IOLoop.instance().start() except KeyboardInterrupt: log().info("exiting...") except BaseException as ex: log().error("exiting due: [%s][%s]" % (str(ex), str(format_exc().splitlines()))) exit(1)
def run_auth_server(): client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8081/callback"]) token_store = TokenStore() provider = Provider( access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=Uuid4() ) provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter())) try: app = Application( [ url(provider.authorize_path, OAuth2Handler, dict(provider=provider)), url(provider.token_path, OAuth2Handler, dict(provider=provider)), ] ) app.listen(8080) print("Starting OAuth2 server on http://localhost:8080/...") IOLoop.current().start() except KeyboardInterrupt: IOLoop.close()
def main(): application = Application([ (r"/", MainHandler), (r"/login", LoginHandler), (r"/logout", LogoutHandler), (r"/events", EventHandler), (r"/translations/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)", TranslationHandler), (r"/translations/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/button", ButtonHandler), (r"/selections/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)/([A-Za-z0-9_]+)", SelectionHandler), (r"/flags/([A-Za-z0-9_]+)", ImageHandler, { 'location': os.path.join(os.path.dirname(__file__), 'flags', '%s'), 'fallback': os.path.join(os.path.dirname(__file__), 'static', 'flag.png') }), ], **{ "login_url": "/", "template_path": os.path.join(os.path.dirname(__file__), "templates"), "static_path": os.path.join(os.path.dirname(__file__), "static"), "cookie_secret": base64.b64encode("000000000000000000000"), }) application.listen(8891) try: IOLoop.instance().start() except KeyboardInterrupt: # Exit cleanly. return
def __init__(self): logging.getLogger().setLevel(options.logging_level) if options.debug: logging.warn("==================================================================================") logging.warn("SERVER IS RUNNING IN DEBUG MODE! MAKE SURE THIS IS OFF WHEN RUNNING IN PRODUCTION!") logging.warn("==================================================================================") logging.info("Starting server...") # apollo distribution root dist_root = os.path.join(os.path.dirname(__file__), "..", "..") Application.__init__( self, [ (r"/", FrontendHandler), (r"/session", SessionHandler), (r"/action", ActionHandler), (r"/events", EventsHandler), (r"/dylib/(.*)\.js", DylibHandler) ], dist_root = dist_root, static_path = os.path.join(dist_root, "static"), debug = options.debug ) self.loader = Loader(os.path.join(dist_root, "template")) setupDBSession() self.dylib_dispatcher = DylibDispatcher(self) self.bus = Bus(self) self.plugins = PluginRegistry(self) self.cron = CronScheduler(self)
def run_auth_server(): client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=[], authorized_grants=[oauth2.grant.ClientCredentialsGrant.grant_type]) token_store = TokenStore() # Generator of tokens token_generator = oauth2.tokengenerator.Uuid4() token_generator.expires_in[oauth2.grant.ClientCredentialsGrant.grant_type] = 3600 provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=token_generator) # provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter())) provider.add_grant(ClientCredentialsGrant()) try: app = Application([ url(provider.authorize_path, OAuth2Handler, dict(provider=provider)), url(provider.token_path, OAuth2Handler, dict(provider=provider)), ]) app.listen(8080) print("Starting OAuth2 server on http://localhost:8080/...") IOLoop.current().start() except KeyboardInterrupt: IOLoop.close()
def testCustomEndpoint(self): MetricTransaction._endpoints = [] config = { "endpoints": {"https://foo.bar.com": ["foo"]}, "dd_url": "https://foo.bar.com", "api_key": "foo", "use_dd": True } app = Application() app.skip_ssl_validation = False app._agentConfig = config app.use_simple_http_client = True trManager = TransactionManager(timedelta(seconds=0), MAX_QUEUE_SIZE, THROTTLING_DELAY, max_endpoint_errors=100) trManager._flush_without_ioloop = True # Use blocking API to emulate tornado ioloop MetricTransaction._trManager = trManager MetricTransaction.set_application(app) MetricTransaction.set_endpoints(config['endpoints']) transaction = MetricTransaction(None, {}, "msgtype") endpoints = [] for endpoint in transaction._endpoints: for api_key in transaction._endpoints[endpoint]: endpoints.append(transaction.get_url(endpoint, api_key)) expected = ['https://foo.bar.com/intake/msgtype?api_key=foo'] self.assertEqual(endpoints, expected, (endpoints, expected))
def make_server(config_path): root = path.dirname(__file__) static_path = path.join(root, 'static') template_path = path.join(root, 'template') define('port', default=7777, type=int) define('production', default=False, type=bool) define('mongo_db_name', default='open_wireless_map', type=str) define('mongo_host', default='localhost', type=str) define('mongo_port', default=27017, type=int) define('mongo_user', default=None, type=str) define('mongo_password', default=None, type=str) define('api_password_hash', default=None, type=str) parse_config_file(config_path) app_config = dict(static_path=static_path, template_path=template_path) if not options.production: app_config.update(debug=True) server = Application(url_map, **app_config) server.settings['api_password_hash'] = options.api_password_hash server.settings['mongo'] = get_mongo(db_name=options.mongo_db_name, host=options.mongo_host, port=options.mongo_port, user=options.mongo_user, password=options.mongo_password) return server
def __init__(self, _web): self.redis = redis.Redis(REDIS_HOST, REDIS_PORT, db=1) settings = {} settings["debug"] = True handlers = [] handlers.extend(_web) Application.__init__(self, handlers, **settings)
def run(filedict, port=None, debug=False): # print args # Set logging level options.logging = 'INFO' if debug: print 'Enter debug mode' options.logging = 'DEBUG' enable_pretty_logging(options) application = Application( [ (r'/', IndexHandler), ], static_path=os.path.join(root_path, 'static'), template_path=os.path.join(root_path, 'template'), debug=debug, ) for host, rules in application.handlers: for i in rules: logging.debug('URL rule %s', i.regex.pattern) application.yaml_filedict = filedict http_server = httpserver.HTTPServer(application) http_server.listen(port) print 'Colordesk server started: http://127.0.0.1:%s' % port try: ioloop.IOLoop.instance().start() except KeyboardInterrupt: print 'Stop colordesk server.'
def main(): define("host", default="127.0.0.1", help="Host IP") define("port", default=8080, help="Port") define("mongodb_url", default="127.0.0.1:27017", help="MongoDB connection URL") tornado.options.parse_command_line() client = motor.motor_tornado.MotorClient(options.mongodb_url) db = client['imgr'] template_dir = os.getenv('OPENSHIFT_REPO_DIR', '') template_dir = os.path.join(template_dir, 'imgr/templates') static_dir = os.getenv('OPENSHIFT_DATA_DIR', os.path.dirname(__file__)) static_dir = os.path.join(static_dir, 'static') settings = { "static_path": static_dir, 'template_path': template_dir } application = Application([(r"/files/([^/]+)/?", MainHandler, dict(db=db)), (r"/files/?", MainHandler, dict(db=db)), (r'/?', HomeHandler, ), (r'/([^/]+)/?', FileHandler, )], **settings) application.listen(options.port, options.host) tornado.ioloop.IOLoop.instance().start()
def testCustomEndpoint(self): MetricTransaction._endpoints = [] config = { "sd_url": "https://foo.bar.com", "agent_key": "foo", "use_dd": True } app = Application() app.skip_ssl_validation = False app._agentConfig = config app.use_simple_http_client = True trManager = TransactionManager(timedelta(seconds=0), MAX_QUEUE_SIZE, THROTTLING_DELAY) trManager._flush_without_ioloop = True # Use blocking API to emulate tornado ioloop MetricTransaction._trManager = trManager MetricTransaction.set_application(app) MetricTransaction.set_endpoints() transaction = MetricTransaction(None, {}, "msgtype") endpoints = [transaction.get_url(e) for e in transaction._endpoints] # Direct metric submission is not being enabled. #expected = ['https://foo.bar.com/intake/msgtype?agent_key=foo'] expected = [] self.assertEqual(endpoints, expected, (endpoints, expected))
def run(): parser = ArgumentParser() parser.add_argument("-f", "--fake", action="store_true", help="Use a fake connection for development") parser.add_argument("-i", "--id", default=socket.gethostname(), help="ID of this site") args = parser.parse_args() if args.fake: m = MissileLauncher(FakeMissileLauncherConnection()) else: m = MissileLauncher(MissileLauncherConnection(0)) config = { 'launcher': m, 'id': args.id } application = Application([ (r"/position", PositionHandler, config), (r"/move/(-?[01])/(-?[01])", PositionHandler, config), (r"/move_to/([-0-9.]*)/([-0-9.]*)", MoveHandler, config), (r"/fire_at/([-0-9.]*)/([-0-9.]*)", FireHandler, config), (r"/calibrate", CalibrateHandler, config), (r"/", IndexHandler), (r"/static/(.*)", StaticFileHandler, {'path': 'static/'}) ], debug=True) application.listen(7777) periodic = PeriodicCallback(m.timestep, 100) periodic.start() print('Site {} listening at http://{}:7777'.format(args.id, socket.gethostname())) IOLoop.instance().start()
def test_proxy(self): config = { "endpoints": {"https://app.datadoghq.com": ["foo"]}, "proxy_settings": { "host": "localhost", "port": PROXY_PORT, "user": None, "password": None } } app = Application() app.skip_ssl_validation = True app._agentConfig = config trManager = TransactionManager(MAX_WAIT_FOR_REPLAY, MAX_QUEUE_SIZE, THROTTLING_DELAY) trManager._flush_without_ioloop = True # Use blocking API to emulate tornado ioloop CustomAgentTransaction.set_tr_manager(trManager) app.use_simple_http_client = False # We need proxy capabilities app.agent_dns_caching = False # _test is the instance of this class. It is needed to call the method stop() and deal with the asynchronous # calls as described here : http://www.tornadoweb.org/en/stable/testing.html CustomAgentTransaction._test = self CustomAgentTransaction.set_application(app) CustomAgentTransaction.set_endpoints(config['endpoints']) CustomAgentTransaction('body', {}, "") # Create and flush the transaction self.wait() del CustomAgentTransaction._test access_log = self.docker_client.exec_start( self.docker_client.exec_create(CONTAINER_NAME, 'cat /var/log/squid/access.log')['Id']) self.assertTrue("CONNECT" in access_log) # There should be an entry in the proxy access log self.assertEquals(len(trManager._endpoints_errors), 1) # There should be an error since we gave a bogus api_key
def main(): parse_command_line() flagfile = os.path.join(os.path.dirname(__file__), options.flagfile) parse_config_file(flagfile) settings = dict( login_url='/todo/login', debug=True, template_path=os.path.join(os.path.dirname(__file__), 'templates'), static_path=os.path.join(os.path.dirname(__file__), 'static'), cookie_secret=options.cookie_secret, dropbox_consumer_key=options.dropbox_consumer_key, dropbox_consumer_secret=options.dropbox_consumer_secret, ) #print options.dropbox_consumer_key #print options.dropbox_consumer_secret app = Application([ ('/', RootHandler), ('/todo/?', TodoHandler), ('/todo/add', AddHandler), ('/delete', DeleteHandler), ('/create', CreateHandler), ('/todo/login', DropboxLoginHandler), ('/todo/logout', LogoutHandler), ], **settings) app.listen(options.port,address='127.0.0.1',xheaders=True) IOLoop.instance().start()
def __init__(self): handlers = [ (r"/", IndexHandler), (r"/schedule", ScheduleHandler), (r"/recently", RecentlyViewHandler), (r"/overview", OverViewHandler), (r"/domains", DomainsViewHandler), (r"/details", DomainDetailHandler), ] config = dict( template_path=os.path.join(os.path.dirname(__file__), settings.TEMPLATE_ROOT), static_path=os.path.join(os.path.dirname(__file__), settings.STATIC_ROOT), #xsrf_cookies=True, cookie_secret="__TODO:_E720135A1F2957AFD8EC0E7B51275EA7__", autoescape=None, debug=settings.DEBUG ) Application.__init__(self, handlers, **config) self.rd_main = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=settings.REDIS_DB) self.db = Connection( host=settings.MYSQL_HOST, database=settings.MYSQL_DB, user=settings.MYSQL_USER, password=settings.MYSQL_PASS)
def run(self): loop = IOLoop() app = Application([ (r'/', WsSocketHandler) ]) app.listen(self.port) loop.start()
def __init__(self): settings = load_settings(config) handlers = [ (r'/$', StaticHandler, dict( template_name='index.html', title=settings['site_title'] )), (r'/drag', StaticHandler, dict( template_name='draggable.html', title=settings['site_title'] )), (r'/http', StaticHandler, dict( template_name='httpdemo.html', title=settings['site_title'] )), (r'/demo', HTTPDemoHandler), (r'/demo/quickstart',StaticHandler,dict( template_name='App/demo/quickstart.html' )), (r'/user/list', UserHandler), (r'/user', UserHandler),#post (r'/user/(\w+)', UserHandler),#delete ] self.db = settings['db'] self.dbsync = settings['dbsync'] Application.__init__(self, handlers, **settings)
def __init__(self): settings = { "static_path": os.path.join(os.path.dirname(__file__), "static"), "cookie_secret": COOKIE_KEY, "login_url": "/login", } Application.__init__(self, routes, debug=DEBUG, **settings)
def main(): app = Application([ (r'/', MainHandler), (r'/res', ResourceHandler) ], debug=True, gzip=True, cookie_secret='nice to meet you', template_path='templates', static_path='public', static_url_prefix="/public/"); app.listen(8000) IOLoop.instance().start()
def run(): parser = ArgumentParser() parser.add_argument("-t", "--targets", help="File with 'targetid x y' tuples in range of this rocket launcher") parser.add_argument("-s", "--sites", help="File with site_id and URL") args = parser.parse_args() sites = {} if args.sites: for site_line in open(args.sites).readlines(): site_id, url = site_line.split() sites[site_id] = url targets = {} if args.targets: for person_line in open(args.targets).readlines(): name, site, x, y = person_line.split() targets[name] = sites[site], map(float, (x, y)) config = { 'targets': targets } application = Application([ (r"/fire_at/([^/]*)", TargetHandler, config) ], debug=True) application.listen(6666) print('Listening at http://localhost:6666') IOLoop.instance().start()
def get_app(self): return Application([('/', HelloWorldRequestHandler, dict(protocol="https"))])
def main(): task_id = process.fork_processes(NUM_INDEX_PORTS + NUM_INDEX_PORTS + 1) if task_id == 0: app = Application([ (r"/search", SearchHandler), ]) app.listen(BASE_PORT) print(BASE_PORT) elif task_id <= NUM_INDEX_PORTS: port = BASE_PORT + task_id app = Application([ (r"/index", IndexHandler, dict(port=port)), ]) app.listen(port) else: port = BASE_PORT + task_id app = Application([ (r"/doc", documentHandler, dict(port=port)), ]) app.listen(port) IOLoop.current().start()
from tornado.ioloop import IOLoop from tornado.web import RequestHandler, \ Application class MainHandler(RequestHandler): def get(self): self.write("Hello, world") application = Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8080) IOLoop.instance().start()
'Date': 20190903, 'Value': 15.5 }, { 'Date': 20190826, 'Value': 13.5 }, { 'Date': 20190813, 'Value': 13.5 }, { 'Date': 20190808, 'Value': 15.5 }] } ] } ] } }) if __name__ == "__main__": import tornado from tornado.web import Application, RequestHandler, authenticated from tornado.websocket import WebSocketHandler app = Application(handlers=[(r"/test", QAHqchartDailyHandler), (r"/testk", QAHqchartKlineHandler)], debug=True) app.listen(8029) tornado.ioloop.IOLoop.current().start()
MainHandler.__client_manager.get_client_list( )) # 将已登陆的玩家列表 转成protobuf 数据 self.write_message( b'\x00\x22\x00\x00' + resp.SerializeToString(), binary=True) #将protobuf数据序列化 传给 新登陆的玩家(前端用词数据生成其玩家的模型) Debug.log('get login req from ' + self.__name) MainHandler.__client_manager.send_message_to_all_except_one( self.__name, message) #将自己的登陆信息 传给除自己以外的其他人 except Exception as e: traceback.print_exc() def on_close(self): #玩家退出时执行的回调 rep = MessageLogout() rep.account = self.__name MainHandler.__client_manager.send_message_to_all_except_one( self.__name, b'\x00\x01\x00\x00' + rep.SerializeToString()) MainHandler.__client_manager.remove_client(self.__name) Debug.log('removed: ' + self.__name) Debug.log('remain clients: ' + str(MainHandler.__client_manager.get_client_list())) self.close() if __name__ == '__main__': Application([ ('/', MainHandler), ]).listen(10040) #绑定的服务器端口 IOLoop.instance().start()
self.write(dumps({"url": "https://somefakeurl.com"})) #response = self.processFile(data) #self.replyToClient(response) def replyToClient(self, dataToBeSentToClient): """Sends data back to client in the form of JSON""" data = dumps(dataToBeSentToClient) self.write(data) def processFile(self, fileObj): """Processes file and returns details to send to client""" filename = fileObj.get("filename") fileBody = fileObj.get("body") fileType = fileObj.get("content_type") class basicRequestHandler(RequestHandler): def get(self): self.write("Server is working") if __name__ == "__main__": app = Application([(r"/", basicRequestHandler), (r"/upload", fileUploadHandler)]) print("Now listening on port 8080") PORT = int(os.environ.get("PORT", 8080)) app.listen(PORT) ioloop.IOLoop.current().start()
log.msg('xxxxxxxxx') app_log.warning('ewwwwwwwwwwwwwwwwwww') gen_log.warning('werewrew') gen_log.info('xfsrewrewadf') app_log.debug('ewwwwwwwwwwwwwwwwwww') self.sendLine(b'xxoo') class MyHandler(tornado.web.RequestHandler): def data_received(self, chunk): pass def get(self, *args, **kwargs): print('web') log.msg('fsadf') access_log.info('ekskskkskskskks') app_log.warning('ewwwwwwwwwwwwwwwwwww') gen_log.warning('werewrew') gen_log.info('xfsrewrewadf') self.write('就这么刘') factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(9000, factory) application = Application(handlers=[(r'/', MyHandler, )]) application.listen(8000) IOLoop.current().start()
def get_app(self): return Application([('/', self.__class__.Handler)])
mac = hmac.new(str(GH_SECRET), msg=self.request.body, digestmod=hashlib.sha1) if not hmac.compare_digest(str(mac.hexdigest()), str(signature)): raise HTTPError(403, 'Wrong signature') @gen.coroutine def post(self): yield [self._verify_ip(), self._verify_signature()] # Implement ping event = self.request.headers.get('X-GitHub-Event', 'ping') if event == 'ping': self.write(json.dumps({'msg': 'pong'})) elif event in ['push']: IOLoop.current().spawn_callback(sync_repos) self.set_status(202) self.finish() if __name__ == "__main__": logging.getLogger().setLevel(logging.INFO) handlers = [ (r"/", MainHandler), ] app = Application(handlers) app.listen(5000) IOLoop.current().start()
def get_app(self): return Application([ ("/echo", EchoHandler), ("/typecheck", TypeCheckHandler), ])
def get_app(self): return Application([(r'/', HelloHandler)], )
def get_app(self): return Application(self.get_handlers())
def get_app(self): self.app = Application(urls) return self.app
ip_address, '', 200) else: yield Logconfig.Write_Sys_Log(self, self.username, '系统配置', '时间配置', ip_address, 'reset failed', 400) self.write(json.dumps({"status_code": 400, "res": "reset failed"})) self.set_status(400, '') @tornado.gen.coroutine def get(self): self.set_header("Content-Type", "application/json") str1 = databasetime.GetNow() self.write( json.dumps({ "status_code": 200, "data": str1, "message": "successd" })) self.set_status(200, '') if __name__ == "__main__": app = Application([ (r"/api/policy/SystemConfigHandler", SystemConfigHandler), (r"/api/policy/SystemTime", SystemTimeHandler), ], cookie_secret="12334") app.listen(8000) IOLoop.current().start()
def get_app(self): return Application([('/', TestRequestHandler, dict(io_loop=self.io_loop))])
def __init__(self, base_path="api"): handlers = [(r"/{0}/pastes/(.*)".format(base_path), PasteHandler)] Application.__init__(self, handlers)
class SRWebServer(threading.Thread): def __init__(self, options={}, io_loop=None): threading.Thread.__init__(self) self.daemon = True self.alive = True self.name = "TORNADO" self.io_loop = io_loop or IOLoop.current() self.options = options self.options.setdefault('port', 8081) self.options.setdefault('host', '0.0.0.0') self.options.setdefault('log_dir', None) self.options.setdefault('username', '') self.options.setdefault('password', '') self.options.setdefault('web_root', None) assert isinstance(self.options['port'], int) assert 'data_root' in self.options # video root if sickbeard.ROOT_DIRS: root_dirs = sickbeard.ROOT_DIRS.split('|') self.video_root = root_dirs[int(root_dirs[0]) + 1] else: self.video_root = None # web root self.options['web_root'] = ('/' + self.options['web_root'].lstrip('/')) if self.options[ 'web_root'] else '' # tornado setup self.enable_https = self.options['enable_https'] self.https_cert = self.options['https_cert'] self.https_key = self.options['https_key'] if self.enable_https: # If either the HTTPS certificate or key do not exist, make some self-signed ones. if not (self.https_cert and os.path.exists(self.https_cert)) or not ( self.https_key and os.path.exists(self.https_key)): if not create_https_certificates(self.https_cert, self.https_key): logger.log(u"Unable to create CERT/KEY files, disabling HTTPS") sickbeard.ENABLE_HTTPS = False self.enable_https = False if not (os.path.exists(self.https_cert) and os.path.exists(self.https_key)): logger.log(u"Disabled HTTPS because of missing CERT and KEY files", logger.WARNING) sickbeard.ENABLE_HTTPS = False self.enable_https = False # Load the app self.app = Application([], debug=True, autoreload=False, gzip=True, xheaders=sickbeard.HANDLE_REVERSE_PROXY, cookie_secret='61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=' ) # Main Handler self.app.add_handlers(".*$", [ (r'%s/api/(.*)(/?)' % self.options['web_root'], webapi.Api), (r'%s/(.*)(/?)' % self.options['web_root'], webserve.MainHandler), (r'(.*)', webserve.MainHandler) ]) # Static Path Handler self.app.add_handlers(".*$", [ (r'%s/(favicon\.ico)' % self.options['web_root'], MultiStaticFileHandler, {'paths': [os.path.join(self.options['data_root'], 'images/ico/favicon.ico')]}), (r'%s/%s/(.*)(/?)' % (self.options['web_root'], 'images'), MultiStaticFileHandler, {'paths': [os.path.join(self.options['data_root'], 'images'), os.path.join(sickbeard.CACHE_DIR, 'images')]}), (r'%s/%s/(.*)(/?)' % (self.options['web_root'], 'css'), MultiStaticFileHandler, {'paths': [os.path.join(self.options['data_root'], 'css')]}), (r'%s/%s/(.*)(/?)' % (self.options['web_root'], 'js'), MultiStaticFileHandler, {'paths': [os.path.join(self.options['data_root'], 'js')]}), ]) # Static Videos Path if self.video_root: self.app.add_handlers(".*$", [ (r'%s/%s/(.*)' % (self.options['web_root'], 'videos'), MultiStaticFileHandler, {'paths': [self.video_root]}), ]) def run(self): if self.enable_https: protocol = "https" self.server = HTTPServer(self.app, ssl_options={"certfile": self.https_cert, "keyfile": self.https_key}) else: protocol = "http" self.server = HTTPServer(self.app) logger.log(u"Starting SickBeard on " + protocol + "://" + str(self.options['host']) + ":" + str( self.options['port']) + "/") try: self.server.listen(self.options['port'], self.options['host']) except: etype, evalue, etb = sys.exc_info() logger.log( "Could not start webserver on %s. Excpeption: %s, Error: %s" % (self.options['port'], etype, evalue), logger.ERROR) return try: self.io_loop.start() self.io_loop.close(True) except (IOError, ValueError): # Ignore errors like "ValueError: I/O operation on closed kqueue fd". These might be thrown during a reload. pass def shutDown(self): self.alive = False if self.server: self.server.stop() self.io_loop.stop()
print filename BaseDir = os.path.join(os.getcwd(),'static',filename) with open(BaseDir,'rb') as fr: content = fr.read() if not content: self.write_error(404) else: self.set_header('Content-Type','image/png') self.write(content) #手动结束此次响应 self.finish() app = Application([ (r'^/static/(.*)$',IndexHandler) ]) app.listen(8000) IOLoop.instance().start()
def get_app(self): return Application([('/', HelloWorldRequestHandler)])
def __init__(self, options={}, io_loop=None): threading.Thread.__init__(self) self.daemon = True self.alive = True self.name = "TORNADO" self.io_loop = io_loop or IOLoop.current() self.options = options self.options.setdefault('port', 8081) self.options.setdefault('host', '0.0.0.0') self.options.setdefault('log_dir', None) self.options.setdefault('username', '') self.options.setdefault('password', '') self.options.setdefault('web_root', None) assert isinstance(self.options['port'], int) assert 'data_root' in self.options # video root if sickbeard.ROOT_DIRS: root_dirs = sickbeard.ROOT_DIRS.split('|') self.video_root = root_dirs[int(root_dirs[0]) + 1] else: self.video_root = None # web root self.options['web_root'] = ('/' + self.options['web_root'].lstrip('/')) if self.options[ 'web_root'] else '' # tornado setup self.enable_https = self.options['enable_https'] self.https_cert = self.options['https_cert'] self.https_key = self.options['https_key'] if self.enable_https: # If either the HTTPS certificate or key do not exist, make some self-signed ones. if not (self.https_cert and os.path.exists(self.https_cert)) or not ( self.https_key and os.path.exists(self.https_key)): if not create_https_certificates(self.https_cert, self.https_key): logger.log(u"Unable to create CERT/KEY files, disabling HTTPS") sickbeard.ENABLE_HTTPS = False self.enable_https = False if not (os.path.exists(self.https_cert) and os.path.exists(self.https_key)): logger.log(u"Disabled HTTPS because of missing CERT and KEY files", logger.WARNING) sickbeard.ENABLE_HTTPS = False self.enable_https = False # Load the app self.app = Application([], debug=True, autoreload=False, gzip=True, xheaders=sickbeard.HANDLE_REVERSE_PROXY, cookie_secret='61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=' ) # Main Handler self.app.add_handlers(".*$", [ (r'%s/api/(.*)(/?)' % self.options['web_root'], webapi.Api), (r'%s/(.*)(/?)' % self.options['web_root'], webserve.MainHandler), (r'(.*)', webserve.MainHandler) ]) # Static Path Handler self.app.add_handlers(".*$", [ (r'%s/(favicon\.ico)' % self.options['web_root'], MultiStaticFileHandler, {'paths': [os.path.join(self.options['data_root'], 'images/ico/favicon.ico')]}), (r'%s/%s/(.*)(/?)' % (self.options['web_root'], 'images'), MultiStaticFileHandler, {'paths': [os.path.join(self.options['data_root'], 'images'), os.path.join(sickbeard.CACHE_DIR, 'images')]}), (r'%s/%s/(.*)(/?)' % (self.options['web_root'], 'css'), MultiStaticFileHandler, {'paths': [os.path.join(self.options['data_root'], 'css')]}), (r'%s/%s/(.*)(/?)' % (self.options['web_root'], 'js'), MultiStaticFileHandler, {'paths': [os.path.join(self.options['data_root'], 'js')]}), ]) # Static Videos Path if self.video_root: self.app.add_handlers(".*$", [ (r'%s/%s/(.*)' % (self.options['web_root'], 'videos'), MultiStaticFileHandler, {'paths': [self.video_root]}), ])
def get_app(self): return Application([ ('/echo', EchoHandler), ])
import os from tornado.ioloop import IOLoop from sockets.websocket import WebSocket from tornado.web import Application if __name__ == '__main__': print("PYTHONPATH: {}".format(os.environ['PYTHONPATH'])) server = Application([(r'/websocket/', WebSocket)]) print("Running server on port 5000!") server.listen(5000) IOLoop.instance().start()
'shorturls': shorturls, 'adminuser': ADMIN_USER, 'self_hostnames': SELF_HOSTNAMES, 'debug': True, # TODO(sudhakar.bg): Investigate feasibility of generating runtime cookie_secret 'cookie_secret': cookie_secret, 'sso_endpoint': SSO_ENDPOINT } # Register URL handlers with the application app = Application([ (r'^/$', Root), (r'^/(favicon\.ico)', StaticFileHandler, {'path': '/opt/inmobi/irs/static/'}), (r'^/_app/login$', LoginAuth), (r'^/_app/logout$', LogoutAuth), (r'^/_app/server-status$', ServerStatus), (r'^/_app/.*$', App), (r'^/_app$', App), (r'^/.+$', Redirect) ], **settings) # We redirect app requests (including auth) back over SSL. # Normal URL redirect requests don't require auth and are served # over plain HTTP. app_insecure = Application([ (r'^/$', Root), (r'^/(favicon\.ico)', StaticFileHandler, {'path': '/opt/inmobi/irs/static/'}), (r'^/_app/login$', LoginAuth), (r'^/_app/logout$', LogoutAuth), (r'^/_app/server-status$', ServerStatus), (r'^/_app/.*$', App),
def get_app(self): return Application([('/', XHeaderTest.Handler)])
app = Application( # URL handler mappings urls, # Randomly generated secret key cookie_secret=get_cookie_secret(), # Ip addresses that access the admin interface admin_ips=options.admin_ips, # Template directory template_path="templates/", # Request that does not pass @authorized will be # redirected here forbidden_url="/403", # Requests that does not pass @authenticated will be # redirected here login_url="/login", # UI Modules ui_modules={ "Menu": Menu, "Theme": AppTheme, "Recaptcha": Recaptcha }, # Enable XSRF protected forms; not optional xsrf_cookies=True, # Anti-bruteforce automatic_ban=False, blacklist_threshold=10, blacklisted_ips=[], failed_logins={}, # Debug mode debug=options.debug, # Flags used to run the game game_started=options.autostart_game, suspend_registration=False, freeze_scoreboard=False, temp_global_notifications=None, # Callback functions score_bots_callback=PeriodicCallback(score_bots, options.bot_reward_interval), history_callback=PeriodicCallback(game_history.take_snapshot, options.history_snapshot_interval), # Scoreboard Hightlights scoreboard_history={}, # Application version version=__version__, )
"routes": self.routes }) if __name__ == "__main__": parser = argparse.ArgumentParser( sys.argv[0], formatter_class=argparse.RawTextHelpFormatter, description="OOB handler" ) parser.add_argument('-p', '--port', type=int, required=False, default=31337, help="Port to listen on") parser.add_argument('-d', '--domain', type=str, required=True, help="Domain name to use in payloads. Specify protocol and port if it isn't default") args = parser.parse_args() routes = [ (r'/dtd', PayloadDTDQueryHandler, dict(hostname=args.domain)), (r'/payload', PayloadVanialaQueryHandler, dict(hostname=args.domain)), (r'/exfil/(.*)', ExfiltrateHandler, dict(hostname=args.domain)) ] app = Application(routes, template_path='templates') app.add_handlers(r'.*', [ (r'/help', HelpHandler, dict(hostname=args.domain, routes=routes)) ]) app.listen(args.port) ioloop.IOLoop.current().start()
class Server(): def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False, logConf=None): self._configfile = configfile self._basedir = basedir self._host = host self._port = port self._debug = debug self._allowRoot = allowRoot self._logConf = logConf self._ioLoop = None def stop(self): if self._ioLoop: self._ioLoop.stop() self._ioLoop = None def run(self): if not self._allowRoot: self._checkForRoot() global userManager global eventManager global loginManager global debug global softwareManager global discoveryManager global VERSION global UI_API_KEY from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application, FallbackHandler from astroprint.printfiles.watchdogs import UploadCleanupWatchdogHandler debug = self._debug # first initialize the settings singleton and make sure it uses given configfile and basedir if available self._initSettings(self._configfile, self._basedir) s = settings() if not s.getBoolean(['api', 'regenerate']) and s.getString( ['api', 'key']): UI_API_KEY = s.getString(['api', 'key']) else: UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes) # then initialize logging self._initLogging(self._debug, self._logConf) logger = logging.getLogger(__name__) if s.getBoolean(["accessControl", "enabled"]): userManagerName = s.get(["accessControl", "userManager"]) try: clazz = util.getClass(userManagerName) userManager = clazz() except AttributeError, e: logger.exception( "Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName) softwareManager = swManager() VERSION = softwareManager.versionString logger.info("Starting AstroBox (%s) - Commit (%s)" % (VERSION, softwareManager.commit)) from astroprint.migration import migrateSettings migrateSettings() eventManager = events.eventManager() printer = printerManager(printerProfileManager().data['driver']) #Start some of the managers here to make sure there are no thread collisions from astroprint.network.manager import networkManager from astroprint.boxrouter import boxrouterManager networkManager() boxrouterManager() # configure timelapse #octoprint.timelapse.configureTimelapse() app.wsgi_app = ReverseProxied(app.wsgi_app) app.secret_key = boxrouterManager().boxId loginManager = LoginManager() loginManager.session_protection = "strong" loginManager.user_callback = load_user if userManager is None: loginManager.anonymous_user = users.DummyUser principals.identity_loaders.appendleft(users.dummy_identity_loader) loginManager.init_app(app) # setup command triggers events.CommandTrigger(printer) if self._debug: events.DebugEventListener() if networkManager().isOnline(): softwareManager.checkForcedUpdate() if self._host is None: self._host = s.get(["server", "host"]) if self._port is None: self._port = s.getInt(["server", "port"]) app.debug = self._debug from octoprint.server.api import api app.register_blueprint(api, url_prefix="/api") boxrouterManager( ) # Makes sure the singleton is created here. It doesn't need to be stored self._router = SockJSRouter(self._createSocketConnection, "/sockjs") discoveryManager = DiscoveryManager() def access_validation_factory(validator): """ Creates an access validation wrapper using the supplied validator. :param validator: the access validator to use inside the validation wrapper :return: an access validation wrapper taking a request as parameter and performing the request validation """ def f(request): """ Creates a custom wsgi and Flask request context in order to be able to process user information stored in the current session. :param request: The Tornado request for which to create the environment and context """ wsgi_environ = tornado.wsgi.WSGIContainer.environ(request) with app.request_context(wsgi_environ): app.session_interface.open_session(app, request) loginManager.reload_user() validator(request) return f self._tornado_app = Application(self._router.urls + [ #(r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {"path": s.getBaseFolder("timelapse"), "as_attachment": True}), (r"/downloads/files/local/([^/]*\.(gco|gcode))", LargeResponseHandler, { "path": s.getBaseFolder("uploads"), "as_attachment": True }), (r"/downloads/logs/([^/]*)", LargeResponseHandler, { "path": s.getBaseFolder("logs"), "as_attachment": True, "access_validation": access_validation_factory(admin_validator) }), #(r"/downloads/camera/current", UrlForwardHandler, {"url": s.get(["webcam", "snapshot"]), "as_attachment": True, "access_validation": access_validation_factory(user_validator)}), (r".*", FallbackHandler, { "fallback": WSGIContainer(app.wsgi_app) }) ]) self._server = HTTPServer(self._tornado_app, max_buffer_size=1048576 * s.getInt(['server', 'maxUploadSize'])) self._server.listen(self._port, address=self._host) logger.info("Listening on http://%s:%d" % (self._host, self._port)) eventManager.fire(events.Events.STARTUP) if s.getBoolean(["serial", "autoconnect"]): (port, baudrate) = s.get(["serial", "port" ]), s.getInt(["serial", "baudrate"]) connectionOptions = printer.getConnectionOptions() if port in connectionOptions["ports"]: printer.connect(port, baudrate) # start up watchdogs observer = Observer() observer.schedule(UploadCleanupWatchdogHandler(), s.getBaseFolder("uploads")) observer.start() try: self._ioLoop = IOLoop.instance() self._ioLoop.start() except SystemExit: pass except: logger.fatal( "Please report this including the stacktrace below in AstroPrint's bugtracker. Thanks!" ) logger.exception("Stacktrace follows:") finally: observer.stop() self.cleanup() observer.join() logger.info('Good Bye!')
def testEndpoints(self): """ Tests that the logic behind the agent version specific endpoints is ok. Also tests that these endpoints actually exist. """ MetricTransaction._endpoints = [] api_key = "a" * 32 config = { "endpoints": { "https://app.datadoghq.com": [api_key] }, "dd_url": "https://app.datadoghq.com", "api_key": api_key, "use_dd": True } app = Application() app.skip_ssl_validation = False app._agentConfig = config app.use_simple_http_client = True trManager = TransactionManager(timedelta(seconds=0), MAX_QUEUE_SIZE, THROTTLING_DELAY, max_endpoint_errors=100) trManager._flush_without_ioloop = True # Use blocking API to emulate tornado ioloop MetricTransaction._trManager = trManager MetricTransaction.set_application(app) MetricTransaction.set_endpoints(config['endpoints']) transaction = MetricTransaction(None, {}, "") endpoints = [] for endpoint in transaction._endpoints: for api_key in transaction._endpoints[endpoint]: endpoints.append(transaction.get_url(endpoint, api_key)) expected = [ 'https://{0}-app.agent.datadoghq.com/intake/?api_key={1}'.format( get_version().replace(".", "-"), api_key) ] self.assertEqual(endpoints, expected, (endpoints, expected)) for url in endpoints: r = requests.post(url, data=json.dumps({"foo": "bar"}), headers={'Content-Type': "application/json"}) r.raise_for_status() # API Metric Transaction transaction = APIMetricTransaction(None, {}) endpoints = [] for endpoint in transaction._endpoints: for api_key in transaction._endpoints[endpoint]: endpoints.append(transaction.get_url(endpoint, api_key)) expected = [ 'https://{0}-app.agent.datadoghq.com/api/v1/series/?api_key={1}'. format(get_version().replace(".", "-"), api_key) ] self.assertEqual(endpoints, expected, (endpoints, expected)) for url in endpoints: r = requests.post(url, data=json.dumps({"foo": "bar"}), headers={'Content-Type': "application/json"}) r.raise_for_status() # API Service Check Transaction APIServiceCheckTransaction._trManager = trManager APIServiceCheckTransaction.set_application(app) APIServiceCheckTransaction.set_endpoints(config['endpoints']) transaction = APIServiceCheckTransaction(None, {}) endpoints = [] for endpoint in transaction._endpoints: for api_key in transaction._endpoints[endpoint]: endpoints.append(transaction.get_url(endpoint, api_key)) expected = [ 'https://{0}-app.agent.datadoghq.com/api/v1/check_run/?api_key={1}' .format(get_version().replace(".", "-"), api_key) ] self.assertEqual(endpoints, expected, (endpoints, expected)) for url in endpoints: r = requests.post(url, data=json.dumps({ 'check': 'test', 'status': 0 }), headers={'Content-Type': "application/json"}) r.raise_for_status()
def handle_shutdown(*arg, **kwargs): IOLoop.instance().stop() if __name__ == "__main__": backend = RosBackend.get_instance(shutdown_hook=handle_shutdown) signal.signal(signal.SIGINT, handle_shutdown) signal.signal(signal.SIGQUIT, handle_shutdown) # SIGQUIT is send by our supervisord to stop this server. signal.signal(signal.SIGTERM, handle_shutdown) # SIGTERM is send by Ctrl+C or supervisord's default. print "Shutdown handler connected" app = Application([ (r"/ws", MessageForwarder, {'backend': backend}), (r'/', ChallengeHandler, {'backend': backend}), (r'/command', CommandReceiver, {'backend': backend}), (r'/static/(.*)', StaticFileHandler, {'path': 'static/'})], (r'/(favicon\.ico)', StaticFileHandler, {'path': 'static/favicon.ico'}), debug=True, template_path="templates") address, port = "localhost", 8888 print "Application instantiated" connected = False while not connected: try: print "Listening..." app.listen(port, address) print "Listening on http://{addr}:{port}".format(addr=address, port=port) connected = True except error as ex:
def post(self): fName = self.get_argument("firstname") lName = self.get_argument("lastname") user_d = self.data.find().sort([("id", -1)]).next() id = user_d["id"] + 1 user_data = {"id": id, "fName": fName, "lName": lName} self.data.insert_one(user_data) self.redirect("/users") if __name__ == '__main__': cursor = MongoClient('mongodb://localhost:27017') settings = { "cookie_secret": "asildh#osafo/awdEEWIFaesRwkW=", "login_url": "/login", "db": cursor['test'], "xsrf_form_html": True, "xsrf_cookies": True } application = Application([ tornado.web.url(r"/", BaseHandler, name="home"), tornado.web.url(r"/signup", SignUpHandler, name="signup"), tornado.web.url(r"/login", LoginHandler, name="login"), tornado.web.url(r"/logout", LogoutHandler, name="logout"), tornado.web.url(r"/users", NonIdHandler, name="main"), ], **settings) application.listen(options.port) print("Listening on port {}".format(options.port)) IOLoop.current().start()