Пример #1
0
def swagger_handlers():
    prefix = default_settings.get('swagger_prefix', '/swagger')
    if prefix[-1] != '/':
        prefix += '/'

    def _path(suffix):
        return prefix + suffix
    return [
        URLSpec(
            _path(r'spec.html$'),
            SwaggerUIHandler,
            default_settings,
            name=SWAGGER_API_DOCS),
        URLSpec(
            _path(r'spec.json$'),
            SwaggerResourcesHandler,
            default_settings,
            name=SWAGGER_API_LIST),
        URLSpec(
            _path(r'spec$'),
            SwaggerApiHandler,
            default_settings,
            name=SWAGGER_API_SPEC),
        (
            _path(r'(.*\.(css|png|gif|js))'),
            StaticFileHandler,
            {'path': default_settings.get('static_path')}),
    ]
def swagger_handlers():
    """Returns the swagger UI handlers

    Returns:
        [(route, handler)] -- list of Tornado URLSpec
    """

    prefix = settings.default_settings.get('swagger_prefix', '/swagger')
    if prefix[-1] != '/':
        prefix += '/'
    # Le o arquivo
    #
    # dir_path = os.path.dirname(os.path.realpath(__file__))
    # print(dir_path)
    # index = open(dir_path + "/index.html", "r").read()
    # # Muda o prefixo
    # index.replace('{{prefix}}', prefix)
    # # Salva no outro local
    # # open(dir_path + "/static/index.html", "w").write(index)

    return [
        URLSpec(prefix + r'spec.html$', SwaggerUIHandler,
                settings.default_settings, name=settings.URL_SWAGGER_API_DOCS),
        URLSpec(prefix + r'spec$', SwaggerApiHandler,
                name=settings.URL_SWAGGER_API_SPEC),
        (prefix + r'(.*\.(css|png|gif|js))', StaticFileHandler,
         {'path': settings.default_settings.get('static_path')}),
    ]
Пример #3
0
    def build(self, prefix=None):
        #logging.debug('\n build')
        prefix = prefix or self.prefix or ''

        res = []
        for r in self.items:
            route = '/' + '/'.join([prefix.strip('/')] +
                                   r[0].strip('/').split('/')).strip('/')

            if isinstance(r[1], HandlersList):
                res += r[1].build(route)
            elif isinstance(r[1], basestring):
                m = r[1].split('.')
                ms, m, h = '.'.join(m[:-1]), m[-2], m[-1]
                m = __import__(ms, fromlist=[m], level=0)
                handler = getattr(m, h)[0]
                d = {'name': self.get_handler_name(handler, r)}
                d.update(r[2:])
                res.append(URLSpec(route, handler, **d))
            else:
                handler = r[1:][0]
                d = {'name': self.get_handler_name(handler, r)}
                if len(r) == 3:
                    d['kwargs'] = r[2]
                res.append(URLSpec(route, handler, **d))

        return res
Пример #4
0
    def url_specs(cls, url_prefix):
        """
        Return the URLSpecs to be register on the application.
        This usually includes one URLSpec for the page itself, and one for
        each datasource.
        """

        url_specs = []
        url_specs.append(
            URLSpec(r"%s%s/" % (url_prefix, cls.base_url.strip("/")),
                    type(cls.__name__, (cls.dashboard_handler_cls, cls), {}), {
                        "template": cls.template,
                        "params": cls.params
                    },
                    name=cls.__name__))
        for datasource in cls.datasources:
            if datasource.data_url is None:
                raise KeyError("A Datasource must have a data_url: %s" %
                               datasource.__name__)
            url_specs.append(
                URLSpec(r"%s%s/" %
                        (url_prefix, datasource.data_url.strip("/")),
                        type(datasource.__name__,
                             (datasource, datasource.datasource_handler_cls),
                             dict(datasource.__dict__)), {
                                 "datasource": datasource,
                                 "params": cls.params
                             },
                        name=datasource.url_name))
        return url_specs
