Tornado.web contains most of the main features of the web framework, and application is one of the important classes
The function of the application class is to implement the URI forwarding, passing the application instance to Httpserver, and when the supervisor hears the request, forwards the request sent back by the server, and processes the request by calling __call__.
Application Source:
Class Application (Httputil. httpserverconnectiondelegate): "" A collection of the request handlers that make up A Web application. Instances of this class is callable and can be passed directly to Httpserver to serve the application:: Applica tion = 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_CL ) tuples. When we receive requests, we iterate over the list in order and instantiate an instance of the first request class W Hose RegExp matches the request path. The request class can be specified as either a class object or a (fully-qualified) name. Each of the tuple can contain additional elements, which correspond to the arguments ' Urlspec '. (Prior to Tornado 3.2, this is only tuples of or three elementswere allowed). A dictionary may passed as the third element of the tuple, which'll be used as keyword arguments to the handler ' s Constructor and ' ~requesthandler.initialize ' method. This-pattern is used for the ' StaticFileHandler '-example (note that a ' StaticFileHandler ' can be installed a Utomatically 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 take s 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'll serve those files from the "/static/" URI (this was configurable with the ' static_url_prefix ' setting), a nd we'll serve '/favicon.ico '' and '/robots.txt ' from the same directory. A custom subclass of ' StaticFileHandler ' can is specified with the ' Static_handler_class ' setting. "" "Def __init__ (self, Handlers=none, default_host=" ", Transforms=none, **settings): If transfor MS is None:self.transforms = [] If Settings.get ("Compress_response") or Settings.get ("gzip"): Self.transforms.append (gzipcontentencoding) else:self.transforms = Transforms Self.han Dlers = [] 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 (set Tings.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", Staticfile Handler) 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, STA Tic_handler_args)) If Handlers:self.add_handlers (". *$", handlers) if Self.settings.get (' Debug '): # if debug = True, turn on the Autoreload and Serve_traceback functions (Error message displayed), turn off Compiled_template_cache and Static_hash_cache<span Style= "Font-family:arial, HelvEtica, Sans-serif; " > Functions </span> self.settings.setdefault (' autoreload ', True) self.settings.setdefault (' Compiled_ Template_cache ', false) Self.settings.setdefault (' Static_hash_cache ', false) Self.settings.setdefaul T (' Serve_traceback ', True) # automatically reload modified modules if Self.settings.get (' Autoreload '): # service can Enough to automatically reload new code from Tornado import Autoreload Autoreload.start () def listen (self, port, address= "" , **kwargs): "" "starts an HTTP server for this application on the given port. This was a convenience alias for creating a '. Httpserver ' object and calling its listen method. Keyword arguments not supported by ' Httpserver.listen <. Tcpserver.listen> ' is passed to the '. Httpserver ' constructor. For the advanced uses (e.g Multi-process mode), does not use the This method; Create an '. Httpserver ' and call it '. Tcpserver.bind '/'. TCPServer. Start ' methods directly. Note that after calling this method, you still need-to-call ' Ioloop.instance (). Start () "To start the server. Accept ports, addresses, other parameters establish an HTTP server and listen to the Port "" "# import is here rather than top level because httpserver # is not importable on AppEngine from tornado.httpserver import httpserver server = Httpserver (self, **kwarg s) Server.listen (port, address) def add_handlers (self, Host_pattern, host_handlers): "" "appends the given Handlers to our handler list. Host patterns is processed sequentially in the order they were added. All matching patterns'll be considered. "" "If Not Host_pattern.endswith (" $ "): Host_pattern + =" $ "handlers = [] # The handlers WI Th 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 be-last on the list, so insert new groups just before it. If self.handlers and Self.handlers[-1][0].pattern = = '. *$ ': Self.handlers.insert ( -1, (Re.compile (Host_pattern), handlers)) Else:self.handlers.append ((Re.compile (Host_pattern), handlers)) for spec in Host_han Dlers:if isinstance (spec, (tuple, list)): Assert Len (Spec) in (2, 3, 4) spec = U Rlspec (*SPEC) handlers.append (spec) if Spec.name:if spec.name in Self.named_handlers : App_log.warning ("multiple handlers named%s; Replacing previous value ", Spec.name) self.named_handlers[spec.name] = Spec Def a Dd_transform (self, Transform_class): Self.transforms.append (Transform_class) def _get_host_handlers (self, reques T): host = Request.host.lower (). Split (': ') [0] matches = [] for pattern, handlers in Self.handlers:if Pattern.match (host): MATCHES.E Xtend (Handlers) # Look for default host if not behind load balancer (for debugging) if not matches and "X-re Al-ip "Not in request.headers:for pattern, handlers in Self.handlers:if Pattern.match (self.def Ault_host): Matches.extend (handlers) return matches or None def _load_ui_methods (self, method s): If Isinstance (Methods, types. Moduletype): Self._load_ui_methods (Dict ((N, GetAttr (methods, n)) for N in Dir (methods))) Elif Isinstance (Methods, list): for M in Methods:self._load_ui_methods (m ) else:for name, FN in Methods.items (): If Not Name.startswith ("_") and Hasattr (FN, "__c All__ ") and name[0].lower () = = Name[0]: self.ui_methods[name] = fn def _load_ui_modules (self, modules): If Isinstance (modules, types. Moduletype): Self._load_ui_modules (Dict ((N, getattr (modules, n)) for N in Dir (modules))) Elif isinstance (modules, list): for M in Modules:self._load_ui_modules (m ) Else:assert isinstance (modules, dict) for name, CLS in Modules.items (): Try : If Issubclass (CLS, uimodule): self.ui_modules[name] = CLS EXCEP T Typeerror:pass def start_request (self, Connection): # Modern Httpserver interface R Eturn _requestdispatcher (self, Connection) def __call__ (self, request): # Legacy Httpserver interface Dis Patcher = _requestdispatcher (self, None) dispatcher.set_request (Request) return Dispatcher.execute () def Reverse_url (self, Name, *args): "" "Returns a URL path for hAndler named ' name ' the handler must is added to the application as a named ' Urlspec '. The Args would be substituted-capturing groups in the ' Urlspec ' regex. They'll is converted to strings if necessary, encoded as UTF8, and url-escaped. Returns the matching URL path according to name "" If Name in Self.named_handlers:return self.named_handlers[name].reverse (*ar GS) Raise Keyerror ("%s not found with named URLs"% name) def log_request (self, Handler): "" "writes a Compl eted HTTP request to the logs. By default writes to the Python root logger. To behavior either subclass application and override this method, or pass a function in the APPL Ication Settings dictionary as ' Log_function '. Write the HTTP request into the log HTTP status code less than 400 for normal greater than or equal to 400 less than 500<span style= "font-family:arial, Helvetica, Sans-serif;" > For </span><span style= "font-family:arial, Helvetica, Sans-serif;" > Request Error </SPAN> Greater than 500 is server error "" "If" log_function "in self.settings:self.settings[" Log_function "] (handler) return if Handler.get_status () < 400:log_method = Access_log.info elif Handler.get_statu S () < 500:log_method = Access_log.warning Else:log_method = Access_log.error requ Est_time = 1000.0 * Handler.request.request_time () Log_method ("%d%s%.2fms", Handler.get_status (), Handler._request_summary (), Request_time)
constructor function
__init__ (self,handlers=none,default_host= "", transforms=none,**settings)
It accepts handlers (tuples that contain matching rules and RequestHandler), Default_host (default host), transforms (output does chunked and compressed conversions), and setting (contains the configured dictionary).
Establish path routing rules for hosts
Method
Listen (self, port, address= "", **kwargs) establishes an HTTP server and listens on that port
Add_handlers (self, host_pattern, host_handlers) adds handler to the handler list. Host_pattern are processed in the order in which they were added, adding the path routing rules for the host
Add_transform (self, transform_class) adds Transform_class to Self.transforms, transforms the output into chunks and compression
_get_host_handlers (self, request) looking for the handlers that belongs to this request
_load_ui_methods (self, methods) adding methods in Self.ui_methods
_load_ui_modules (self, modules) adding methods in Self.ui_modules
Reverse_url (self, name, *args) uses name to return a matching URL path
__call__ (self, request) is called when the server accepts a new connection accept HttpRequest object calls the Execute method according to HttpRequest
Start_request (self, connection) function with __call__
Log_request (self, Handler) writes the HTTP request into the log.
The principle of dynamic automatic compilation of code when Debug=true
Application object instantiation, give "debug=true" parameter , turn on Autoreload and Serve_traceback function (Error message), close Compiled_template_ Cache and Static_hash_cache Features
Autoreload: When changing the source code, the server process will be able to automatically reload the new code and reboot.
serve _traceback: If traceback and with this we can see where the error do convenient debugging
compiled_template_cache: Compiling the template cache If you close When refreshed The server's template will be load .
static _hash_cache: Static hash cache , If you close When refreshed with static_url () will be load files that need to be read under static, rather than files that have already been cached
Tornado Source Analysis-application