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


Python web.Application方法代码示例

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


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

示例1: run

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def run():
    app = Application([("/", RootHandler)])
    port = random.randrange(options.min_port, options.max_port)
    app.listen(port, address='127.0.0.1')
    signal.signal(signal.SIGCHLD, handle_sigchld)
    args = ["ab"]
    args.extend(["-n", str(options.n)])
    args.extend(["-c", str(options.c)])
    if options.keepalive:
        args.append("-k")
    if options.quiet:
        # just stops the progress messages printed to stderr
        args.append("-q")
    args.append("http://127.0.0.1:%d/" % port)
    subprocess.Popen(args)
    IOLoop.instance().start()
    IOLoop.instance().close()
    del IOLoop._instance
    assert not IOLoop.initialized() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:21,代码来源:benchmark.py

示例2: main

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def main():
    parse_command_line()
    app = Application([('/', ChunkHandler)])
    app.listen(options.port, address='127.0.0.1')

    def callback(response):
        response.rethrow()
        assert len(response.body) == (options.num_chunks * options.chunk_size)
        logging.warning("fetch completed in %s seconds", response.request_time)
        IOLoop.current().stop()

    logging.warning("Starting fetch with curl client")
    curl_client = CurlAsyncHTTPClient()
    curl_client.fetch('http://localhost:%d/' % options.port,
                      callback=callback)
    IOLoop.current().start()

    logging.warning("Starting fetch with simple client")
    simple_client = SimpleAsyncHTTPClient()
    simple_client.fetch('http://localhost:%d/' % options.port,
                        callback=callback)
    IOLoop.current().start() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:24,代码来源:chunk_benchmark.py

示例3: main

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def main():
    parse_command_line(final=False)
    parse_config_file(options.config_file)

    app = Application(
        [
            ('/', MainHandler),
            ('/login', LoginHandler),
            ('/logout', LogoutHandler),
        ],
        login_url='/login',
        **options.group_dict('application'))
    app.listen(options.port)

    logging.info('Listening on http://localhost:%d' % options.port)
    IOLoop.current().start() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:18,代码来源:twitterdemo.py

示例4: initialize

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def initialize(self):
        """子类初始化(Hook).

        作为url spec的第三个参数传递的字典, 将作为关键字参数提供给
        initialize().

        例子::

            class ProfileHandler(RequestHandler):
                def initialize(self, database):
                    self.database = database

                def get(self, username):
                    ...

            app = Application([
                (r'/user/(.*)', ProfileHandler, dict(database=database)),
                ])
        """
        pass 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:22,代码来源:web.py

示例5: set_secure_cookie

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def set_secure_cookie(self, name, value, expires_days=30, version=None,
                          **kwargs):
        """给cookie签名和时间戳以防被伪造.

        你必须在你的Application设置中指定 ``cookie_secret`` 来使用这个方法.
        它应该是一个长的, 随机的字节序列作为HMAC密钥来做签名.

        使用 `get_secure_cookie()` 方法来阅读通过这个方法设置的cookie.

        注意 ``expires_days`` 参数设置cookie在浏览器中的有效期, 并且它是
        独立于 `get_secure_cookie` 的 ``max_age_days`` 参数的.

        安全cookie(Secure cookies)可以包含任意字节的值, 而不只是unicode
        字符串(不像是普通cookie)

        .. versionchanged:: 3.2.1

           添加 ``version`` 参数. 提出cookie version 2
           并将它作为默认设置.
        """
        self.set_cookie(name, self.create_signed_value(name, value,
                                                       version=version),
                        expires_days=expires_days, **kwargs) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:25,代码来源:web.py

示例6: make_static_url

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def make_static_url(cls, settings, path, include_version=True):
        """为给定路径构造一个的有版本的url.

        这个方法可以在子类中被复写(但是注意他是一个类方法而不是一个
        实例方法). 子类只需实现签名
        ``make_static_url(cls, settings, path)``; 其他关键字参数可
        以通过 `~RequestHandler.static_url` 传递, 但这不是标准.

        ``settings`` 是 `Application.settings` 字典. ``path``
        是被请求的静态路径. 返回的url应该是相对于当前host的.

        ``include_version`` 决定生成的URL是否应该包含含有给定
        ``path`` 相对应文件的hash版本查询字符串.

        """
        url = settings.get('static_url_prefix', '/static/') + path
        if not include_version:
            return url

        version_hash = cls.get_version(settings, path)
        if not version_hash:
            return url

        return '%s?v=%s' % (url, version_hash) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:26,代码来源:web.py

示例7: setUp

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def setUp(self):
        if IOLoop.configured_class().__name__ in ('TwistedIOLoop',
                                                  'AsyncIOMainLoop'):
            # TwistedIOLoop only supports the global reactor, so we can't have
            # separate IOLoops for client and server threads.
            # AsyncIOMainLoop doesn't work with the default policy
            # (although it could with some tweaks to this test and a
            # policy that created loops for non-main threads).
            raise unittest.SkipTest(
                'Sync HTTPClient not compatible with TwistedIOLoop or '
                'AsyncIOMainLoop')
        self.server_ioloop = IOLoop()

        sock, self.port = bind_unused_port()
        app = Application([('/', HelloWorldHandler)])
        self.server = HTTPServer(app, io_loop=self.server_ioloop)
        self.server.add_socket(sock)

        self.server_thread = threading.Thread(target=self.server_ioloop.start)
        self.server_thread.start()

        self.http_client = HTTPClient() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:24,代码来源:httpclient_test.py

