類 Application

Application:(代碼目錄:tornado-4.1\tornado\web.py)html

    用來配置httpserver如何影響客戶端請求的配置項集合的類,開發者在自定義的web應用裏配置好這個類裏的各項數據,在此基礎上建立HTTPServer實例,HTTPServer啓動監聽,同步啓動IOLoop類的start,啓動一個web應用。(用戶在pc機打開瀏覽器輸入url肯定以後,瀏覽器就向url中定義的服務器某個端口發送請求,服務器上此端口的監聽類就會獲知有具體的請求,tornado框架如何將監聽到的請求轉到具體的處理的須要仔細走讀IOLoop類,TCPServer類等python

一個簡單使用的例子:(能夠認爲全部的web應用都是用相似的腳本啓動的:首先實例一個app類,其次啓動一個server監聽,最後使用單例類IOLoop的start啓動web服務)web

        application = web.Application([
            (r"/", MainPageHandler),
        ])
        http_server = httpserver.HTTPServer(application)
        http_server.listen(8080)
        ioloop.IOLoop.instance().start()


    Application類最重要的一個參數是handlers,它是一個由多個(包含1個)元組(結構爲(regexp, request_class))組成的列表,其中的regexp通常指向一個相對路徑,request_class就是用來接收客戶端輸入並作出對應響應類,通常由用戶自定義,繼承於tornado.web.RequestHandler(這個regexp和request_class是怎麼起做用,須要詳細閱讀RequestHandler類和HTTPServer類express

class Application(httputil.HTTPServerConnectionDelegate):
    """A collection of request handlers that make up a web application.
    Instances of this class are callable and can be passed directly to
    HTTPServer to serve the application::
        application = web.Application([
            (r"/", MainPageHandler),
        ])
        http_server = httpserver.HTTPServer(application)
        http_server.listen(8080)
        ioloop.IOLoop.instance().start()
    The constructor for this class takes in a list of `URLSpec` objects
    or (regexp, request_class) tuples. When we receive requests, we
    iterate over the list in order and instantiate an instance of the
    first request class whose regexp matches the request path.
    The request class can be specified as either a class object or a
    (fully-qualified) name.
    Each tuple can contain additional elements, which correspond to the
    arguments to the `URLSpec` constructor.  (Prior to Tornado 3.2, this
    only tuples of two or three elements were allowed).
    A dictionary may be passed as the third element of the tuple,
    which will be used as keyword arguments to the handler's
    constructor and `~RequestHandler.initialize` method.  This pattern
    is used for the `StaticFileHandler` in this example (note that a
    `StaticFileHandler` can be installed automatically with the
    static_path setting described below)::
        application = web.Application([
            (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
        ])
    We support virtual hosts with the `add_handlers` method, which takes in
    a host regular expression as the first argument::
        application.add_handlers(r"www\.myhost\.com", [
            (r"/article/([0-9]+)", ArticleHandler),
        ])
    You can serve static files by sending the ``static_path`` setting
    as a keyword argument. We will serve those files from the
    ``/static/`` URI (this is configurable with the
    ``static_url_prefix`` setting), and we will serve ``/favicon.ico``
    and ``/robots.txt`` from the same directory.  A custom subclass of
    `StaticFileHandler` can be specified with the
    ``static_handler_class`` setting.
    """
    def __init__(self, handlers=None, default_host="", transforms=None,
                 **settings):
        if transforms is None:
            self.transforms = []
            if settings.get("compress_response") or settings.get("gzip"):
                self.transforms.append(GZipContentEncoding)
        else:
            self.transforms = transforms
        self.handlers = []
        self.named_handlers = {}
        self.default_host = default_host
        self.settings = settings
        self.ui_modules = {'linkify': _linkify,
                           'xsrf_form_html': _xsrf_form_html,
                           'Template': TemplateModule,
                           }
        self.ui_methods = {}
        self._load_ui_modules(settings.get("ui_modules", {}))
        self._load_ui_methods(settings.get("ui_methods", {}))
        if self.settings.get("static_path"):
            path = self.settings["static_path"]
            handlers = list(handlers or [])
            static_url_prefix = settings.get("static_url_prefix",
                                             "/static/")
            static_handler_class = settings.get("static_handler_class",
                                                StaticFileHandler)
            static_handler_args = settings.get("static_handler_args", {})
            static_handler_args['path'] = path
            for pattern in [re.escape(static_url_prefix) + r"(.*)",
                            r"/(favicon\.ico)", r"/(robots\.txt)"]:
                handlers.insert(0, (pattern, static_handler_class,
                                    static_handler_args))
        if handlers:
            self.add_handlers(".*$", handlers)
        if self.settings.get('debug'):
            self.settings.setdefault('autoreload', True)
            self.settings.setdefault('compiled_template_cache', False)
            self.settings.setdefault('static_hash_cache', False)
            self.settings.setdefault('serve_traceback', True)
        # Automatically reload modified modules
        if self.settings.get('autoreload'):
            from tornado import autoreload
            autoreload.start()
相關文章
相關標籤/搜索