當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。