def _build_routers(self): """ Builds the http and websocket routers. Routers are instances of Tornado RuleRouter. """ self.logger.debug(messages.ROUTER_BUILD_ROUTERS) self._http_router = RuleRouter(self._http_router_rules) self._websocket_router = RuleRouter(self._websocket_router_rules)
def load(self) -> None: self._apps.apps = len(HttpService.services) * [None] self._apps.listeners = len(HttpService.services) * [None] for service in self.definition.services: self.unhandled_data.requests.append({}) port_mapping = self.map_ports() for port, services in port_mapping.items(): ssl, ssl_options = self.resolve_ssl(services) rules = [] for service in services: if not self.load_service(service, rules, ssl, ssl_options): continue if rules: router = RuleRouter(rules) server = self.impl.get_server(router, ssl, ssl_options) logging.debug('Listening on port: %s:%d', self.address, service.port) server.listen(services[0].port, address=self.address) self.load_management_api()
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 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_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 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 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 get_app(self): wsgi_app = WSGIContainer(self.wsgi_app) class Handler(RequestHandler): def get(self, *args, **kwargs): self.finish(self.reverse_url("tornado")) return RuleRouter([ (PathMatches("/tornado.*"), Application([(r"/tornado/test", Handler, {}, "tornado")])), (PathMatches("/wsgi"), wsgi_app), ])
def start(self): parse_command_line() # Repurpose tuples to keep itemfeed reference rs = self.ROUTER.ROUTES for i, x in enumerate(rs): rs[i] = x + ({"app": self}, ) # Connect Database self.connect_db() # Attach Routes router = RuleRouter([("/.*", Application(rs, debug=True))]) # Configure Server and start server = HTTPServer(router) server.listen(options.port) print("Server Listening on PORT: " + str(options.port)) IOLoop.current().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 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_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()
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), ])
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()
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")
from tornado.routing import Rule, RuleRouter, PathMatches from example.apps import auth router = RuleRouter([Rule(PathMatches("/auth/.*"), auth.application)])
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)
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()