Пример #5
0
    def _add_handlers(self, host_pattern, host_handlers, url_prefix=''):
        
        handlers = []
        for spec in host_handlers:
            if isinstance(spec, type(())):
                assert len(spec) in (2, 3)
                pattern = spec[0]
                handler = spec[1]

                if isinstance(handler, str):
                    handler = import_object(handler)

                if len(spec) == 3:
                    kwargs = spec[2]
                else:
                    kwargs = {}
                pattern = '%s%s' % (url_prefix, pattern)
                spec = URLSpec(pattern, handler, kwargs)
            elif isinstance(spec, URLSpec):
                pattern = '%s%s' % (url_prefix, spec.regex.pattern)
                spec = URLSpec(pattern, spec.handler_class,
                               spec.kwargs, spec.name)

            handlers.append(spec)
        
        if host_pattern:
            self.sub_handlers.append((host_pattern, handlers))
        else:
            for handler in handlers:
                self.add_handler(handler)
    def build(self, prefix=None):
        prefix = prefix or self.prefix or ''

        res = []
        for r in self.items:
            if len(r) != 2:
                raise Exception(
                    'Url item must be typle which length is 2. Invalid item is {}'
                    .format(r))

            ro = '/' + '/'.join([prefix.strip('/')] +
                                r[0].strip('/').split('/')).strip('/')

            if isinstance(r[1], Handlers):
                res += r[1].build(ro)
            elif isinstance(r[1], six.string_types):
                m = r[1].split('.')
                ms, m, h = '.'.join(m[:-1]), m[-2], m[-1]
                m = __import__(ms, fromlist=[m], level=0)
                handler = getattr(m, h)[0]
                d = {'name': self.get_handler_name(handler, r)}
                d.update(r[2:])
                res.append(URLSpec(ro, handler, **d))
            else:
                handler = r[1:][0]
                d = {'name': self.get_handler_name(handler, r)}
                if len(r) == 3:
                    d['kwargs'] = r[2]
                res.append(URLSpec(ro, handler, **d))

        return res
Пример #7
0
    def _register_app_handlers(self, app, url_prefix):
        if not app.handlers:
            return
        for spec in app.handlers:
            if isinstance(spec, tuple):
                assert len(spec) in (2, 3)
                pattern = spec[0]
                handler = spec[1]

                if isinstance(handler, str):
                    handler = import_object(handler)

                if len(spec) == 3:
                    kwargs = spec[2]
                else:
                    kwargs = {}

                pattern = '%s%s' % (url_prefix, pattern)
                spec = URLSpec(pattern, handler, kwargs)
            elif isinstance(spec, URLSpec):
                pattern = '%s%s' % (url_prefix, spec.regex.pattern)
                spec = URLSpec(pattern, spec.handler_class,
                               spec.kwargs, spec.name)

            self.add_handler(spec)
Пример #8
0
def criar_rotas():
    """Esta função é responsavel por criar as rotas do app do Tornado."""
    routes = [
        URLSpec(r'/garcom-sincrono', GarcomSincrono),
        URLSpec(r'/garcom-assincrono', GarcomAssincrono)
    ]

    return Application(routes, **options.as_dict())
Пример #9
0
    def detectURL(self, headURL='', itertime=0):
        """
        get url
        :headURL :the former URL which need to be merged
        :return: (url,url_module)
        """
        from tornado.web import URLSpec
        urlList = []
        # print urlList
        for it in self.patterns:
            if isinstance(it, URLSpec):
                urlList.append(it)
                continue
            else:
                # compatible with native tornado url configuration
                url, url_module = it[:2]
                if len(it) > 2:
                    # there maybe some other configuration setting
                    other_config = it[2:]
                else:
                    other_config = []

            # iterable get the URL
            if isinstance(url_module, urlPackage):
                # BFS get URL then extend it
                urlList.extend(
                    url_module.detectURL(headURL='%s%s' % (headURL, url),
                                         itertime=itertime + 1))
            elif isinstance(url_module, str):
                # print url_module
                # for individual one then add it to the list
                if headURL:
                    assemblyURL = '%s%s' % (headURL, url)
                else:
                    assemblyURL = '%s' % url
                    # convert it to URLSpec
                urlList.append(
                    URLSpec(assemblyURL,
                            url_module,
                            *other_config,
                            name=url_module))
                # set up mapper for
                self.URLMapper[url_module] = assemblyURL
            else:
                # try to use directly
                if headURL:
                    assemblyURL = '%s%s' % (headURL, url)
                else:
                    assemblyURL = '%s' % url
                urlList.append(
                    URLSpec(assemblyURL,
                            url_module,
                            *other_config,
                            name=str(url_module)))
                # raise ImproperlyConfigured(
                #     'URL only accept string or URLpackage object(you can use include)'
                # )
        return urlList
Пример #10
0
def create_app():
    """
    Create instance of tornado.web.Application.
    """
    routes = [
        URLSpec(r'/async', MainHandlerAsync),
        URLSpec(r"/block", MainHandlerBlocking)
    ]
    return Application(routes, **options.as_dict())
