当前位置: 首页>>代码示例>>Python>>正文


Python Application.reverse_url方法代码示例

本文整理汇总了Python中tornado.web.Application.reverse_url方法的典型用法代码示例。如果您正苦于以下问题:Python Application.reverse_url方法的具体用法?Python Application.reverse_url怎么用?Python Application.reverse_url使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tornado.web.Application的用法示例。


在下文中一共展示了Application.reverse_url方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ExhibitionistServer

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import reverse_url [as 别名]

#.........这里部分代码省略.........

        may throw RuntimeError if provider refuses to accept new handlers
        (for example, new HTTP handlers after server start)
        """
        if self.started_ok:
            raise ExhibitionistError(
                "can only add handlers before server start")

        for prvdr in self.providers:
            handlers = self._discover(prvdr.is_handler, ns_or_h)
            [prvdr.subscribe(x) for x in
             handlers] # py3 has lazy map, side-effects.

        return self # fluent

    def _register_handlers(self):
        """ register http_handlers with tornado application"""
        from tornado.web import URLSpec,Application

        urlconf = [URLSpec(http_handler.get_route(h), h,
                           name=http_handler.get_view_name(h),
                           kwargs=http_handler.get_kwds(h))
                   for h in self.http_handlers]

        self.application = Application(urlconf,
                                       **self.tornado_app_settings)
        #
        # self.application.add_handlers("", urlconf) # re-register everything


    def get_view_url(self, handler_name, *args, **kwds):
        """Returns a full url for the given view, with given argument

        a wrapper around tornado's reverse_url with some bells and whistles.

        if the handler included the {{objid}} special marker, 'objid'
        must be provide to reverse_url to be inserted into the returned
        url, and args[0] will be interpreted as the object to be viewed.
        If you pass in an object it will automatically be registered
        and the objid substituted into the url, but you can also
        provide an objid for an object previously registered.

        if you want a weakref to be used (to prevent memory leaks) to store
        the object in the object registry ,pass in a kwd argument
        `_weakref=True` when first viewing the argument.
        Note that not all types are supported by weakref.

        :param handler_name: Handler class name, or value of view_name used
            in @http_handler.
        :param obj_or_objid: objid is the return value of a previous call to
            registry.register
        :param args: values to use in unnamed capture groups in route regexp,
            if any.  must match the number and order of groups.
        :param kwds: values to use in named capture groups in route regexp,
            if any   must match the number and and names of groups.

        Throws: IOError if the server thread failed to initialize

        Examples:

        @http_handler("/blah/{{objid}}")
        class A():
           ...

        get_view_url('A',my_object)
开发者ID:karelin,项目名称:Exhibitionist,代码行数:69,代码来源:server.py

示例2: WSGISafeWebTest

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import reverse_url [as 别名]
class WSGISafeWebTest(AsyncHTTPTestCase, LogTrapTestCase):
    COOKIE_SECRET = "WebTest.COOKIE_SECRET"

    def get_app(self):
        self.app = Application(self.get_handlers(), **self.get_app_kwargs())
        return self.app

    def get_app_kwargs(self):
        loader = DictLoader({
                "linkify.html": "{% module linkify(message) %}",
                "page.html": """\
<html><head></head><body>
{% for e in entries %}
{% module Template("entry.html", entry=e) %}
{% end %}
</body></html>""",
                "entry.html": """\
{{ set_resources(embedded_css=".entry { margin-bottom: 1em; }", embedded_javascript="js_embed()", css_files=["/base.css", "/foo.css"], javascript_files="/common.js", html_head="<meta>", html_body='<script src="/analytics.js"/>') }}
<div class="entry">...</div>""",
                })
        return dict(template_loader=loader,
                    autoescape="xhtml_escape",
                    cookie_secret=self.COOKIE_SECRET)

    def get_handlers(self):
        urls = [
            url("/typecheck/(.*)", TypeCheckHandler, name='typecheck'),
            url("/decode_arg/(.*)", DecodeArgHandler, name='decode_arg'),
            url("/decode_arg_kw/(?P<arg>.*)", DecodeArgHandler),
            url("/linkify", LinkifyHandler),
            url("/uimodule_resources", UIModuleResourceHandler),
            url("/optional_path/(.+)?", OptionalPathHandler),
            url("/multi_header", MultiHeaderHandler),
            url("/redirect", RedirectHandler),
            url("/header_injection", HeaderInjectionHandler),
            ]
        return urls

    def fetch_json(self, *args, **kwargs):
        response = self.fetch(*args, **kwargs)
        response.rethrow()
        return json_decode(response.body)

    def test_types(self):
        cookie_value = to_unicode(create_signed_value(self.COOKIE_SECRET,
                                                      "asdf", "qwer"))
        response = self.fetch("/typecheck/asdf?foo=bar",
                              headers={"Cookie": "asdf=" + cookie_value})
        data = json_decode(response.body)
        self.assertEqual(data, {})

        response = self.fetch("/typecheck/asdf?foo=bar", method="POST",
                              headers={"Cookie": "asdf=" + cookie_value},
                              body="foo=bar")

    def test_decode_argument(self):
        # These urls all decode to the same thing
        urls = ["/decode_arg/%C3%A9?foo=%C3%A9&encoding=utf-8",
                "/decode_arg/%E9?foo=%E9&encoding=latin1",
                "/decode_arg_kw/%E9?foo=%E9&encoding=latin1",
                ]
        for url in urls:
            response = self.fetch(url)
            response.rethrow()
            data = json_decode(response.body)
            self.assertEqual(data, {u'path': [u'unicode', u'\u00e9'],
                                    u'query': [u'unicode', u'\u00e9'],
                                    })

        response = self.fetch("/decode_arg/%C3%A9?foo=%C3%A9")
        response.rethrow()
        data = json_decode(response.body)
        self.assertEqual(data, {u'path': [u'bytes', u'c3a9'],
                                u'query': [u'bytes', u'c3a9'],
                                })

    def test_reverse_url(self):
        self.assertEqual(self.app.reverse_url('decode_arg', 'foo'),
                         '/decode_arg/foo')
        self.assertEqual(self.app.reverse_url('decode_arg', 42),
                         '/decode_arg/42')
        self.assertEqual(self.app.reverse_url('decode_arg', b('\xe9')),
                         '/decode_arg/%E9')
        self.assertEqual(self.app.reverse_url('decode_arg', u'\u00e9'),
                         '/decode_arg/%C3%A9')

    def test_uimodule_unescaped(self):
        response = self.fetch("/linkify")
        self.assertEqual(response.body,
                         b("<a href=\"http://example.com\">http://example.com</a>"))

    def test_uimodule_resources(self):
        response = self.fetch("/uimodule_resources")
        self.assertEqual(response.body, b("""\
<html><head><link href="/base.css" type="text/css" rel="stylesheet"/><link href="/foo.css" type="text/css" rel="stylesheet"/>
<style type="text/css">
.entry { margin-bottom: 1em; }
</style>
<meta>
</head><body>
#.........这里部分代码省略.........
开发者ID:Loopycube,项目名称:tornado,代码行数:103,代码来源:web_test.py


注:本文中的tornado.web.Application.reverse_url方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。