def getWebApplication(): routes = [ URLSpec(r"/", RootHandler), URLSpec(r"/async", AsyncHandler), URLSpec(r"/sync", RootHandler) ] return Application(routes, debug=True)
def make_app(debug=False): es = elasticsearch.Elasticsearch( os.environ['ELASTICSEARCH_HOSTS'].split(',') ) redis_client = redis.Redis(host=os.environ['REDIS_HOST']) lazo_client = lazo_index_service.LazoIndexClient( host=os.environ['LAZO_SERVER_HOST'], port=int(os.environ['LAZO_SERVER_PORT']) ) return Application( [ URLSpec('/profile', Profile, name='profile'), URLSpec('/search', Search, name='search'), URLSpec('/download/([^/]+)', DownloadId, name='download_id'), URLSpec('/download', Download, name='download'), URLSpec('/metadata/([^/]+)', Metadata, name='metadata'), URLSpec('/augment', Augment, name='augment'), URLSpec('/upload', Upload, name='upload'), URLSpec('/statistics', Statistics, name='statistics'), URLSpec('/version', Version, name='version'), URLSpec('/health', Health, name='health'), ], debug=debug, es=es, redis_client=redis_client, lazo=lazo_client )
def make_app(cls, **settings): return GracefulApplication( [ ( IsKubernetesProbe(), [ URLSpec('/health', Health), ], ), URLSpec('.*', cls), ], **settings, )
def main(args): log.basicConfig(format='%(asctime)s %(levelname)s: %(message)s') if args.verbosity >= len(LOG_LEVELS): log.error("Verbosity must be 0 <= n < %d" % len(LOG_LEVELS)) return 1 log.getLogger().setLevel(LOG_LEVELS[args.verbosity]) fonts = _collect_fonts() if not fonts: log.error( "no font files found; did you forget to run update-fonts.sh?") return 1 recaptcha_settings = _load_recaptcha_settings( ) if not args.no_recaptcha else False if not recaptcha_settings: logfun = log.warning if recaptcha_settings is None else log.info logfun("reCAPTCHA is disabled") cookie_secret = str(uuid4()) app_settings = { "autoreload": args.debug, "debug": args.debug, "template_path": TEMPLATES_DIR, "fonts": fonts, "font_names": sorted(fonts.keys()), "recaptcha": recaptcha_settings, "static_path": STATIC_DIR, "cookie_secret": cookie_secret, "xsrf_cookies": True, } routes = [ URLSpec(r"/?", MainHandler), ] if args.debug: log.debug("debug mode enabled") routes.append(URLSpec(r"/%s/(.*)" % STATIC_DIR, StaticFileHandler)) server_settings = {} if not args.no_ssl: server_settings["ssl_options"] = SSL_OPTIONS else: log.info("SSL is disabled") http_server = HTTPServer(Application(routes, **app_settings), **server_settings) http_server.listen(args.port, args.host) log.info("listening on %s:%d..." % (args.host, args.port)) try: IOLoop.instance().start() except KeyboardInterrupt: log.info("interrupted by user; bye!") return 0
def make_app(cls, **settings): return tornado.web.Application( [ URLSpec('.*', cls), ], **settings, )
def make_app(debug=False): es = elasticsearch.Elasticsearch( os.environ['ELASTICSEARCH_HOSTS'].split(',')) redis_client = redis.Redis(host=os.environ['REDIS_HOST']) lazo_client = lazo_index_service.LazoIndexClient( host=os.environ['LAZO_SERVER_HOST'], port=int(os.environ['LAZO_SERVER_PORT'])) return Application( [ ApiRule('/profile', '1', Profile), ApiRule('/search', '1', Search), ApiRule('/download/([^/]+)', '1', DownloadId), ApiRule('/download', '1', Download), ApiRule('/metadata/([^/]+)', '1', Metadata), ApiRule('/augment', '1', Augment), ApiRule('/augment/([^/]+)', '1', AugmentResult), ApiRule('/upload', '1', Upload), ApiRule('/session/new', '1', SessionNew), ApiRule('/session/([^/]+)', '1', SessionGet), ApiRule('/location', '1', LocationSearch), ApiRule('/statistics', '1', Statistics), ApiRule('/version', '1', Version), URLSpec('/health', Health), ], debug=debug, es=es, redis_client=redis_client, lazo=lazo_client, default_handler_class=CustomErrorHandler, default_handler_args={"status_code": 404}, )
def make_app(debug=False): if 'XDG_CACHE_HOME' in os.environ: cache = os.environ['XDG_CACHE_HOME'] else: cache = os.path.expanduser('~/.cache') os.makedirs(cache, 0o700, exist_ok=True) cache = os.path.join(cache, 'datamart.json') secret = None try: fp = open(cache) except IOError: pass else: try: secret = json.load(fp)['cookie_secret'] fp.close() except Exception: logger.exception("Couldn't load cookie secret from cache file") if not isinstance(secret, str) or not 10 <= len(secret) < 2048: logger.error("Invalid cookie secret in cache file") secret = None if secret is None: secret = os.urandom(30).decode('iso-8859-15') try: with open(cache, 'w') as fp: json.dump({'cookie_secret': secret}, fp) except IOError: logger.error("Couldn't open cache file, cookie secret won't be " "persisted! Users will be logged out if you restart " "the program.") es = elasticsearch.Elasticsearch( os.environ['ELASTICSEARCH_HOSTS'].split(',')) return Application( [ URLSpec('/api/statistics', Statistics), URLSpec('/', Index, name='index'), ], static_path=pkg_resources.resource_filename('coordinator', 'static'), debug=debug, cookie_secret=secret, es=es, default_handler_class=CustomErrorHandler, default_handler_args={"status_code": 404}, )
def main(): app = tornado.web.Application([ (r'^/$', IndexHandler), (r'^/red/$', tornado.web.RedirectHandler, {'url': 'https://www.taobao.com'}), URLSpec(r'^/fix$', IndexHandler, name='index'), (r'^/reverse/$', ReverseHandler), ]) app.listen(8888) tornado.ioloop.IOLoop.current().start()
def make_app(): return tornado.web.Application([ (r'^/$', IndexHandler), # 3.系统自带重定向 (r'^/red/$', RedirectHandler, { "url": "https://www.baidu.com" }), # 通过name="hahaha"找到 IndexHandler视图类 URLSpec(r'^/dfhfdgsjdfvbjhdbvdfnb/$', IndexHandler, name="hahaha"), # 设置逆向路由的视图类 (r'^/reverse/$', ReverseHandler), ])
def make_app(debug=False, xsrf_cookies=True, proxy=None): if proxy is not None: proxy = [ URLSpec('/results/(?:[^/]+)/port/(?:[0-9]+)(?:/.*)?', proxy, name='proxy'), ] else: proxy = [] return Application( [ URLSpec('/', views.Index, name='index'), URLSpec('/upload', views.Upload, name='upload'), URLSpec('/reproduce/([^/]+)/(.+)', views.ReproduceRepo, name='reproduce_repo'), URLSpec('/reproduce/([^/]+)', views.ReproduceLocal, name='reproduce_local'), URLSpec('/run/([^/]+)', views.StartRun, name='start_run'), URLSpec('/results/([^/]+)', views.Results, name='results'), URLSpec('/results/([^/]+)/json', views.ResultsJson, name='results_json'), ] + proxy + [ URLSpec('/about', views.About, name='about'), URLSpec('/data', views.Data, name='data'), URLSpec('/health', views.Health, name='health'), URLSpec('/runners/run/([^/]+)/init', api.InitRunGetInfo), URLSpec('/runners/run/([^/]+)/start', api.RunStarted), URLSpec('/runners/run/([^/]+)/done', api.RunDone), URLSpec('/runners/run/([^/]+)/failed', api.RunFailed), URLSpec('/runners/run/([^/]+)/output/(.+)', api.UploadOutput), URLSpec('/runners/run/([^/]+)/log', api.Log), ], static_path=pkg_resources.resource_filename('reproserver', 'static'), xsrf_cookies=xsrf_cookies, debug=debug, connection_token=os.environ.get('CONNECTION_TOKEN', ''), )
from tornado.web import RedirectHandler from tornado.routing import URLSpec class IndexHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): # 302重定向 # self.redirect('https://www.baidu.com') self.set_status(302) self.set_header('Location', 'https://www.jd.com') class ReverseHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.redirect(self.reverse_url('index')) app = tornado.web.Application([ (r'^/$', IndexHandler), (r'^/red/$', RedirectHandler, { 'url': 'https://www.taobao.com' }), URLSpec(r'^/fdsafdslajjflds$', IndexHandler, name='index'), (r'^/reverse/$', ReverseHandler), ]) app.listen(8000) tornado.ioloop.IOLoop.instance().start()
def make_app(config, debug=False, xsrf_cookies=True): return Application( [ # Basic pages URLSpec('/', views.Index, name='index'), URLSpec('/cookies', views.CookiesPrompt, name='cookies_prompt'), URLSpec('/login', views.Login, name='login'), URLSpec('/logout', views.Logout, name='logout'), URLSpec('/register', views.Register, name='register'), URLSpec('/account', views.Account, name='account'), URLSpec('/reset_password', views.AskResetPassword, name='reset_password'), URLSpec('/new_password', views.SetNewPassword, name='new_password'), URLSpec('/project/new', views.ProjectAdd, name='new_project'), URLSpec('/project/([0-9]+)/delete', views.ProjectDelete, name='delete_project'), # Project view URLSpec('/project/([0-9]+)', views.Project, name='project'), URLSpec('/project/([0-9]+)/document/[0-9]+', views.Project, name='project_doc'), URLSpec('/project/([0-9]+)/highlights/.*', views.Project, name='project_tag'), # Export options URLSpec('/project/([0-9]+)/export/codebook\\.qdc', export.ExportCodebookXml, name='export_codebook_qdc'), URLSpec('/project/([0-9]+)/export/codebook\\.csv', export.ExportCodebookCsv, name='export_codebook_csv'), URLSpec('/project/([0-9]+)/export/codebook\\.xlsx', export.ExportCodebookXlsx, name='export_codebook_xlsx'), URLSpec('/project/([0-9]+)/export/codebook\\.([a-z0-3]{2,4})', export.ExportCodebookDoc, name='export_codebook_doc'), URLSpec( '/project/([0-9]+)/export/document/' '([^/]+)\\.([a-z0-9]{2,4})', export.ExportDocument, name='export_document'), URLSpec( '/project/([0-9]+)/export/highlights/' '(.*)\\.([a-z0-3]{2,4})', export.ExportHighlightsDoc, name='export_highlights_doc'), # API URLSpec('/api/check_user', api.CheckUser), URLSpec('/api/project/([0-9]+)', api.ProjectMeta), URLSpec('/api/project/([0-9]+)/document/new', api.DocumentAdd), URLSpec('/api/project/([0-9]+)/document/([0-9]+)', api.DocumentUpdate), URLSpec('/api/project/([0-9]+)/document/([0-9]+)/content', api.DocumentContents), URLSpec('/api/project/([0-9]+)/document/([0-9]+)/highlight/new', api.HighlightAdd), URLSpec( '/api/project/([0-9]+)/document/([0-9]+)/highlight/([0-9]+)', api.HighlightUpdate), URLSpec('/api/project/([0-9]+)/highlights/(.*)', api.Highlights), URLSpec('/api/project/([0-9]+)/tag/new', api.TagAdd), URLSpec('/api/project/([0-9]+)/tag/([0-9]+)', api.TagUpdate), URLSpec('/api/project/([0-9]+)/tag/merge', api.TagMerge), URLSpec('/api/project/([0-9]+)/members', api.MembersUpdate), URLSpec('/api/project/([0-9]+)/events', api.ProjectEvents), # Translation catalog and functions URLSpec('/trans.js', TranslationJs, name='trans.js'), # Messages URLSpec('/messages.js', MessagesJs, name='messages.js'), # Well-known URLs URLSpec('/.well-known/change-password', RedirectAccount), ], static_path=pkg_resources.resource_filename('taguette', 'static'), login_url='/login', xsrf_cookies=xsrf_cookies, debug=debug, config=config, )
if platform.system() == "Windows": import asyncio asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) class IndexHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): # 默认302 的重定向 # self.redirect('http://www.google.com') self.set_status(302) self.set_header('Location', 'https://www.pornhub.com') self.redirect(self.reverse_url('index')) class ReverseHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.redirect(self.reverse_url('index')) if __name__ == '__main__': app = tornado.web.Application([(r'^/$', IndexHandler), (r'^/red/$', RedirectHandler, { 'url': 'https://www.taobao.com' }), URLSpec(r'^/asdfasdfasdf$', IndexHandler, name='index'), (r'^/reverse/$', ReverseHandler)]) app.listen(9999) tornado.ioloop.IOLoop.current().start()
# 重定向的三种方式 class IndexHandler(RequestHandler): def get(self): pass # 方法1 默认302重定向 # self.redirect('https://www.baidu.com') # 方法2 self.set_status(302) self.set_header('Location', 'https://www.jd.com') class LoginHandler(RequestHandler): def get(self): self.redirect(self.reverse_url('index')) app = Application([ (r'^/$', IndexHandler), # 方法3 (r'^/redirect/$', RedirectHandler, { 'url': 'https://www.taobao.com' }), (r'^/login/$', LoginHandler), URLSpec(R'^/index/$', IndexHandler, name='index') ]) app.listen(8888) IOLoop.instance().start()