Пример #11
0
    def __init__(self, args):
        handlers = [
            URLSpec(r"/", UsersHandler, name="index"),
            URLSpec(r"/user/([0-9a-f]+)", UserDetailHandler, name="userDetail"),
        ]
        super(MonitorApp, self).__init__(handlers,
                                  template_path="templates/monitor")

        self.report_collector = ReportCollector(args.db)
Пример #12
0
def make_application(app, debug=False, wsgi=False, settings_path="", url_root="/", **keywords):
    app_path = os.path.abspath(os.path.dirname(app.__file__))
    conf = None
    if settings_path != "":
        #conf = app.settings
        conf = Yaml_Config(app_path, settings_path, url_root=url_root)
    #else:
    #    conf = Yaml_Config(app_path, os.path.join(app_path, 'settings.yaml'), url_root=url_root)
    views_path = os.path.join(app_path, 'views')
    module_list = []
    def getModule(module):
        if type(module) == tuple:
            return getModule(module[0])
        else:
            return module

    for module, name in get_modules([app.__name__, 'views'], views_path):
        module = getModule(module)
        #if type(module) == tuple:
        #    module = module[0]
        #    if type(module) == tuple:
        #        module = module[0]
        m = __import__(module, {}, {}, name)
        module_list.append(m)
    from torweb.urls import url, except_url
    def _set_debug(kw):
        kw["debug"] = debug
        return kw
    url_handlers = url.handlers
    url_handlers = [URLSpec(spec.regex.pattern, spec.handler_class, _set_debug(spec.kwargs), spec.name) for spec in url_handlers]
    if hasattr(app, "url"):
        app_url_handlers = app.url.handlers
        app_url_handlers = [URLSpec(spec.regex.pattern, spec.handler_class, _set_debug(spec.kwargs), spec.name) for spec in app_url_handlers]
        url_handlers.extend(app_url_handlers)
    _static_urls = [spec.regex.pattern for spec in url.handlers if spec.kwargs.has_key("path") and hasattr(spec.handler_class, 'static_handler') and spec.handler_class.static_handler==True]
    #url_handlers = [(u, c, _set_debug(kw)) for u, c, kw in url_handlers]
    #_static_urls = [url for url, cls, kw in url.handlers if kw.has_key("path") and hasattr(cls, 'static_handler') and cls.static_handler==True]
    url_handlers.extend(except_url.handlers)
    keywords.update({"debug":debug})
    if debug:
        application = DebugApplication(url_handlers, **keywords)
    else:
        if wsgi == True:
            application = _WSGIApplication(url_handlers, **keywords)
        else:
            application = WebApplication(url_handlers, **keywords)
    application.url_handlers = url_handlers
    application._static_urls = _static_urls
    # 初始化session store
    if conf:
        application.session_store = conf.session_store
    else:
        from torweb.sessions import MemorySessionStore
        application.session_store = MemorySessionStore()
    return application
Пример #13
0
 def init_handlers(self):
     self.handlers = [
         URLSpec(r'/', handlers.IndexHandler, name='Index'),
         URLSpec(r'/data/(\d*)', handlers.DataHandler, name='Data'),
         URLSpec(r'/nodeinfo', handlers.NodeInfoHandler, name='NodeInfo'),
         URLSpec(r'/vis', handlers.VisHandler, name='Vis'),
         URLSpec(r'/led',
                 handlers.LEDHandler,
                 dict(bat_mac=self.bat_mac),
                 name='LED')
     ]
Пример #14
0
    def __init__(self):
        handlers = [
            URLSpec(r'/', IndexHandler),
            URLSpec(r'/cat/(\d{1,2})', CatHandler, name="cat"),
            URLSpec(r'/detail/(\w+)', DetailHandler),
            URLSpec(r'/login', LoginHandler),
        ]

        tornado.web.Application.__init__(self, handlers, **settings.settings)
        self.db = torndb.Connection(host=settings.DBHOST,
                                    database=settings.DATABASE,
                                    user=settings.DBUSER,
                                    password=settings.DBPWD)
Пример #15
0
def view_handlers():
    prefix = default_settings.get('product_prefix', '/alipay')
    if prefix[-1] != '/':
        prefix += '/'

    return [
        URLSpec('/', views.DefaultHandler, default_settings),
        URLSpec(prefix + r'home.html$', views.HomeHandler, default_settings),
        (prefix + r'(.*\.(css|png|gif|jpg|js|ttf|woff|woff2))',
         StaticFileHandler, {
             'path': default_settings.get('static_path')
         }),
    ]
