Application is one of the important modules of tornado, which is mainly to configure the Access routing table and other application parameters settings.
The source code is located under the Virtual Environment folder (my env), with the location of env > lib>sit-packages>tornado>web.py.
Comment General Meaning:
Application is made up of the request handlers collection, which is configured as a application and passed directly to the Httpserver as a parameter.
The constructor for this class contains a collection of Urlspec objects or a set of tuples (regular expressions, request handler). When the server receives the request, we iterate through the Loop collection sequentially, find the configuration item corresponding to the first regular expression matching the request path, and instantiate the corresponding Hanlder object in the configuration item.
Of course, Tornado also supports virtual hosts, using the Add_handles method, using the host regular expression as the first parameter.
6.1 Constructors
Defined:
__init__ (self, handlers=none, default_host= "", transforms=none,
**settings):
Parameters:
- Hanlders: Urlspec collection for configuration or (regular expression, hanlder) tuple set
- Default_host: The default server name. (I don't know what to do for the time being)
- Transforms: Convert. is a collection of content conversion processor collections. Used to convert the contents of a response, such as compression processing.
- Settings: Configuration dictionary.
Main processing process:
(1) The processing of static files.
#if the Static_path parameter is configured in the settingsifSelf.settings.get ("Static_path"): #get Static_path parameter valuePath = self.settings["Static_path"] Handlers= List (handlersor []) #get static_url_prefix parameter value, default value is/static/Static_url_prefix = Settings.get ("Static_url_prefix", "/static/") #get the Static_handler_class parameter value, which is the static file processing class, the default value is StaticFileHandlerStatic_handler_class = Settings.get ("Static_handler_class", StaticFileHandler)#get Static_handler_args parameter value, other parametersStatic_handler_args = Settings.get ("Static_handler_args", {}) static_handler_args['Path'] =Path#1 A regular expression is composed of path accesses prefixed with Static_url_prefix and Favicon.ico and robots.txt under the root directory . #2 and associate these regular expressions to static_handler_class as tuples #3 Insert one of these tuples to the front of the Hanlders collection forPatterninch[Re.escape (Static_url_prefix) + R"(.*)", R"/(Favicon\.ico)"R"/(Robots\.txt)"]: Handlers.insert (0, (pattern, Static_handler_class, Static_handler_args))
Because the tornado request is handled by Hanlder, the Hanlder decides how to return the response. static files such as CSS files, image files, and other files such as Word, Excel, TXT, and so on, when the browser access to these static files, you need to distinguish between the business Hanlder processing method.
As an example:
The source structure is:
The source code is:
Static_root = Os.path.join (Os.path.dirname (__file__),'Static'). Replace ('\\','/') Settings= {"Static_path": Static_root,"Static_url_prefix":"/static/",'Debug': True,}app= Application (handlers=[url (r"/", mainhanlder), url (r"/story/([0-9]+)", Storyhanlder, Dict (db=db), name=" Story"),], **settings)
Finally, the STYLE.CSS static style sheet file is accessed in the browser. The results are as follows.
Of course, you can configure Static_path, static_url_prefix two parameters according to the structure of your project.
(2) Treatment of handlers
If handlers:
Self.add_handlers (". *$", handlers)
The method of Add_handlers is called here.
(3) The processing of the setting parameter condition
ifSelf.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 modulesifSelf.settings.get ('Autoreload'): fromTornadoImportAutoreloadautoreload.start ()
6.2 Setting Parameter Descriptions
Application can be set to include 3 types of parameters, namely general parameters, authorization and security settings parameters, template parameters, static file configuration parameters.
General parameters:
- L Autoreload: If true, the server process will restart when any source file changes. This option is only available in version 3.2, previously this feature is controlled by the debug option.
- L Debug: Set to debug mode. debug = True equals to Autoreload=true,compiled_template=false,static_hash_cache=false,serve_traceback=true.
- L Default_handler_class and Default_handler_args: If no matching handler is found, use this default handler.s to customize the 404 page.
- L Compresss_response: If set to true. The response returned by the text format is compressed. This feature is only available in the Tornado 4.0 version.
- L GZIP: Obsolete after version 4.0, replaced by Compresss_response
- L Log_function: After each request response, the function is called to record the result. The default implementation is written to the logging module with the logger. This can be customized.
- L Serve_traceback: If set to true. The default error page contains error tracking. This option was added in version 3.2. The previous version implements the functionality by setting Debug=true.
- L Ui_modules and Ui_methods: Sets the mapping of Uimodule or uimethods to the UI template.
Authorization and security settings parameters:
- L Cookie_secret: Used by Requesthandler.get_secure_cookie and set_secure_cookie to issue cookies;
- L Login_url: If the user is not logged in, request processing using the authenticated adorner will be redirected to this URL. You can override the Requesthanlder.get_login_url for further customization.
- L Xsrf_cookies: If set to true, cross-site (cross-site) protection will be initiated.
Template parameters:
- L Autoscape: Automatic escape for template control. Can be set to none to disable escaping, or set to a function name so that all output is passed. The default value is Xhtml_escape. The {% autoescape%} directive can be changed on each template;
- L Compiled_template_cache: The default setting is true. If set to False, each template will be recompiled for each request. This option was added in version 3.2, which was implemented by setting the debug option to the previous version.
- L Template_path: The folder directory containing the template file. You can override Requesthandler.get_template_path to further customize.
- L Template_loader: Set an instance for Tornado.template.BaseLoader with the load from the definition template. If this option is set, then both the Template_path and Autoescape options are ignored. This is done by rewriting Requesthandler.create_template_loader to further customize.
Static File Settings:
- L Static_hash_cache: The default value is true. If False, the static URL will be recalculated for each request. This option was added in version 3.2. Previously this function can only be controlled by the debug settings.
- L Static_path: The directory where the static files reside.
- L Static_url_prefix: URL prefix for static file access. The default is: "/static"
- L Static_handler_class,static_handler_args: You can use a custom static file processor to override the default Tornado.web.StaticFileHandler. Static_handler_args, if set, must be a dictionary, and will be passed to the handler initialize method as a parameter.
6.3 Add_handlers Method
In the constructor processing, there is an important process, that is, the configuration of the handlers processing. is the Add_hanlders method.
The method is to append the given hanlders to our Hanlder list.
- Method definition: Def add_handlers (self, Host_pattern, host_handlers):
- Parameters:
Host_pattern: A regular expression that matches a virtual host. Application default setting is ""
Host_handlers: The handlers to add.
if notHost_pattern.endswith ("$"): Host_pattern + ="$"handlers= []#The handlers with the wildcard Host_pattern is a special#Case-they ' re added in the constructor but should has lower#precedence than the More-precise handlers added later.#If A wildcard handler group exists, it should always is last#the list, so insert new groups just before it.ifSelf.handlers andSelf.handlers[-1][0].pattern = ='.*$': Self.handlers.insert (-1, (Re.compile (Host_pattern), handlers))Else: Self.handlers.append ((Re.compile (Host_pattern), handlers)) forSpecinchhost_handlers:ifisinstance (spec, (tuple, list)):assertLen (spec)inch(2, 3, 4) Spec= Urlspec (*spec) handlers.append (spec)ifSpec.name:ifSpec.nameinchself.named_handlers:app_log.warning ("multiple handlers named%s; replacing previous value", Spec.name) Self.named_handlers[spec.name]= Spec
The main logic of the method is to add handlers to the handlers property of application, but the added Hanlder must first be converted to the Urlspec type. If Hanlder is configured with named parameters, verify the uniqueness of the name and, if there are duplicates, overwrite and record in the log.
Using the if isinstance (spec, (tuple, list)) source can be seen, hanlders configuration type can have two types, one is a tuple set, one is a list, and if it is a list, then the items in the list is the Urlspec type. And each handler can be named. As an example: application can be created in the following two ways:
Mode one: Hanlders is passed with the Urlspec object list and can be named.
App = Application (handlers=[ url (r"/", Mainhanlder), URL (r " /story/([0-9]+) ", Storyhanlder, Dict (db=db), name="story"**settings)
Method Two: Hanlders is passed with a tuple set
App = Application (handlers=[ url (r"/", Mainhanlder), URL (r " /story/([0-9]+) ", Storyhanlder, Dict (db=db), name="story"**settings)
6 Application Source Analysis