tornado.web — RequestHandler and Application classes¶
tornado.web
provides a simple web framework with asynchronousfeatures that allow it to scale to large numbers of open connections,making it ideal for long polling.
Here is a simple “Hello, world” example app:
- import tornado.ioloop
- import tornado.web
- class MainHandler(tornado.web.RequestHandler):
- def get(self):
- self.write("Hello, world")
- if __name__ == "__main__":
- application = tornado.web.Application([
- (r"/", MainHandler),
- ])
- application.listen(8888)
- tornado.ioloop.IOLoop.current().start()
See the 用户手册 for additional information.
Thread-safety notes¶
In general, methods on RequestHandler
and elsewhere in Tornado arenot thread-safe. In particular, methods such aswrite()
, finish()
, andflush()
must only be called from the main thread. Ifyou use multiple threads it is important to use IOLoop.add_callback
to transfer control back to the main thread before finishing therequest.
Request handlers¶
- class
tornado.web.
RequestHandler
(application, request, **kwargs)[源代码]¶
Base class for HTTP request handlers.
Subclasses must define at least one of the methods defined in the“Entry points” section below.
Entry points¶
RequestHandler.
initialize
()[源代码]¶
Hook for subclass initialization. Called for each request.
A dictionary passed as the third argument of a url spec will besupplied as keyword arguments to initialize().
Example:- class ProfileHandler(RequestHandler):
def initialize(self, database):
self.database = database
def get(self, username):
…
app = Application([
(r'/user/(.)', ProfileHandler, dict(database=database)),
])
- class ProfileHandler(RequestHandler):
RequestHandler.
prepare
()[源代码]¶
Called at the beginning of a request beforeget
/post
/etc.
Override this method to perform common initialization regardlessof the request method.
Asynchronous support: Decorate this method withgen.coroutine
orreturn_future
to make it asynchronous (theasynchronous
decorator cannot be used onprepare
).If this method returns aFuture
execution will not proceeduntil theFuture
is done.
3.1 新版功能: Asynchronous support.
RequestHandler.
onfinish
()[源代码]¶
Called after the end of a request.
Override this method to perform cleanup, logging, etc.This method is a counterpart toprepare
.on_finish
maynot produce any output, as it is called after the responsehas been sent to the client.
Implement any of the following methods (collectively known as theHTTP verb methods) to handle the corresponding HTTP method.These methods can be made asynchronous with one of the followingdecorators:
gen.coroutine
, return_future
, or asynchronous
.To support a method not on this list, override the class variable
SUPPORTED_METHODS
:
- class WebDAVHandler(RequestHandler):
SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ('PROPFIND',)
def propfind(self):
pass
Input¶
RequestHandler.
getargument
(_name, default=<object object>, strip=True)[源代码]¶
Returns the value of the argument with the given name.
If default is not provided, the argument is considered to berequired, and we raise aMissingArgumentError
if it is missing.
If the argument appears in the url more than once, we return thelast value.
The returned value is always unicode.
RequestHandler.
getarguments
(_name, strip=True)[源代码]¶
Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
RequestHandler.
getquery_argument
(_name, default=<object object>, strip=True)[源代码]¶
Returns the value of the argument with the given namefrom the request query string.
If default is not provided, the argument is considered to berequired, and we raise aMissingArgumentError
if it is missing.
If the argument appears in the url more than once, we return thelast value.
The returned value is always unicode.
3.2 新版功能.
RequestHandler.
getquery_arguments
(_name, strip=True)[源代码]¶
Returns a list of the query arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
3.2 新版功能.
RequestHandler.
getbody_argument
(_name, default=<object object>, strip=True)[源代码]¶
Returns the value of the argument with the given namefrom the request body.
If default is not provided, the argument is considered to berequired, and we raise aMissingArgumentError
if it is missing.
If the argument appears in the url more than once, we return thelast value.
The returned value is always unicode.
3.2 新版功能.
RequestHandler.
getbody_arguments
(_name, strip=True)[源代码]¶
Returns a list of the body arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.
3.2 新版功能.
RequestHandler.
decodeargument
(_value, name=None)[源代码]¶
Decodes an argument from the request.
The argument has been percent-decoded and is now a byte string.By default, this method decodes the argument as utf-8 and returnsa unicode string, but this may be overridden in subclasses.
This method is used as a filter for bothget_argument()
and forvalues extracted from the url and passed toget()
/post()
/etc.
The name of the argument is provided if known, but may be None(e.g. for unnamed groups in the url regex).
RequestHandler.
request
¶
Thetornado.httputil.HTTPServerRequest
object containing additionalrequest parameters including e.g. headers and body data.
RequestHandler.
path_args
¶
RequestHandler.
path_kwargs
¶
Thepath_args
andpath_kwargs
attributes contain thepositional and keyword arguments that are passed to theHTTP verb methods. These attributes are setbefore those methods are called, so the values are availableduringprepare
.
Output¶
RequestHandler.
setstatus
(_status_code, reason=None)[源代码]¶
Sets the status code for our response.
|参数:
|——-
|
- status_code (int) – Response status code. If reason is None,it must be present in httplib.responses.
- reason (string) – Human-readable reason phrase describing the statuscode. If None, it will be filled in fromhttplib.responses.
RequestHandler.
setheader
(_name, value)[源代码]¶
Sets the given response header name and value.
If a datetime is given, we automatically format it according to theHTTP specification. If the value is not a string, we convert it toa string. All header values are then encoded as UTF-8.
RequestHandler.
addheader
(_name, value)[源代码]¶
Adds the given response header and value.
Unlikeset_header
,add_header
may be called multiple timesto return multiple values for the same header.
RequestHandler.
clearheader
(_name)[源代码]¶
Clears an outgoing header, undoing a previousset_header
call.
Note that this method does not apply to multi-valued headersset byadd_header
.
RequestHandler.
setdefault_headers
()[源代码]¶
Override this to set HTTP headers at the beginning of the request.
For example, this is the place to set a customServer
header.Note that setting such headers in the normal flow of requestprocessing may not do what you want, since headers may be resetduring error handling.
RequestHandler.
write
(_chunk)[源代码]¶
Writes the given chunk to the output buffer.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and setthe Content-Type of the response to beapplication/json
.(if you want to send JSON as a differentContent-Type
, callsetheader _after calling write()).
Note that lists are not converted to JSON because of a potentialcross-site security vulnerability. All JSON output should bewrapped in a dictionary. More details athttp://haacked.com/archive/2009/06/25/json-hijacking.aspx/ andhttps://github.com/facebook/tornado/issues/1009
RequestHandler.
flush
(include_footers=False, callback=None)[源代码]¶
Flushes the current output buffer to the network.
Thecallback
argument, if given, can be used for flow control:it will be run when all flushed data has been written to the socket.Note that only one flush callback can be outstanding at a time;if another flush occurs before the previous flush’s callbackhas been run, the previous callback will be discarded.
在 4.0 版更改: Now returns aFuture
if no callback is given.
RequestHandler.
render
(template_name, **kwargs)[源代码]¶
Renders the template with the given arguments as the response.
RequestHandler.
renderstring
(_template_name, **kwargs)[源代码]¶
Generate the given template with the given arguments.
We return the generated byte string (in utf8). To generate andwrite a template as a response, use render() above.
RequestHandler.
gettemplate_namespace
()[源代码]¶
Returns a dictionary to be used as the default template namespace.
May be overridden by subclasses to add or modify values.
The results of this method will be combined with additionaldefaults in thetornado.template
module and keyword argumentstorender
orrender_string
.
RequestHandler.
redirect
(_url, permanent=False, status=None)[源代码]¶
Sends a redirect to the given (optionally relative) URL.
If thestatus
argument is specified, that value is used as theHTTP status code; otherwise either 301 (permanent) or 302(temporary) is chosen based on thepermanent
argument.The default is 302 (temporary).
RequestHandler.
senderror
(_status_code=500, **kwargs)[源代码]¶
Sends the given HTTP error code to the browser.
Ifflush()
has already been called, it is not possible to sendan error, so this method will simply terminate the response.If output has been written but not yet flushed, it will be discardedand replaced with the error page.
Overridewrite_error()
to customize the error page that is returned.Additional keyword arguments are passed through towrite_error
.
RequestHandler.
writeerror
(_status_code, **kwargs)[源代码]¶
Override to implement custom error pages.writeerror
may callwrite
,render
,set_header
, etcto produce output as usual.
If this error was caused by an uncaught exception (includingHTTPError), anexc_info
triple will be available askwargs["exc_info"]
. Note that this exception may not bethe “current” exception for purposes of methods likesys.exc_info()
ortraceback.format_exc
.
RequestHandler.
data_received
(_chunk)[源代码]¶
Implement this method to handle streamed request data.
Requires thestream_request_body
decorator.
Cookies¶
An alias forself.request.cookies
.
Gets the value of the cookie with the given name, else default.
Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morseldirectly.See http://docs.python.org/library/cookie.html#morsel-objectsfor available attributes.
Deletes the cookie with the given name.
Due to limitations of the cookie protocol, you must pass the samepath and domain to clear a cookie as were used when that cookiewas set (but there is no way to find out on the server sidewhich values were used for a given cookie).
Deletes all the cookies the user sent with this request.
Seeclear_cookie
for more information on the path and domainparameters.
在 3.2 版更改: Added thepath
anddomain
parameters.
Returns the given signed cookie if it validates, or None.
The decoded cookie value is returned as a byte string (unlikeget_cookie
).
在 3.2.1 版更改: Added theminversion
argument. Introduced cookie version 2;both versions 1 and 2 are accepted by default.
Returns the signing key version of the secure cookie.
The version is returned as int.
Signs and timestamps a cookie so it cannot be forged.
You must specify thecookiesecret
setting in your Applicationto use this method. It should be a long, random sequence of bytesto be used as the HMAC secret for the signature.
To read a cookie set with this method, useget_secure_cookie()
.
Note that theexpires_days
parameter sets the lifetime of thecookie in the browser, but is independent of themax_age_days
parameter toget_secure_cookie
.
Secure cookies may contain arbitrary byte values, not just unicodestrings (unlike regular cookies)
在 3.2.1 版更改: Added theversion
argument. Introduced cookie version 2and made it the default.
RequestHandler.
create_signed_value
(_name, value, version=None)[源代码]¶
Signs and timestamps a string so it cannot be forged.
Normally used via setsecure_cookie, but provided as a separatemethod for non-cookie uses. To decode a value not storedas a cookie use the optional value argument to get_secure_cookie.
在 3.2.1 版更改: Added theversion
argument. Introduced cookie version 2and made it the default.
tornado.web.
MIN_SUPPORTED_SIGNED_VALUE_VERSION
= 1¶
The oldest signed value version supported by this version of Tornado.
Signed values older than this version cannot be decoded.
3.2.1 新版功能.
tornado.web.
MAX_SUPPORTED_SIGNED_VALUE_VERSION
= 2¶
The newest signed value version supported by this version of Tornado.
Signed values newer than this version cannot be decoded.
3.2.1 新版功能.
tornado.web.
DEFAULT_SIGNED_VALUE_VERSION
= 2¶
The signed value version produced byRequestHandler.create_signed_value
.
May be overridden by passing aversion
keyword argument.
3.2.1 新版功能.
tornado.web.
DEFAULT_SIGNED_VALUE_MIN_VERSION
= 1_¶
The oldest signed value accepted byRequestHandler.get_secure_cookie
.
May be overridden by passing amin_version
keyword argument.
3.2.1 新版功能.
Other¶
RequestHandler.
application
¶
TheApplication
object serving this request
RequestHandler.
checketag_header
()[源代码]¶
Checks theEtag
header against requests’sIf-None-Match
.
ReturnsTrue
if the request’s Etag matches and a 304 should bereturned. For example:- self.set_etag_header()
if self.check_etag_header():
self.set_status(304)
return
This method is called automatically when the request is finished,but may be called earlier for applications that overridecompute_etag
and want to do an early check forIf-None-Match
before completing the request. TheEtag
header should be set(perhaps withset_etag_header
) before calling this method.- self.set_etag_header()
Verifies that the_xsrf
cookie matches the_xsrf
argument.
To prevent cross-site request forgery, we set an_xsrf
cookie and include the same value as a non-cookiefield with allPOST
requests. If the two do not match, wereject the form submission as a potential forgery.
The_xsrf
value may be set as either a form field named_xsrf
or in a custom HTTP header namedX-XSRFToken
orX-CSRFToken
(the latter is accepted for compatibility with Django).
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
Prior to release 1.1.1, this check was ignored if the HTTP headerX-Requested-With: XMLHTTPRequest
was present. This exceptionhas been shown to be insecure and has been removed. For moreinformation please seehttp://www.djangoproject.com/weblog/2011/feb/08/security/http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails
在 3.2.2 版更改: Added support for cookie version 2. Both versions 1 and 2 aresupported.
RequestHandler.
compute_etag
()[源代码]¶
Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations,or may return None to disable tornado’s default etag support.
RequestHandler.
create_template_loader
(_template_path)[源代码]¶
Returns a new template loader for the given path.
May be overridden by subclasses. By default returns adirectory-based loader on the given path, using theautoescape
andtemplatewhitespace
applicationsettings. If atemplate_loader
application setting issupplied, uses that instead.
RequestHandler.
current_user
¶
The authenticated user for this request.
This is set in one of two ways:
-
A subclass may override get_current_user(), which will be calledautomatically the first time self.current_user is accessed.get_current_user() will only be called once per request,and is cached for future access:
def get_current_user(self):
user_cookie = self.get_secure_cookie("user")
if user_cookie:
return json.loads(user_cookie)
return None
-
It may be set as a normal variable, typically from an overriddenprepare():
@gen.coroutine
def prepare(self):
user_id_cookie = self.get_secure_cookie("user_id")
if user_id_cookie:
self.current_user = yield load_user(user_id_cookie)
Note thatprepare()
may be a coroutine whileget_current_user()
may not, so the latter form is necessary if loading the user requiresasynchronous operations.
The user object may any type of the application’s choosing.
RequestHandler.
get_browser_locale
(_default='en_US')[源代码]¶
Determines the user’s locale fromAccept-Language
header.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
RequestHandler.
getcurrent_user
()[源代码]¶
Override to determine the current user from, e.g., a cookie.
This method may not be a coroutine.
RequestHandler.
get_login_url
()[源代码]¶
Override to customize the login URL based on the request.
By default, we use thelogin_url
application setting.
RequestHandler.
get_template_path
()[源代码]¶
Override to customize template path for each handler.
By default, we use thetemplate_path
application setting.Return None to load templates relative to the calling file.
RequestHandler.
get_user_locale
()[源代码]¶
Override to determine the locale from the authenticated user.
If None is returned, we fall back toget_browser_locale()
.
This method should return atornado.locale.Locale
object,most likely obtained via a call liketornado.locale.get("en")
RequestHandler.
locale
¶
The locale for the current session.
Determined by eitherget_user_locale
, which you can override toset the locale based on, e.g., a user preference stored in adatabase, orget_browser_locale
, which uses theAccept-Language
header.
RequestHandler.
log_exception
(_typ, value, tb)[源代码]¶
Override to customize logging of uncaught exceptions.
By default logs instances ofHTTPError
as warnings withoutstack traces (on thetornado.general
logger), and allother exceptions as errors with stack traces (on thetornado.application
logger).
3.1 新版功能.
RequestHandler.
onconnection_close
()[源代码]¶
Called in async handlers if the client closed the connection.
Override this to clean up resources associated withlong-lived connections. Note that this method is called only ifthe connection was closed during asynchronous processing; if youneed to do cleanup after every request overrideon_finish
instead.
Proxies may keep a connection open for a time (perhapsindefinitely) after the client has gone away, so this methodmay not be called promptly after the end user closes theirconnection.
RequestHandler.
require_setting
(_name, feature='this feature')[源代码]¶
Raises an exception if the given app setting is not defined.
RequestHandler.
reverseurl
(_name, *args)[源代码]¶
Alias forApplication.reverse_url
.
RequestHandler.
setetag_header
()[源代码]¶
Sets the response’s Etag header usingself.compute_etag()
.
Note: no header will be set ifcompute_etag()
returnsNone
.
This method is called automatically when the request is finished.
RequestHandler.
settings
¶
An alias forself.application.settings
.
RequestHandler.
static_url
(_path, include_host=None, **kwargs)[源代码]¶
Returns a static URL for the given relative static file path.
This method requires you set thestatic_path
setting in yourapplication (which specifies the root directory of your staticfiles).
This method returns a versioned url (by default appending?v=<signature>
), which allows the static files to becached indefinitely. This can be disabled by passinginclude_version=False
(in the default implementation;other static file implementations are not required to supportthis, but they may support other options).
By default this method returns URLs relative to the currenthost, but ifinclude_host
is true the URL returned will beabsolute. If this handler has aninclude_host
attribute,that value will be used as the default for allstatic_url
calls that do not passinclude_host
as a keyword argument.
RequestHandler.
xsrf_form_html
()[源代码]¶
An HTML<input/>
element to be included with all POST forms.
It defines the_xsrf
input value, which we check on all POSTrequests to prevent cross-site request forgery. If you have setthexsrf_cookies
application setting, you must include thisHTML within all of your HTML forms.
In a template, this method should be called with{% module
xsrf_form_html() %}
Seecheck_xsrf_cookie()
above for more information.
RequestHandler.
xsrf_token
¶
The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an ‘_xsrf’ cookieand include the same ‘_xsrf’ value as an argument with all POSTrequests. If the two do not match, we reject the form submissionas a potential forgery.
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
在 3.2.2 版更改: The xsrf token will now be have a random mask applied in everyrequest, which makes it safe to include the token in pagesthat are compressed. See http://breachattack.com for moreinformation on the issue fixed by this change. Old (version 1)cookies will be converted to version 2 when this method is calledunless thexsrf_cookie_version
Application
setting isset to 1.
在 4.3 版更改: Thexsrf_cookie_kwargs
Application
setting may beused to supply additional cookie options (which will bepassed directly toset_cookie
). For example,xsrf_cookie_kwargs=dict(httponly=True, secure=True)
will set thesecure
andhttponly
flags on the_xsrf
cookie.
Application configuration¶
- class
tornado.web.
Application
(handlers=None, default_host='', transforms=None, **settings)[源代码]¶
A collection of request handlers that make up a web application.
Instances of this class are callable and can be passed directly toHTTPServer to serve the application:- application = web.Application([
(r"/", MainPageHandler),
])
httpserver = httpserver.HTTPServer(application)
http_server.listen(8080)
ioloop.IOLoop.current().start()
The constructor for this class takes in a list ofURLSpec
objectsor (regexp, request_class) tuples. When we receive requests, weiterate over the list in order and instantiate an instance of thefirst 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 thearguments to theURLSpec
constructor. (Prior to Tornado 3.2,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’sconstructor andinitialize
method. This patternis used for theStaticFileHandler
in this example (note that aStaticFileHandler
can be installed automatically with thestatic_path setting described below):- application = web.Application([
(r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
])
We support virtual hosts with theadd_handlers
method, which takes ina 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 thestatic_path
settingas a keyword argument. We will serve those files from the/static/
URI (this is configurable with thestatic_url_prefix
setting), and we will serve/favicon.ico
and/robots.txt
from the same directory. A custom subclass ofStaticFileHandler
can be specified with thestatic_handler_class
setting.settings
¶
Additional keyword arguments passed to the constructor aresaved in thesettings
dictionary, and are often referred toin documentation as “application settings”. Settings areused to customize various aspects of Tornado (although insome cases richer customization is possible by overridingmethods in a subclass ofRequestHandler
). Someapplications also like to use thesettings
dictionary as away to make application-specific settings available tohandlers without using global variables. Settings used inTornado are described below.
General settings:
- autoreload: If True, the server process will restartwhen any source files change, as described in Debug 模式 和 自动重新加载.This option is new in Tornado 3.2; previously this functionalitywas controlled by the debug setting.
- debug: Shorthand for several debug mode settings,described in Debug 模式 和 自动重新加载. Setting debug=True isequivalent to autoreload=True, compiled_template_cache=False,static_hash_cache=False, serve_traceback=True.
- default_handler_class and default_handler_args:This handler will be used if no other match is found;use this to implement custom 404 pages (new in Tornado 3.2).
- compress_response: If True, responses in textual formatswill be compressed automatically. New in Tornado 4.0.
- gzip: Deprecated alias for compress_response sinceTornado 4.0.
- log_function: This function will be called at the endof every request to log the result (with one argument, theRequestHandler object). The default implementationwrites to the logging module’s root logger. May also becustomized by overriding Application.log_request.
- serve_traceback: If true, the default error pagewill include the traceback of the error. This option is new inTornado 3.2; previously this functionality was controlled bythe debug setting.
- ui_modules and ui_methods: May be set to a mappingof UIModule or UI methods to be made available to templates.May be set to a module, dictionary, or a list of modulesand/or dicts. See UI 模版 for more details.
Authentication and security settings:
- cookie_secret: Used by RequestHandler.get_secure_cookieand set_secure_cookie to sign cookies.
- key_version: Used by requestHandler set_secure_cookieto sign cookies with a specific key when cookie_secretis a key dictionary.
- login_url: The authenticated decorator will redirectto this url if the user is not logged in. Can be furthercustomized by overriding RequestHandler.get_login_url
- xsrf_cookies: If true, 跨站请求伪造防护 will be enabled.
- xsrf_cookie_version: Controls the version of new XSRFcookies produced by this server. Should generally be leftat the default (which will always be the highest supportedversion), but may be set to a lower value temporarilyduring version transitions. New in Tornado 3.2.2, whichintroduced XSRF cookie version 2.
- xsrf_cookie_kwargs: May be set to a dictionary ofadditional arguments to be passed to RequestHandler.set_cookiefor the XSRF cookie.
- twitter_consumer_key, twitter_consumer_secret,friendfeed_consumer_key, friendfeed_consumer_secret,google_consumer_key, google_consumer_secret,facebook_api_key, facebook_secret: Used in thetornado.auth module to authenticate to various APIs.
Template settings:
- autoescape: Controls automatic escaping for templates.May be set to None to disable escaping, or to the _name_of a function that all output should be passed through.Defaults to "xhtml_escape". Can be changed on a per-templatebasis with the {% autoescape %} directive.
- compiled_template_cache: Default is True; if Falsetemplates will be recompiled on every request. This optionis new in Tornado 3.2; previously this functionality was controlledby the debug setting.
- template_path: Directory containing template files. Can befurther customized by overriding RequestHandler.get_template_path
- template_loader: Assign to an instance oftornado.template.BaseLoader to customize template loading.If this setting is used the template_path and autoescapesettings are ignored. Can be further customized by overridingRequestHandler.create_template_loader.
- template_whitespace: Controls handling of whitespace intemplates; see tornado.template.filter_whitespace for allowedvalues. New in Tornado 4.3.
Static file settings:
- static_hash_cache: Default is True; if Falsestatic urls will be recomputed on every request. This optionis new in Tornado 3.2; previously this functionality was controlledby the debug setting.
- static_path: Directory from which static files will beserved.
- static_url_prefix: Url prefix for static files,defaults to "/static/".
- static_handler_class, static_handler_args: May be set touse a different handler for static files instead of the defaulttornado.web.StaticFileHandler. static_handler_args, if set,should be a dictionary of keyword arguments to be passed to thehandler’s initialize method.
listen
(_port, address='', **kwargs)[源代码]¶
Starts an HTTP server for this application on the given port.
This is a convenience alias for creating anHTTPServer
object and calling its listen method. Keyword arguments notsupported byHTTPServer.listen
are passed to theHTTPServer
constructor. For advanced uses(e.g. multi-process mode), do not use this method; create anHTTPServer
and call itsTCPServer.bind
/TCPServer.start
methods directly.
Note that after calling this method you still need to callIOLoop.current().start()
to start the server.
Returns theHTTPServer
object.
在 4.3 版更改: Now returns theHTTPServer
object.
addhandlers
(_host_pattern, host_handlers)[源代码]¶
Appends the given handlers to our handler list.
Host patterns are processed sequentially in the order they wereadded. All matching patterns will be considered.
- application = web.Application([
- _class
tornado.web.
URLSpec
(pattern, handler, kwargs=None, name=None)[源代码]¶
Specifies mappings between URLs and handlers.
Parameters:
- pattern: Regular expression to be matched. Any capturinggroups in the regex will be passed in to the handler’sget/post/etc methods as arguments (by keyword if named, byposition if unnamed. Named and unnamed capturing groups maymay not be mixed in the same rule).
- handler: RequestHandler subclass to be invoked.
- kwargs (optional): A dictionary of additional argumentsto be passed to the handler’s constructor.
- name (optional): A name for this handler. Used byApplication.reverse_url.
TheURLSpec
class is also available under the nametornado.web.url
.
Decorators¶
tornado.web.
asynchronous
(method)[源代码]¶
Wrap request handler methods with this if they are asynchronous.
This decorator is for callback-style asynchronous methods; forcoroutines, use the@gen.coroutine
decorator without@asynchronous
. (It is legal for legacy reasons to use the twodecorators together provided@asynchronous
is first, but@asynchronous
will be ignored in this case)
This decorator should only be applied to the HTTP verbmethods; its behavior is undefined for any other method.This decorator does not make a method asynchronous; it tellsthe framework that the method is asynchronous. For this decoratorto be useful the method must (at least sometimes) do somethingasynchronous.
If this decorator is given, the response is not finished when themethod returns. It is up to the request handler to callself.finish()
to finish the HTTPrequest. Without this decorator, the request is automaticallyfinished when theget()
orpost()
method returns. Example:- class MyRequestHandler(RequestHandler):
@asynchronous
def get(self):
http = httpclient.AsyncHTTPClient()
http.fetch("http://friendfeed.com/", self.on_download)
def _on_download(self, response):
self.write("Downloaded!")
self.finish()
在 3.1 版更改: The ability to use@gen.coroutine
without@asynchronous
.
在 4.3 版更改: Returning anything butNone
or ayieldable object from a method decorated with@asynchronous
is an error. Such return values were previously ignored silently.- class MyRequestHandler(RequestHandler):
tornado.web.
authenticated
(_method)[源代码]¶
Decorate methods with this to require that the user be logged in.
If the user is not logged in, they will be redirected to the configuredlogin url
.
If you configure a login url with a query parameter, Tornado willassume you know what you’re doing and use it as-is. If not, itwill add anext
parameter so the login page knows where to sendyou once you’re logged in.
tornado.web.
addslash
(method)[源代码]¶
Use this decorator to add a missing trailing slash to the request path.
For example, a request to/foo
would redirect to/foo/
with thisdecorator. Your request handler mapping should use a regular expressionliker'/foo/?'
in conjunction with using the decorator.
tornado.web.
removeslash
(method)[源代码]¶
Use this decorator to remove trailing slashes from the request path.
For example, a request to/foo/
would redirect to/foo
with thisdecorator. Your request handler mapping should use a regular expressionliker'/foo/*'
in conjunction with using the decorator.
tornado.web.
streamrequest_body
(_cls)[源代码]¶
Apply toRequestHandler
subclasses to enable streaming body support.
This decorator implies the following changes:
- HTTPServerRequest.body is undefined, and body arguments will notbe included in RequestHandler.get_argument.
- RequestHandler.prepare is called when the request headers have beenread instead of after the entire body has been read.
- The subclass must define a method datareceived(self, data):, whichwill be called zero or more times as data is available. Note thatif the request has an empty body, data_received may not be called.
- prepare and data_received may return Futures (such as via@gen.coroutine, in which case the next method will not be calleduntil those futures have completed.
- The regular HTTP method (post, put, etc) will be called afterthe entire body has been read.
There is a subtle interaction betweendata_received
and asynchronousprepare
: The first call todata_received
may occur at any pointafter the call toprepare
has returned _or yielded.
Everything else¶
- exception
tornado.web.
HTTPError
(status_code=500, log_message=None, *args, **kwargs)[源代码]¶
An exception that will turn into an HTTP error response.
Raising anHTTPError
is a convenient alternative to callingRequestHandler.send_error
since it automatically ends thecurrent function.
To customize the response sent with anHTTPError
, overrideRequestHandler.write_error
.
|参数:
|——-
|
- status_code (int) – HTTP status code. Must be listed inhttplib.responses unless the reasonkeyword argument is given.
- log_message (string) – Message to be written to the log for this error(will not be shown to the user unless the Application is in debugmode). May contain %s-style placeholders, which will be filledin with remaining positional parameters.
- reason (string) – Keyword-only argument. The HTTP “reason” phraseto pass in the status line along with statuscode. Normallydetermined automatically from status_code, but can be usedto use a non-standard numeric code.
- _exception
tornado.web.
Finish
[源代码]¶
An exception that ends the request without producing an error response.
WhenFinish
is raised in aRequestHandler
, the request willend (callingRequestHandler.finish
if it hasn’t already beencalled), but the error-handling methods (includingRequestHandler.write_error
) will not be called.
IfFinish()
was created with no arguments, the pending responsewill be sent as-is. IfFinish()
was given an argument, thatargument will be passed toRequestHandler.finish()
.
This can be a more convenient way to implement custom error pagesthan overridingwriteerror
(especially in library code):- if self.current_user is None:
self.set_status(401)
self.set_header('WWW-Authenticate', 'Basic realm="something"')
raise Finish()
在 4.3 版更改: Arguments passed toFinish()
will be passed on toRequestHandler.finish
.- if self.current_user is None:
- _exception
tornado.web.
MissingArgumentError
(arg_name)[源代码]¶
Exception raised byRequestHandler.get_argument
.
This is a subclass ofHTTPError
, so if it is uncaught a 400 responsecode will be used instead of 500 (and a stack trace will not be logged).
3.1 新版功能.
- class
tornado.web.
UIModule
(handler)[源代码]¶
A re-usable, modular UI unit on a page.
UI modules often execute additional queries, and they can includeadditional CSS and JavaScript that will be included in the outputpage, which is automatically inserted on page render.
Subclasses of UIModule must override therender
method.javascript_files
()[源代码]¶
Override to return a list of JavaScript files needed by this module.
If the return values are relative paths, they will be passed toRequestHandler.static_url
; otherwise they will be used as-is.
css_files
()[源代码]¶
Override to returns a list of CSS files required by this module.
If the return values are relative paths, they will be passed toRequestHandler.static_url
; otherwise they will be used as-is.
- class
tornado.web.
ErrorHandler
(application, request, **kwargs)[源代码]¶
Generates an error response withstatuscode
for all requests.
- _class
tornado.web.
FallbackHandler
(application, request, **kwargs)[源代码]¶
ARequestHandler
that wraps another HTTP server callback.
The fallback is a callable object that accepts anHTTPServerRequest
, such as anApplication
ortornado.wsgi.WSGIContainer
. This is most useful to use bothTornadoRequestHandlers
and WSGI in the same server. Typicalusage:- wsgiapp = tornado.wsgi.WSGIContainer(
django.core.handlers.wsgi.WSGIHandler())
application = tornado.web.Application([
(r"/foo", FooHandler),
(r".*", FallbackHandler, dict(fallback=wsgi_app),
])
- wsgiapp = tornado.wsgi.WSGIContainer(
- _class
tornado.web.
RedirectHandler
(application, request, **kwargs)[源代码]¶
Redirects the client to the given URL for all GET requests.
You should provide the keyword argumenturl
to the handler, e.g.:- application = web.Application([
(r"/oldpath", web.RedirectHandler, {"url": "/newpath"}),
])
- application = web.Application([
- class
tornado.web.
StaticFileHandler
(application, request, **kwargs)[源代码]¶
A simple handler that can serve static content from a directory.
AStaticFileHandler
is configured automatically if you pass thestaticpath
keyword argument toApplication
. This handlercan be customized with thestatic_url_prefix
,static_handler_class
,andstatic_handler_args
settings.
To map an additional path to this handler for a static data directoryyou would add a line to your application like:- application = web.Application([
(r"/content/(.)", web.StaticFileHandler, {"path": "/var/www"}),
])
The handler constructor requires apath
argument, which specifies thelocal root directory of the content to be served.
Note that a capture group in the regex is required to parse the value forthepath
argument to the get() method (different than the constructorargument above); seeURLSpec
for details.
To serve a file likeindex.html
automatically when a directory isrequested, setstatic_handler_args=dict(default_filename="index.html")
in your application settings, or adddefault_filename
as an initializerargument for yourStaticFileHandler
.
To maximize the effectiveness of browser caching, this class supportsversioned urls (by default using the argument?v=
). If a versionis given, we instruct the browser to cache this file indefinitely.make_static_url
(also available asRequestHandler.static_url
) canbe used to construct a versioned url.
This handler is intended primarily for use in development and light-dutyfile serving; for heavy traffic it will be more efficient to usea dedicated static file server (such as nginx or Apache). We supportthe HTTPAccept-Ranges
mechanism to return partial content (becausesome browsers require this functionality to be present to seek inHTML5 audio or video).
*Subclassing notes
This class is designed to be extensible by subclassing, but becauseof the way static urls are generated with class methods rather thaninstance methods, the inheritance patterns are somewhat unusual.Be sure to use the@classmethod
decorator when overriding aclass method. Instance methods may use the attributesself.path
self.absolute_path
, andself.modified
.
Subclasses should only override methods discussed in this section;overriding other methods is error-prone. OverridingStaticFileHandler.get
is particularly problematic due to thetight coupling withcompute_etag
and other methods.
To change the way static urls are generated (e.g. to match the behaviorof another server or CDN), overridemake_static_url
,parse_url_path
,get_cache_time
, and/orget_version
.
To replace all interaction with the filesystem (e.g. to servestatic content from a database), overrideget_content
,get_content_size
,get_modified_time
,get_absolute_path
, andvalidate_absolute_path
.
在 3.1 版更改: Many of the methods for subclasses were added in Tornado 3.1.compute_etag
()[源代码]¶
Sets theEtag
header based on static url version.
This allows efficientIf-None-Match
checks against cachedversions, and sends the correctEtag
for a partial response(i.e. the sameEtag
as the full file).
3.1 新版功能.
- _classmethod
getabsolute_path
(_root, path)[源代码]¶
Returns the absolute location ofpath
relative toroot
.root
is the path configured for thisStaticFileHandler
(in most cases thestaticpath
Application
setting).
This class method may be overridden in subclasses. By defaultit returns a filesystem path, but other strings may be usedas long as they are unique and understood by the subclass’soverriddenget_content
.
3.1 新版功能.
validate_absolute_path
(_root, absolute_path)[源代码]¶
Validate and return the absolute path.root
is the configured path for theStaticFileHandler
,andpath
is the result ofget_absolute_path
This is an instance method called during request processing,so it may raiseHTTPError
or use methods likeRequestHandler.redirect
(return None after redirecting tohalt further processing). This is where 404 errors for missing filesare generated.
This method may modify the path before returning it, but note thatany such modifications will not be understood bymake_static_url
.
In instance methods, this method’s result is available asself.absolutepath
.
3.1 新版功能.
- _classmethod
getcontent
(_abspath, start=None, end=None)[源代码]¶
Retrieve the content of the requested resource which is locatedat the given absolute path.
This class method may be overridden by subclasses. Note that itssignature is different from other overridable class methods(nosettings
argument); this is deliberate to ensure thatabspath
is able to stand on its own as a cache key.
This method should either return a byte string or an iteratorof byte strings. The latter is preferred for large filesas it helps reduce memory fragmentation.
3.1 新版功能.
- classmethod
getcontent_version
(_abspath)[源代码]¶
Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. Thedefault implementation is a hash of the file’s contents.
3.1 新版功能.
getcontent_size
()[源代码]¶
Retrieve the total size of the resource at the given path.
This method may be overridden by subclasses.
3.1 新版功能.
在 4.0 版更改: This method is now always called, instead of only whenpartial results are requested.
get_modified_time
()[源代码]¶
Returns the time thatself.absolute_path
was last modified.
May be overridden in subclasses. Should return adatetime
object or None.
3.1 新版功能.
getcache_time
(_path, modified, mime_type)[源代码]¶
Override to customize cache control behavior.
Return a positive number of seconds to make the resultcacheable for that amount of time or 0 to mark resource ascacheable for an unspecified amount of time (subject tobrowser heuristics).
By default returns cache expiry of 10 years for resources requestedwithv
argument.
- classmethod
makestatic_url
(_settings, path, include_version=True)[源代码]¶
Constructs a versioned url for the given path.
This method may be overridden in subclasses (but note that itis a class method rather than an instance method). Subclassesare only required to implement the signaturemakestatic_url(cls, settings, path)
; other keywordarguments may be passed throughstatic_url
but are not standard.settings
is theApplication.settings
dictionary.path
is the static path being requested. The url returned should berelative to the current host.include_version
determines whether the generated URL shouldinclude the query string containing the version hash of thefile corresponding to the givenpath
.
parse_url_path
(_url_path)[源代码]¶
Converts a static URL path into a filesystem path.urlpath
is the path component of the URL withstatic_url_prefix
removed. The return value should befilesystem path relative tostatic_path
.
This is the inverse ofmake_static_url
.
- _classmethod
getversion
(_settings, path)[源代码]¶
Generate the version string to be used in static URLs.settings
is theApplication.settings
dictionary andpath
is the relative location of the requested asset on the filesystem.The returned value should be a string, orNone
if no versioncould be determined.
在 3.1 版更改: This method was previously recommended for subclasses to override;get_content_version
is now preferred as it allows the baseclass to handle caching of the result.
- application = web.Application([
原文: