Python tornado.web.Application() Examples

The following are 30 code examples of tornado.web.Application(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.web , or try the search function .
Example #1
Source File: benchmark.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #2
Source File: httpclient_test.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #3
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: simple_httpclient_test.py    From tornado-zh with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
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 
Example #7
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: httpserver_test.py    From tornado-zh with MIT License 6 votes vote down vote up
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,
                   }) 
Example #9
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
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) 
Example #10
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
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 
Example #11
Source File: twitterdemo.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #12
Source File: chunk_benchmark.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #13
Source File: curl_httpclient_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        return Application([
            ('/digest', DigestAuthHandler),
            ('/custom_reason', CustomReasonHandler),
            ('/custom_fail_reason', CustomFailReasonHandler),
        ]) 
Example #14
Source File: web_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        self.app = Application(self.get_handlers(), **self.get_app_kwargs())
        return self.app 
Example #15
Source File: web_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_listen(self):
        app = Application([])
        server = app.listen(0, address='127.0.0.1')
        server.stop() 
Example #16
Source File: wsgi_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def wrap_web_tests_adapter():
    result = {}
    for cls in web_test.wsgi_safe_tests:
        class WSGIAdapterWrappedTest(cls):
            def get_app(self):
                self.app = Application(self.get_handlers(),
                                       **self.get_app_kwargs())
                return WSGIContainer(validator(WSGIAdapter(self.app)))
        result["WSGIAdapter_" + cls.__name__] = WSGIAdapterWrappedTest
    return result 
Example #17
Source File: httpserver_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        return Application([('/', HelloWorldRequestHandler)]) 
Example #18
Source File: gen_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        return Application([
            ('/sequence', GenSequenceHandler),
            ('/coroutine_sequence', GenCoroutineSequenceHandler),
            ('/coroutine_unfinished_sequence',
             GenCoroutineUnfinishedSequenceHandler),
            ('/task', GenTaskHandler),
            ('/exception', GenExceptionHandler),
            ('/coroutine_exception', GenCoroutineExceptionHandler),
            ('/yield_exception', GenYieldExceptionHandler),
            ('/undecorated_coroutine', UndecoratedCoroutinesHandler),
            ('/async_prepare_error', AsyncPrepareErrorHandler),
            ('/native_coroutine', NativeCoroutineHandler),
        ]) 
Example #19
Source File: websocket_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        self.close_future = Future()
        return Application([
            ('/echo', EchoHandler, dict(
                close_future=self.close_future,
                compression_options=self.get_server_compression_options())),
        ]) 
Example #20
Source File: stack_context_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        return Application([('/', TestRequestHandler,
                             dict(io_loop=self.io_loop))]) 
Example #21
Source File: websocket_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        self.close_future = Future()
        return Application([
            ('/echo', EchoHandler, dict(close_future=self.close_future)),
            ('/non_ws', NonWebSocketHandler),
            ('/header', HeaderHandler, dict(close_future=self.close_future)),
            ('/close_reason', CloseReasonHandler,
             dict(close_future=self.close_future)),
            ('/error_in_on_message', ErrorInOnMessageHandler,
             dict(close_future=self.close_future)),
            ('/async_prepare', AsyncPrepareHandler,
             dict(close_future=self.close_future)),
        ]) 
Example #22
Source File: wsgi.py    From tornado-zh with MIT License 5 votes vote down vote up
def __init__(self, application):
        if isinstance(application, WSGIApplication):
            self.application = lambda request: web.Application.__call__(
                application, request)
        else:
            self.application = application 
Example #23
Source File: web.py    From tornado-zh with MIT License 5 votes vote down vote up
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) 
Example #24
Source File: web.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_absolute_path(cls, root, path):
        """返回 ``path`` 相对于 ``root`` 的绝对路径.

        ``root`` 是这个 `StaticFileHandler` 配置的路径(在大多数情
        况下是 `Application` 的 ``static_path`` 设置).

        这个类方法可能在子类中被复写. 默认情况下它返回一个文件系统
        路径, 但其他字符串可以被使用, 只要它们是独特的并且被
        子类复写的 `get_content` 理解.

        .. versionadded:: 3.1
        """
        abspath = os.path.abspath(os.path.join(root, path))
        return abspath 
Example #25
Source File: web.py    From tornado-zh with MIT License 5 votes vote down vote up
def _log(self):
        """记录当前请求.

        可以说这是过时的因为这个功能已经被移动到了Application, 留在这里
        是为了兼容已经复写这个方法的现有app.
        """
        self.application.log_request(self) 
Example #26
Source File: web.py    From tornado-zh with MIT License 5 votes vote down vote up
def settings(self):
        """ `self.application.settings <Application.settings>` 的别名."""
        return self.application.settings 
Example #27
Source File: red_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        return Application(self.get_handlers(), gzip=True, **self.get_app_kwargs()) 
Example #28
Source File: twisted_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def start_tornado_server(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello from tornado!")
        app = Application([('/', HelloHandler)],
                          log_function=lambda x: None)
        server = HTTPServer(app, io_loop=self.io_loop)
        sock, self.tornado_port = bind_unused_port()
        server.add_sockets([sock]) 
Example #29
Source File: httpserver_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        class BufferedHandler(RequestHandler):
            def put(self):
                self.write(str(len(self.request.body)))

        @stream_request_body
        class StreamingHandler(RequestHandler):
            def initialize(self):
                self.bytes_read = 0

            def prepare(self):
                if 'expected_size' in self.request.arguments:
                    self.request.connection.set_max_body_size(
                        int(self.get_argument('expected_size')))
                if 'body_timeout' in self.request.arguments:
                    self.request.connection.set_body_timeout(
                        float(self.get_argument('body_timeout')))

            def data_received(self, data):
                self.bytes_read += len(data)

            def put(self):
                self.write(str(self.bytes_read))

        return Application([('/buffered', BufferedHandler),
                            ('/streaming', StreamingHandler)]) 
Example #30
Source File: httpserver_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get_app(self):
        return Application(self.get_handlers())