Пример #16
0
    def __init__(self):
        handlers = [
            URLSpec(r"/upload/", UploadHandler, name='upload'),
            URLSpec(r"/download/([^/]+)?", DownloadHandler, name='download'),
        ]

        settings = {
            "template_path": os.path.join(os.path.dirname(__file__),
                                          "templates"),
            "static_path": os.path.join(os.path.dirname(__file__), "static"),
            "debug": True,
        }

        tornado.web.Application.__init__(self, handlers, **settings)
Пример #17
0
    def resolve(self):
        if isinstance(self.patterns, str):
            self.patterns = import_object(self.patterns)

        for pattern in self.patterns:
            if isinstance(pattern, dict):
                yield URLSpec(**pattern)
            elif isinstance(pattern, URLSpec):
                yield pattern
            elif isinstance(pattern, Resolver):
                yield from pattern.resolve()
            elif len(pattern) > 1 and isinstance(pattern[1], Resolver):
                yield from self.include(*pattern)
            else:
                yield URLSpec(*pattern)
Пример #18
0
    def get_handler(self, *args, **kwargs):
        """Return Tornado application with Django WSGI handlers"""

        # Patch prepare method from Tornado's FallbackHandler
        FallbackHandler.prepare = patches.patch_prepare(FallbackHandler.prepare)

        django_app = wsgi.WSGIContainer(WSGIHandler())
        handlers = (
            URLSpec(r'/_', WelcomeHandler),
            URLSpec(r'.*', FallbackHandler, dict(fallback=django_app)),
        )
        opts = {
            "debug": settings.DEBUG,
            "loglevel": settings.DEBUG and "debug" or "warn",
        }
        return Application(handlers, **opts)
Пример #19
0
def main():

    parse_command_line(final=False)
    parse_config_file(options.config)
    handlers = [
        URLSpec("/", MainHandler, name="root"),
        URLSpec("/login", LoginHandler, name="login"),
        URLSpec("/logout", LogoutHandler, name="logout")
    ]
    app = Application(handlers,
                      login_url="/login",
                      **options.group_dict("application"))
    app.listen(options.port)

    logging.info("Listening on http://localhost:%d" % options.port)
    IOLoop.current().start()
Пример #20
0
    def detectURL(self, headURL = '', itertime=0):
        """
        get url
        :headURL :the former URL which need to be merged
        :return: (url,url_module)
        """
        from tornado.web import URLSpec
        urlList = []
        # print urlList
        for it in self.patterns:
            if isinstance(it,URLSpec):
                urlList.append(it)
                continue
            else:
                url,url_module = it

            # iterable get the URL
            if isinstance(url_module,urlPackage):
                # BFS get URL then extend it
                urlList.extend(url_module.detectURL(headURL='%s%s' %(headURL,url),itertime=itertime+1))
            elif isinstance(url_module,str):
                #print url_module
                # for individual one then add it to the list
                if headURL:
                    assemblyURL = '%s%s' %(headURL,url)
                else:
                    assemblyURL = '%s' %url
                    # convert it to URLSpec
                urlList.append(URLSpec(assemblyURL,url_module,name=url_module))
                # set up mapper for
                self.URLMapper[url_module] = assemblyURL
            else:
                raise ImproperlyConfigured('URL only accept string or URLpackage object(you can use include)')
        return urlList
Пример #21
0
    def add_handler(self, url_handler):
        """Appends the given url_handlers to our handler list.
        """
        print(url_handler)
        url_pattern = url_handler[0]
        if not url_pattern.endswith("$"):
            url_pattern += "$"
        handlers = []
        #wildcard .*$ should have lowest priority
        #notice:first we only insert a empty handlers as a placeholder
        if self.handlers and self.handlers[-1][0].pattern == '.*$':
            self.handlers.insert(-1, (re.compile(url_pattern), handlers))
        else:
            self.handlers.append((re.compile(url_pattern), handlers))

        spec = url_handler
        if isinstance(
                spec,
            (tuple, list)):  #the url_handler should be inited with some args
            assert len(spec) in (2, 3, 4)
            spec = URLSpec(*spec)
        handlers.append(spec)
        if spec.name:
            if spec.name and self.named_handlers:
                Log4Spider.warnLog(
                    "Multiple handlers named %s; replacing previous value",
                    spec.name)
            self.named_handlers[spec.name] = spec
Пример #22
0
 def new_urlSpec(self, pattern, handler, kwargs=None, name=None):
     if name:
         name = "%s:%s" % (self.name, name)
     return URLSpec('%s%s' % (self.prefix, pattern),
                    handler,
                    kwargs=kwargs,
                    name=name)
Пример #23
0
 def publish(self, base):
     finalRoutes = []
     base = [part for part in base.split('/') if part]
     for route in self.routes:
         route['pattern'] = '/' + '/'.join(base + route['pattern'])
         finalRoutes.append(URLSpec(**route))
     return finalRoutes
Пример #24
0
def load_jupyter_server_extension(nb_app):
    '''Loads server extension.'''
    nb_app.log.info('Loaded nb2kg extension')

    # TODO: There is no clean way to override existing handlers that are already
    # registered with the Tornado application.  The first handler to match the
    # URL will handle the request, so we must prepend our handlers to override
    # the existing ones.
    web_app = nb_app.web_app

    # Detect tornado compatibility.  The 'handlers' list was "moved" (and
    # transformed) in tornado >= 4.5.  Check for its existence and continue the
    # load accordingly.  In 4.5, a "rules" list is used and now resides under
    # the wildcard_router.  Fortunately, URLSpec derives from Rule (as of 4.5)
    # so much of the previous code can be retained.

    # Detect older version of tornado
    if hasattr(web_app, 'handlers'):  # tornado < 4.5
        pattern, handlers = web_app.handlers[0]
    else:  # tornado >= 4.5
        handlers = web_app.wildcard_router.rules

    base_url = web_app.settings['base_url']
    for handler in ext_handlers[::-1]:
        pattern = url_path_join(base_url, handler[0])
        new_handler = URLSpec(pattern, *handler[1:])
        nb_app.log.info('Overriding handler %s' % new_handler)
        handlers.insert(0, new_handler)
Пример #25
0
def add_handlers(self, host_pattern, host_handlers):
    """Appends the given handlers to our handler list.

    Host patterns are processed sequentially in the order they were
    added. All matching patterns will be considered.
    """
    handlers = []
    # The handlers with the wildcard host_pattern are a special
    # case - they're added in the constructor but should have lower
    # precedence than the more-precise handlers added later.
    # If a wildcard handler group exists, it should always be last
    # in the list, so insert new groups just before it.
    if isinstance(host_pattern, basestring):
        if not host_pattern.endswith('$'):
            host_pattern += '$'
        if self.handlers and self.handlers[-1][0].pattern == '.*$':
            self.handlers.insert(-1, (re.compile(host_pattern), handlers))
        else:
            self.handlers.append((re.compile(host_pattern), handlers))
    else:
        self.handlers.append((host_pattern, handlers))

    for spec in host_handlers:
        if isinstance(spec, (tuple, list)):
            assert len(spec) in (2, 3, 4)
            spec = URLSpec(*spec)
        handlers.append(spec)
        if spec.name:
            if spec.name in self.named_handlers:
                app_log.warning(
                    'Multiple handlers named %s; replacing previous value',
                    spec.name)
            self.named_handlers[spec.name] = spec
Пример #26
0
def _handlers():
    prefix = default_settings.get('view_prefix', 'edu')
    if prefix[-1] != '/':
        prefix += '/'
    return [
        URLSpec('/', input.DefaultHandler, default_settings),
        URLSpec(prefix + r'index.html', input.IndextHandler, default_settings),
        URLSpec(prefix + r'login.html$', input.LoginViewHandler,
                default_settings),
        URLSpec(prefix + r'(?P<manage_obj>.+).html$', input.ManageViewHandler,
                default_settings),
        (prefix + r'(.*\.(css|png|gif|jpg|js|ttf|woff|woff2|xls))',
         StaticFileHandler, {
             'path': default_settings.get('static_path')
         }),
    ]
Пример #27
0
 def publish(self, base):
     finalRoutes = []
     base = [part for part in base.split("/") if part]
     for route in self.routes:
         route["pattern"] = "/" + "/".join(base + route["pattern"])
         finalRoutes.append(URLSpec(**route))
     return finalRoutes
Пример #28
0
 def decorator(handler):
     _name = name or handler.__name__
     spec = URLSpec(self.url_prefix + route,
                    handler,
                    initialize,
                    name='%s.%s' % (self.name, _name))
     self.ROUTES.append({'host': host, 'spec': spec})
     return handler
Пример #29
0
def url(route=None, controller=None, action=None, name=None):

    route = Route(name, route)
    route.makeregexp('')

    regexp = re.sub(r'(?<!\\)\\', '', route.regexp)

    return URLSpec(regexp, controller, dict(action=action), name=name)
Пример #30
0
 def __call__(self, handler):
     """
     Called when we decorate a class.
     """
     name = self.name or handler.__name__
     spec = URLSpec(self.route, handler, self.initialize, name=name)
     self._routes.append({'host': self.host, 'spec': spec})
     return handler