示例8: get_app

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def get_app(self):
        # callable objects to finish pending /trigger requests
        self.triggers = collections.deque()
        return Application([
            url("/trigger", TriggerHandler, dict(queue=self.triggers,
                                                 wake_callback=self.stop)),
            url("/chunk", ChunkHandler),
            url("/countdown/([0-9]+)", CountdownHandler, name="countdown"),
            url("/hang", HangHandler),
            url("/hello", HelloWorldHandler),
            url("/content_length", ContentLengthHandler),
            url("/head", HeadHandler),
            url("/options", OptionsHandler),
            url("/no_content", NoContentHandler),
            url("/see_other_post", SeeOtherPostHandler),
            url("/see_other_get", SeeOtherGetHandler),
            url("/host_echo", HostEchoHandler),
            url("/no_content_length", NoContentLengthHandler),
            url("/echo_post", EchoPostHandler),
            url("/respond_in_prepare", RespondInPrepareHandler),
            url("/redirect", RedirectHandler),
        ], gzip=True) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:24,代码来源:simple_httpclient_test.py

示例9: test_missing_key

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def test_missing_key(self):
        """A missing SSL key should cause an immediate exception."""

        application = Application()
        module_dir = os.path.dirname(__file__)
        existing_certificate = os.path.join(module_dir, 'test.crt')
        existing_key = os.path.join(module_dir, 'test.key')

        self.assertRaises((ValueError, IOError),
                          HTTPServer, application, ssl_options={
                              "certfile": "/__mising__.crt",
        })
        self.assertRaises((ValueError, IOError),
                          HTTPServer, application, ssl_options={
                              "certfile": existing_certificate,
                              "keyfile": "/__missing__.key"
        })

        # This actually works because both files exist
        HTTPServer(application, ssl_options={
                   "certfile": existing_certificate,
                   "keyfile": existing_key,
                   }) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:25,代码来源:httpserver_test.py

示例10: get_app

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def get_app(self):
        return web.Application([("/echo", EchoHandler), ("/fail", FailureHandler)]) 
开发者ID:bcb,项目名称:jsonrpcclient,代码行数:4,代码来源:test_tornado_client.py

示例11: __init__

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def __init__(self, root_directory, bucket_depth=0):
        web.Application.__init__(self, [
            (r"/", RootHandler),
            (r"/([^/]+)/(.+)", ObjectHandler),
            (r"/([^/]+)/", BucketHandler),
        ])
        self.directory = os.path.abspath(root_directory)
        if not os.path.exists(self.directory):
            os.makedirs(self.directory)
        self.bucket_depth = bucket_depth 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:12,代码来源:s3server.py

示例12: reverse_url

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def reverse_url(self, name, *args):
        """ `Application.reverse_url` 的别名."""
        return self.application.reverse_url(name, *args) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:5,代码来源:web.py

示例13: _log

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def _log(self):
        """记录当前请求.

        可以说这是过时的因为这个功能已经被移动到了Application, 留在这里
        是为了兼容已经复写这个方法的现有app.
        """
        self.application.log_request(self) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:9,代码来源:web.py

示例14: get_version

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def get_version(cls, settings, path):
        """生成用于静态URL的版本字符串.

        ``settings`` 是 `Application.settings` 字典并且 ``path``
        是请求资源在文件系统中的相对位置. 返回值应该是一个字符串
        或 ``None`` 如果没有版本可以被确定.

        .. versionchanged:: 3.1
           这个方法之前建议在子类中复写; `get_content_version`
           现在是首选因为它允许基类来处理结果的缓存.
        """
        abs_path = cls.get_absolute_path(settings['static_path'], path)
        return cls._get_cached_version(abs_path) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:15,代码来源:web.py

示例15: __init__

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import Application [as 别名]
def __init__(self, pattern, handler, kwargs=None, name=None):
        """Parameters:

        * ``pattern``: 被匹配的正则表达式. 任何在正则表达式的group
          都将作为参数传递给处理程序的get/post/等方法.

        * ``handler``: 被调用的 `RequestHandler` 子类.

        * ``kwargs`` (optional): 将被传递给处理程序构造器的额外
          参数组成的字典.

        * ``name`` (optional): 该处理程序的名称. 被
          `Application.reverse_url` 使用.
        """
        if not pattern.endswith('$'):
            pattern += '$'
        self.regex = re.compile(pattern)
        assert len(self.regex.groupindex) in (0, self.regex.groups), \
            ("groups in url regexes must either be all named or all "
             "positional: %r" % self.regex.pattern)

        if isinstance(handler, str):
            # import the Module and instantiate the class
            # Must be a fully qualified name (module.ClassName)
            handler = import_object(handler)

        self.handler_class = handler
        self.kwargs = kwargs or {}
        self.name = name
        self._path, self._group_count = self._find_groups() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:32,代码来源:web.py


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