Application:(代码目录:tornado-4.1\tornado\web.py)
用来配置httpserver如何影响客户端请求的配置项集合的类,开发者在自定义的web应用里配置好这个类里的各项数据,在此基础上创建HTTPServer实例,HTTPServer启动监听,同步启动IOLoop类的start,启动一个web应用。(用户在pc机打开浏览器输入url确定之后,浏览器就向url中定义的服务器某个端口发送请求,服务器上此端口的监听类就会获知有具体的请求,tornado框架如何将监听到的请求转到具体的处理的需要仔细走读IOLoop类,TCPServer类等)
一个简单使用的例子:(可以认为所有的web应用都是用类似的脚本启动的:首先实例一个app类,其次启动一个server监听,最后使用单例类IOLoop的start启动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类)
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()