def start_server(prefix='', port=8888): if prefix: path = '/' + prefix + '/(.*)' else: path = '/(.*)' file_app = tornado.web.Application([ (path, FileHandler, {'path': os.getcwd()}), ], debug=True) folder_app = tornado.web.Application([ (path, FolderHandler), ], debug=True) router = RuleRouter([ Rule(File_matcher(), file_app), Rule(Folder_matcher(), folder_app) ]) # router = RuleRouter([ # Rule(PathMatches("/app1.*"), file_app), # Rule(PathMatches("/app2.*"), folder_app) # ]) server = HTTPServer(router) server.listen(port) IOLoop.current().start()
def make(): """ Make the Tornado `RuleRouter`. """ # API v1 endpoints v1_app = Application([ (r'^/?(?P<environs>.*?)/v1/manifest/?', ManifestHandler), (r'^.*?/v1/environs/(?P<environ_id>.+)', EnvironHandler), (r'^.*?/v1/proxy/(?P<binder_id>[^@]+)\@(?P<token>[^\/]+)/(?P<path>.+)', ProxyHandler) ]) # API v0 endpoints v0_app = Application([ (r'^/?(?P<environs>.*?)/v0/manifest/?', ManifestHandler), (r'^.*?/v0/environ/(?P<environ_id>.+)', EnvironHandler), (r'^.*?/v0/proxy/(?P<binder_id>[^@]+)\@(?P<token>[^\/]+)/(?P<path>.+)', ProxyHandler) ]) index_app = Application([(r'^/', IndexHandler)]) return RuleRouter([ Rule(PathMatches(r'^.*?/v1/.*'), v1_app), Rule(PathMatches(r'^.*?/v0/.*'), v0_app), Rule(PathMatches(r'^/$'), index_app) ])
def get_app(self): app = Application() def request_callable(request): request.connection.write_headers( ResponseStartLine("HTTP/1.1", 200, "OK"), HTTPHeaders({"Content-Length": "2"})) request.connection.write(b"OK") request.connection.finish() router = CustomRouter() router.add_routes({ "/nested_handler": (app, _get_named_handler("nested_handler")) }) app.add_handlers(".*", [ (HostMatches("www.example.com"), [ (PathMatches("/first_handler"), "tornado.test.routing_test.SecondHandler", {}, "second_handler") ]), Rule(PathMatches("/.*handler"), router), Rule(PathMatches("/first_handler"), FirstHandler, name="first_handler"), Rule(PathMatches("/request_callable"), request_callable), ("/connection_delegate", ConnectionDelegate()) ]) return app
def make_router(): from source.payment.cmb import cmb_app from source.tasks import tasks_app cmb_router = RuleRouter([ Rule(PathMatches('/cmb/.*'), cmb_app), Rule(PathMatches('/tasks/.*'), tasks_app), ]) return cmb_router
def _build_routing(self, routing): from tornado.routing import Rule, AnyMatches, PathMatches routes = [ Rule(PathMatches(route), _RestApplicationRouter(self, subRoutes)) for route, subRoutes in routing.items() ] routes.append(Rule(AnyMatches(), self.wildcard_router)) self.default_router = _RestApplicationRouter(self, routes) self._build_reverse_routing()
def __post_init__(self, ssl_certificate_path, ssl_private_key_path): if (self.logger_name is None): self.logger_name = f'{self.application.logger_name}.{self.name}' self.initialize_logger() self.settings = self._get_settings() self.ssl_options = self._get_ssl(ssl_certificate_path, ssl_private_key_path) if (self.protocol is None): self.protocol = 'https' if (self.ssl_enabled) else 'http' if (self.port is None): self.port = 443 if (self.ssl_enabled) else 80 if (self.address is None): self.address = self._get_address() if (self.pattern is None): self.pattern = re.escape(self.bind_address) if (self.matcher is None): self.matcher = HostMatches( self.pattern) if (self.pattern) else StrictHostMatches( protocol=self.protocol, port=self.port) if (self.router is None): params = dict() if (issubclass(self.router_class, IRouter)): params['owner'] = self # noinspection PyArgumentList self.router = self.router_class(self.application, **params) if (self.rule is None): self.rule = Rule(self.matcher, target=self.router, name=f"Host:{self.name}")
def add_handler(self, pattern: str, target: Any, target_params: Optional[Dict[str, Any]]) -> None: if pattern in self.pattern_to_rule: self.remove_handler(pattern) new_rule = Rule(PathMatches(pattern), target, target_params) self.pattern_to_rule[pattern] = new_rule self.rules.append(new_rule)
def make_app(root_dir): rules = [ Rule(PathMatches(r'/(.*)'), SaveHandler, target_kwargs={'root_dir': root_dir}) ] return Application(rules)
def make_router(routing_table): """Resolves a uri to the Story and line number to execute.""" method_rules = [] for method, routes in routing_table.items(): rules = [ Rule( PathMatches(route.endpoint), CustomRouter(route.filename, route.linenum) ) for route in routes ] # create a new rule by method mapping to many rule by path method_rules.append(Rule(MethodMatches(method), RuleRouter(rules))) router = RuleRouter(method_rules) return router
def main(): IOLoop.configure('tornado.platform.asyncio.AsyncIOLoop') router = RuleRouter([Rule(PathMatches(r"/.*"), MyApplication())]) server = HTTPServer(router, ssl_options={ "certfile": str(cert), "keyfile": str(key), }) server.listen(443) IOLoop.instance().start()
def _rebuild(self): """Resolves a uri to the Story and line number to execute.""" method_rules = [] for method, routes in self._cache.items(): rules = [ Rule(HostAndPathMatches(route.host, route.path), CustomRouter(route.endpoint)) for route in routes ] # create a new rule by method mapping to many rule by path method_rules.append(Rule(MethodMatches(method), RuleRouter(rules))) # replace rules self.rules = method_rules # save route to file with open(self.routes_file, 'wb') as file: # [TODO] only works for one server pickle.dump(self._cache, file)
def get_app(self): app = Application() def request_callable(request): request.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK") request.finish() app.add_handlers( ".*", [(HostMatches("www.example.com"), [ (PathMatches("/first_handler"), "tornado.test.routing_test.SecondHandler", {}, "second_handler") ]), Rule(PathMatches("/first_handler"), FirstHandler, name="first_handler"), Rule(PathMatches("/request_callable"), request_callable), ("/connection_delegate", ConnectionDelegate())]) return app
def main(): rules = [] for i, appName in enumerate(supportedApps): app = handlers[i].get_app() rules.append(Rule(PathMatches("/%s.*" % appName), app)) # Default app settings = dict(template_path="html", static_path="static", debug=True) app = tornado.web.Application([ (r"/(.*)", DefaultHandler), (r'/favicon.ico', tornado.web.StaticFileHandler), (r'/static/', tornado.web.StaticFileHandler), ], **settings) rules.append(Rule(PathMatches(r"/.*"), app)) router = RuleRouter(rules) http_server = tornado.httpserver.HTTPServer(router) port = int(os.environ.get("PORT", 5000)) http_server.listen(port) tornado.ioloop.IOLoop.instance().start()
def load_jupyter_server_extension(mfapp): """ Called during notebook start """ resuseconfig = ResourceUseDisplay(parent=mfapp) mfapp.web_app.settings['gdadorn_display_config'] = resuseconfig route_pattern = url_path_join(mfapp.web_app.settings['base_url'], '/metrics') mfapp.web_app.add_handlers('.*', [(route_pattern, MetricsHandler)]) rules = mfapp.web_app.wildcard_router.rules index = 0 for rule in rules: if rule.target == AuthenticatedFileHandler: mfapp.web_app.wildcard_router.rules = [ Rule(rule.matcher, DownLoadLimitHandler, rule.target_kwargs, rule.name) ] + mfapp.web_app.wildcard_router.rules if rule.target == ContentsHandler: mfapp.web_app.wildcard_router.rules[index] = Rule( rule.matcher, ContentsMonitorHandler, rule.target_kwargs, rule.name) index = index + 1
def _build_router_rules(self): """ Builds the router rules. Each service is registered to the path configured in the Service object. Rules are created for both http and websocket routers and set to the rules objects of the router. """ self.logger.debug(messages.ROUTER_BUILD_ROUTER_RULES) http_rules = [] websocket_rules = [] for name in sorted(self._services): service = self._services[name] path = '/{}/.*'.format(service.path) self.logger.debug( messages.ROUTER_BUILD_ROUTER_RULES_ADD_SERVICE.format( service.name, path)) http_rules.append(Rule(PathMatches(path), service.http_router)) websocket_rules.append( Rule(PathMatches(path), service.websocket_router)) self._http_router_rules = http_rules self._websocket_router_rules = websocket_rules
def _load_application(self): """ """ if settings.translation: try: from tornado import locale locale.load_translations(settings.translations_dir) except: warnings.warn( 'locale dir load failure,maybe your config file is not set correctly.' ) apps = settings.INSTALLED_APPS if not apps: raise ConfigError('settings.INSTALLED_APPS is empty') handlers = [] for app_name in apps: handlers += get_handlers(app_name) app = self._install_application(handlers) self.router = RuleRouter([Rule(PathMatches('/.*'), app)])
def main(): # tornado.options.parse_command_line() settings = {"debug": "debug"} '''路由配置url——处理类''' api = Application([ (r"/test/user", QueryUserHandler), (r"/test/user/save", SaveUserHandler), ], **settings) router = RuleRouter([ Rule(AnyMatches(), api), ]) http_server = tornado.httpserver.HTTPServer(router) http_server.listen(options.port) t = threading.Thread() t.setDaemon(True) t.start() tornado.ioloop.IOLoop.instance().start() t.join()
def add_prefix_to_handlers(prefix, auth_dict, handlers): login_url = "/login" if prefix == '/': return login_url, handlers prefix = prefix.rstrip('/') login_url = '{}/{}'.format(prefix, login_url.lstrip('/')) for i in range(len(handlers)): hdl = handlers[i] if isinstance(hdl, Rule): # log.debug(hdl.matcher.regex.pattern) ptn = '{}/{}'.format(prefix, hdl.matcher.regex.pattern.lstrip('/')) tgt = hdl.target kwargs = hdl.target_kwargs name = hdl.name hdl = Rule(PathMatches(ptn), tgt, kwargs, name) # log.debug(" routing %s to %s", hdl.matcher.regex.pattern, tgt) else: if isinstance(hdl[0], re.Pattern): # log.debug(hdl[0].pattern) hdl[0] = re.compile('{}/{}'.format(prefix, hdl[0].pattern.lstrip('/'))) # log.debug(hdl[0].pattern) # log.debug(" routing %s to %s", hdl[0].pattern, hdl[1]) else: # log.debug(hdl[0]) if isinstance(hdl, list): hdl[0] = '{}/{}'.format(prefix, hdl[0].lstrip('/')) if isinstance(hdl, tuple): hdl = tuple(['{}/{}'.format(prefix, hdl[0].lstrip('/'))] + list(hdl[1:])) else: raise RuntimeError() # log.debug(" routing %s to %s", hdl[0], hdl[1]) handlers[i] = hdl handlers.insert(len(handlers), ('/', HomeRedirectHandler, dict(prefix=prefix))) return login_url, handlers
def load_service(self, service: HttpService, rules: list, ssl: bool, ssl_options: dict) -> bool: if not self.load_guard(service): return False protocol = 'https' if ssl else 'http' http_path_list, management_root = self.prepare_app(service) app = self.make_app(service, http_path_list, self.globals, debug=self.debug, management_root=management_root) self._apps.apps[service.internal_http_service_id] = app address_str = self.address if self.address else 'localhost' self._apps.listeners[service.internal_http_service_id] = _Listener( service.hostname, service.port, address_str) if service.hostname is None: server = self.impl.get_server(app, ssl, ssl_options) logging.debug('Will listen: %s:%d', address_str, service.port) server.listen(service.port, address=self.address) self.services_log.append( 'Serving at %s://%s:%s%s' % (protocol, address_str, service.port, ' the mock for %r' % service.get_name_or_empty())) else: rules.append(Rule(HostMatches(service.hostname), app)) logging.debug('Registered hostname and port: %s://%s:%d', protocol, service.hostname, service.port) self.services_log.append( 'Serving at %s://%s:%s%s' % (protocol, service.hostname, service.port, ' the mock for %r' % service.get_name_or_empty())) if service.name is not None: logging.debug('Finished registering: %s', service.name) return True
from tornado.routing import Rule, RuleRouter, PathMatches from example.apps import auth router = RuleRouter([Rule(PathMatches("/auth/.*"), auth.application)])
def reset_handlers(self): self.wildcard_router = _ApplicationRouter(self, []) self.default_router = _ApplicationRouter(self, [ Rule(AnyMatches(), self.wildcard_router) ])
def add_component(self, component: type): """ Adds a components handlers to the http or websocket routers respectively. :param component: Services component :raises ValueError: Error indicating the component provided is not a subclass of Component. :raises TypeError: Error indicating the component provided is not a class. """ try: if not issubclass(component, Component): msg = messages.SERVICE_ADD_COMPONENT_INVALID_COMPONENT_CLASS.format( component.__name__) self.logger.error(msg) raise ValueError(msg) except TypeError: self.logger.error( messages.SERVICE_ADD_COMPONENT_INVALID_COMPONENT_TYPE) raise TypeError( messages.SERVICE_ADD_COMPONENT_INVALID_COMPONENT_TYPE) self.logger.debug( messages.SERVICE_ADD_COMPONENT.format(self.name, component.component_name, component.component_path)) if component.component_http_handler is None and component.component_websocket_handler is None: self.logger.warning( messages.SERVICE_ADD_COMPONENT_WITH_NO_HANDLER.format( component.component_name, self.name)) http_handlers = [] websocket_handlers = [] if component.component_http_handler: self.logger.debug( messages.SERVICE_ADD_COMPONENT_REGISTER_HANDLER.format( self.name, component.component_name, 'http_handler')) http_handlers = [(r'/.*', component.component_http_handler, dict(component_class=component))] if component.component_websocket_handler: self.logger.debug( messages.SERVICE_ADD_COMPONENT_REGISTER_HANDLER.format( self.name, component.component_name, 'websocket_handler')) websocket_handlers = [(r'/.*', component.component_websocket_handler, dict(component_class=component))] http_application = Application(http_handlers) websocket_application = Application(websocket_handlers) self.http_rules.append( Rule(PathMatches('/{}.*'.format(component.component_path)), http_application)) self.websocket_rules.append( Rule(PathMatches('/{}.*'.format(component.component_path)), websocket_application)) self.http_router = RuleRouter(self.http_rules) self.websocket_router = RuleRouter(self.websocket_rules)
def load(self): port_override = environ.get('MOCKINTOSH_FORCE_PORT', None) services = self.definition.data['services'] self._apps.apps = len(services) * [None] self._apps.listeners = len(services) * [None] for service in services: self.unhandled_data.requests.append({}) port_mapping = OrderedDict() for service in self.definition.data['services']: if 'type' in service and service['type'] != 'http': continue if port_override is not None: service['port'] = int(port_override) port = str(service['port']) if port not in port_mapping: port_mapping[port] = [] port_mapping[port].append(service) for port, services in port_mapping.items(): rules = [] ssl = False cert_file = path.join(__location__, 'ssl', 'cert.pem') key_file = path.join(__location__, 'ssl', 'key.pem') for service in services: ssl = service.get('ssl', False) if ssl: if 'sslCertFile' in service: cert_file = self.resolve_cert_path( service['sslCertFile']) if 'sslKeyFile' in service: key_file = self.resolve_cert_path( service['sslKeyFile']) break protocol = 'https' if ssl else 'http' ssl_options = { "certfile": cert_file, "keyfile": key_file, } for service in services: if self.services_list: if 'name' in service: if service['name'] not in self.services_list: continue else: # pragma: no cover continue # https://github.com/nedbat/coveragepy/issues/198 endpoints = [] if 'endpoints' in service: endpoints = HttpServer.merge_alternatives( service, self.definition.stats) management_root = None if 'managementRoot' in service: management_root = service['managementRoot'] app = self.make_app(service, endpoints, self.globals, debug=self.debug, management_root=management_root) self._apps.apps[service['internalServiceId']] = app self._apps.listeners[service['internalServiceId']] = _Listener( service['hostname'] if 'hostname' in service else None, service['port'], self.address if self.address else 'localhost') if 'hostname' not in service: server = self.impl.get_server(app, ssl, ssl_options) server.listen(service['port'], address=self.address) logging.debug('Will listen port number: %d' % service['port']) self.services_log.append( 'Serving at %s://%s:%s%s' % (protocol, self.address if self.address else 'localhost', service['port'], ' the mock for %r' % service['name'] if 'name' in service else '')) else: rules.append(Rule(HostMatches(service['hostname']), app)) logging.debug( 'Registered hostname and port: %s://%s:%d' % (protocol, service['hostname'], service['port'])) self.services_log.append( 'Serving at %s://%s:%s%s' % (protocol, service['hostname'], service['port'], ' the mock for %r' % service['name'] if 'name' in service else '')) if 'name' in service: logging.debug('Finished registering: %s' % service['name']) if rules: router = RuleRouter(rules) server = self.impl.get_server(router, ssl, ssl_options) server.listen(services[0]['port'], address=self.address) logging.debug('Will listen port number: %d' % service['port']) self.load_management_api()
from tornado.routing import RuleRouter, Rule, PathMatches from tornado.web import url, Application from core.views import MainView from apps.account.urls import URL_ACCOUNT URL_PATTERNS = RuleRouter([ Rule(PathMatches("/account.*"), URL_ACCOUNT), ])
class HandlerInApp1(tornado.web.RequestHandler): def get(self): self.write("Handler in app1") app1 = Application([(r"/app1/handler", HandlerInApp1)]) class HandlerInApp2(tornado.web.RequestHandler): def get(self): self.write("Handler in app2") app2 = Application([(r"/app2/handler", HandlerInApp2)]) if __name__ == '__main__': # 创建服务器 server = tornado.web.HTTPServer( RuleRouter([ Rule(PathMatches(r"/app1.*"), app1), Rule(PathMatches(r"/app2.*"), app2) ])) # 侦听端口 8888 server.listen(8888) # 启动 try: tornado.ioloop.IOLoop.current().start() except KeyboardInterrupt: print("Server stopped by user")
def add_handler(self, pattern, target, target_params): if pattern in self.pattern_to_rule: self.remove_handler(pattern) new_rule = Rule(PathMatches(pattern), target, target_params) self.pattern_to_rule[pattern] = new_rule self.rules.append(new_rule)
def make_app(cookie_secret=None, workspace='fixtures/workspace', title='Pipelines', auth=None, history_limit=0, prefix='/'): if cookie_secret is None: raise PipelineError('Cookie secret can not be empty') if not os.path.isdir(workspace): raise PipelinesError('Workspace is not a valid directory: %s' % workspace) auth_dict = _get_auth_dict(auth) slug_regexp = '[0-9a-zA-Z_\\-]+' endpoints = [ Rule(PathMatches(r"/api/pipelines/"), GetPipelinesHandler, name='api_base'), Rule(PathMatches(r"/api/pipelines/({slug})/".format(slug=slug_regexp)), GetPipelineHandler), Rule( PathMatches( r"/api/pipelines/({slug})/run".format(slug=slug_regexp)), RunPipelineHandler), Rule( PathMatches(r"/api/pipelines/({slug})/({slug})/status".format( slug=slug_regexp)), GetStatusHandler), Rule( PathMatches(r"/api/pipelines/({slug})/({slug})/log".format( slug=slug_regexp)), GetLogsHandler), Rule( PathMatches( r"/api/pipelines/({slug})/triggers".format(slug=slug_regexp)), GetTriggersHandler), Rule(PathMatches(r"/api/webhook/({slug})".format(slug=slug_regexp)), WebhookHandler), Rule(PathMatches(r"/api/slackbot/({slug})".format(slug=slug_regexp)), SlackbotHandler), Rule(PathMatches(r"/login"), LoginHandler, name='login'), Rule(PathMatches(r'/(.*)'), AuthStaticFileHandler, { 'path': _get_static_path('app'), "default_filename": "index.html" }), ] if auth_dict and auth_dict.get('type') == 'gh': hdl = Rule(PathMatches('/ghauth'), GithubOAuth2LoginHandler, name='ghauth') endpoints.insert(len(endpoints) - 1, hdl) # prefix support login_url, endpoints = add_prefix_to_handlers(prefix, auth_dict, endpoints) return Application( endpoints, title=title, workspace_path=workspace, auth=auth_dict, login_url=login_url, debug="True", cookie_secret=cookie_secret, history_limit=history_limit, prefix=prefix.rstrip('/'), )
db_engine = io_loop.asyncio_loop.run_until_complete( create_engine(settings.DB_URI, loop=io_loop.asyncio_loop)) amqp_connection = io_loop.asyncio_loop.run_until_complete( make_amqp_connection(db_engine)) if clean: io_loop.asyncio_loop.run_until_complete(db_prepair(db_engine)) application = tornado.web.Application( [ Rule( PathMatches("/api/v1/.*"), tornado.web.Application([ (r"/api/v1/device/(?P<id>\d+)/reports", ReportHandler), (r"/api/v1/device", DeviceHandler), ], amqp_connection=amqp_connection, engine=db_engine), {}, 'api_v1') ], default_handler_class=NotFoundHandler) application.listen(8888) try: io_loop.start() except KeyboardInterrupt: print('STOP') db_engine.close() io_loop.asyncio_loop.run_until_complete(db_engine.wait_closed()) io_loop.stop()
import sys import os import logging import tornado.ioloop from tornado.httpserver import HTTPServer from tornado.routing import RuleRouter, Rule, PathMatches from ams.urls import ams_router from pdms.urls import pdms_router router = RuleRouter([ Rule(PathMatches("/api/accounts.*"), ams_router), Rule(PathMatches("/api/blockchain.*"), pdms_router) ]) if __name__ == '__main__': logging.basicConfig(filename='pmes.log',level=logging.DEBUG, format='%(asctime)s %(message)s') server = HTTPServer(router) server.listen(8000) tornado.ioloop.IOLoop.current().start()