1``tornado.web`` --- ``RequestHandler`` and ``Application`` classes
2==================================================================
3
4.. testsetup::
5
6   from tornado.web import *
7
8.. automodule:: tornado.web
9
10   Request handlers
11   ----------------
12   .. autoclass:: RequestHandler(...)
13
14   Entry points
15   ^^^^^^^^^^^^
16
17   .. automethod:: RequestHandler.initialize
18   .. automethod:: RequestHandler.prepare
19   .. automethod:: RequestHandler.on_finish
20
21   .. _verbs:
22
23   Implement any of the following methods (collectively known as the
24   HTTP verb methods) to handle the corresponding HTTP method. These
25   methods can be made asynchronous with the ``async def`` keyword or
26   `.gen.coroutine` decorator.
27
28   The arguments to these methods come from the `.URLSpec`: Any
29   capturing groups in the regular expression become arguments to the
30   HTTP verb methods (keyword arguments if the group is named,
31   positional arguments if it's unnamed).
32
33   To support a method not on this list, override the class variable
34   ``SUPPORTED_METHODS``::
35
36     class WebDAVHandler(RequestHandler):
37         SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ('PROPFIND',)
38
39         def propfind(self):
40             pass
41
42   .. automethod:: RequestHandler.get
43   .. automethod:: RequestHandler.head
44   .. automethod:: RequestHandler.post
45   .. automethod:: RequestHandler.delete
46   .. automethod:: RequestHandler.patch
47   .. automethod:: RequestHandler.put
48   .. automethod:: RequestHandler.options
49
50   Input
51   ^^^^^
52
53   The ``argument`` methods provide support for HTML form-style
54   arguments. These methods are available in both singular and plural
55   forms because HTML forms are ambiguous and do not distinguish
56   between a singular argument and a list containing one entry. If you
57   wish to use other formats for arguments (for example, JSON), parse
58   ``self.request.body`` yourself::
59
60       def prepare(self):
61           if self.request.headers['Content-Type'] == 'application/x-json':
62               self.args = json_decode(self.request.body)
63           # Access self.args directly instead of using self.get_argument.
64
65
66   .. automethod:: RequestHandler.get_argument(name: str, default: Union[None, str, RAISE] = RAISE, strip: bool = True) -> Optional[str]
67   .. automethod:: RequestHandler.get_arguments
68   .. automethod:: RequestHandler.get_query_argument(name: str, default: Union[None, str, RAISE] = RAISE, strip: bool = True) -> Optional[str]
69   .. automethod:: RequestHandler.get_query_arguments
70   .. automethod:: RequestHandler.get_body_argument(name: str, default: Union[None, str, RAISE] = RAISE, strip: bool = True) -> Optional[str]
71   .. automethod:: RequestHandler.get_body_arguments
72   .. automethod:: RequestHandler.decode_argument
73   .. attribute:: RequestHandler.request
74
75      The `tornado.httputil.HTTPServerRequest` object containing additional
76      request parameters including e.g. headers and body data.
77
78   .. attribute:: RequestHandler.path_args
79   .. attribute:: RequestHandler.path_kwargs
80
81      The ``path_args`` and ``path_kwargs`` attributes contain the
82      positional and keyword arguments that are passed to the
83      :ref:`HTTP verb methods <verbs>`.  These attributes are set
84      before those methods are called, so the values are available
85      during `prepare`.
86
87   .. automethod:: RequestHandler.data_received
88
89   Output
90   ^^^^^^
91
92   .. automethod:: RequestHandler.set_status
93   .. automethod:: RequestHandler.set_header
94   .. automethod:: RequestHandler.add_header
95   .. automethod:: RequestHandler.clear_header
96   .. automethod:: RequestHandler.set_default_headers
97   .. automethod:: RequestHandler.write
98   .. automethod:: RequestHandler.flush
99   .. automethod:: RequestHandler.finish
100   .. automethod:: RequestHandler.render
101   .. automethod:: RequestHandler.render_string
102   .. automethod:: RequestHandler.get_template_namespace
103   .. automethod:: RequestHandler.redirect
104   .. automethod:: RequestHandler.send_error
105   .. automethod:: RequestHandler.write_error
106   .. automethod:: RequestHandler.clear
107   .. automethod:: RequestHandler.render_linked_js
108   .. automethod:: RequestHandler.render_embed_js
109   .. automethod:: RequestHandler.render_linked_css
110   .. automethod:: RequestHandler.render_embed_css
111
112   Cookies
113   ^^^^^^^
114
115   .. autoattribute:: RequestHandler.cookies
116   .. automethod:: RequestHandler.get_cookie
117   .. automethod:: RequestHandler.set_cookie
118   .. automethod:: RequestHandler.clear_cookie
119   .. automethod:: RequestHandler.clear_all_cookies
120   .. automethod:: RequestHandler.get_secure_cookie
121   .. automethod:: RequestHandler.get_secure_cookie_key_version
122   .. automethod:: RequestHandler.set_secure_cookie
123   .. automethod:: RequestHandler.create_signed_value
124   .. autodata:: MIN_SUPPORTED_SIGNED_VALUE_VERSION
125   .. autodata:: MAX_SUPPORTED_SIGNED_VALUE_VERSION
126   .. autodata:: DEFAULT_SIGNED_VALUE_VERSION
127   .. autodata:: DEFAULT_SIGNED_VALUE_MIN_VERSION
128
129   Other
130   ^^^^^
131
132   .. attribute:: RequestHandler.application
133
134      The `Application` object serving this request
135
136   .. automethod:: RequestHandler.check_etag_header
137   .. automethod:: RequestHandler.check_xsrf_cookie
138   .. automethod:: RequestHandler.compute_etag
139   .. automethod:: RequestHandler.create_template_loader
140   .. autoattribute:: RequestHandler.current_user
141   .. automethod:: RequestHandler.detach
142   .. automethod:: RequestHandler.get_browser_locale
143   .. automethod:: RequestHandler.get_current_user
144   .. automethod:: RequestHandler.get_login_url
145   .. automethod:: RequestHandler.get_status
146   .. automethod:: RequestHandler.get_template_path
147   .. automethod:: RequestHandler.get_user_locale
148   .. autoattribute:: RequestHandler.locale
149   .. automethod:: RequestHandler.log_exception
150   .. automethod:: RequestHandler.on_connection_close
151   .. automethod:: RequestHandler.require_setting
152   .. automethod:: RequestHandler.reverse_url
153   .. automethod:: RequestHandler.set_etag_header
154   .. autoattribute:: RequestHandler.settings
155   .. automethod:: RequestHandler.static_url
156   .. automethod:: RequestHandler.xsrf_form_html
157   .. autoattribute:: RequestHandler.xsrf_token
158
159
160
161   Application configuration
162   -------------------------
163
164   .. autoclass:: Application(handlers: Optional[List[Union[Rule, Tuple]]] = None, default_host: Optional[str] = None, transforms: Optional[List[Type[OutputTransform]]] = None, **settings)
165
166      .. attribute:: settings
167
168         Additional keyword arguments passed to the constructor are
169         saved in the `settings` dictionary, and are often referred to
170         in documentation as "application settings".  Settings are
171         used to customize various aspects of Tornado (although in
172         some cases richer customization is possible by overriding
173         methods in a subclass of `RequestHandler`).  Some
174         applications also like to use the `settings` dictionary as a
175         way to make application-specific settings available to
176         handlers without using global variables.  Settings used in
177         Tornado are described below.
178
179         General settings:
180
181         * ``autoreload``: If ``True``, the server process will restart
182           when any source files change, as described in :ref:`debug-mode`.
183           This option is new in Tornado 3.2; previously this functionality
184           was controlled by the ``debug`` setting.
185         * ``debug``: Shorthand for several debug mode settings,
186           described in :ref:`debug-mode`.  Setting ``debug=True`` is
187           equivalent to ``autoreload=True``, ``compiled_template_cache=False``,
188           ``static_hash_cache=False``, ``serve_traceback=True``.
189         * ``default_handler_class`` and ``default_handler_args``:
190           This handler will be used if no other match is found;
191           use this to implement custom 404 pages (new in Tornado 3.2).
192         * ``compress_response``: If ``True``, responses in textual formats
193           will be compressed automatically.  New in Tornado 4.0.
194         * ``gzip``: Deprecated alias for ``compress_response`` since
195           Tornado 4.0.
196         * ``log_function``: This function will be called at the end
197           of every request to log the result (with one argument, the
198           `RequestHandler` object).  The default implementation
199           writes to the `logging` module's root logger.  May also be
200           customized by overriding `Application.log_request`.
201         * ``serve_traceback``: If ``True``, the default error page
202           will include the traceback of the error.  This option is new in
203           Tornado 3.2; previously this functionality was controlled by
204           the ``debug`` setting.
205         * ``ui_modules`` and ``ui_methods``: May be set to a mapping
206           of `UIModule` or UI methods to be made available to templates.
207           May be set to a module, dictionary, or a list of modules
208           and/or dicts.  See :ref:`ui-modules` for more details.
209         * ``websocket_ping_interval``: If set to a number, all websockets will
210           be pinged every n seconds. This can help keep the connection alive
211           through certain proxy servers which close idle connections, and it
212           can detect if the websocket has failed without being properly closed.
213         * ``websocket_ping_timeout``: If the ping interval is set, and the
214           server doesn't receive a 'pong' in this many seconds, it will close
215           the websocket. The default is three times the ping interval, with a
216           minimum of 30 seconds. Ignored if the ping interval is not set.
217
218         Authentication and security settings:
219
220         * ``cookie_secret``: Used by `RequestHandler.get_secure_cookie`
221           and `.set_secure_cookie` to sign cookies.
222         * ``key_version``: Used by requestHandler `.set_secure_cookie`
223           to sign cookies with a specific key when ``cookie_secret``
224           is a key dictionary.
225         * ``login_url``: The `authenticated` decorator will redirect
226           to this url if the user is not logged in.  Can be further
227           customized by overriding `RequestHandler.get_login_url`
228         * ``xsrf_cookies``: If ``True``, :ref:`xsrf` will be enabled.
229         * ``xsrf_cookie_version``: Controls the version of new XSRF
230           cookies produced by this server.  Should generally be left
231           at the default (which will always be the highest supported
232           version), but may be set to a lower value temporarily
233           during version transitions.  New in Tornado 3.2.2, which
234           introduced XSRF cookie version 2.
235         * ``xsrf_cookie_kwargs``: May be set to a dictionary of
236           additional arguments to be passed to `.RequestHandler.set_cookie`
237           for the XSRF cookie.
238         * ``twitter_consumer_key``, ``twitter_consumer_secret``,
239           ``friendfeed_consumer_key``, ``friendfeed_consumer_secret``,
240           ``google_consumer_key``, ``google_consumer_secret``,
241           ``facebook_api_key``, ``facebook_secret``:  Used in the
242           `tornado.auth` module to authenticate to various APIs.
243
244         Template settings:
245
246         * ``autoescape``: Controls automatic escaping for templates.
247           May be set to ``None`` to disable escaping, or to the *name*
248           of a function that all output should be passed through.
249           Defaults to ``"xhtml_escape"``.  Can be changed on a per-template
250           basis with the ``{% autoescape %}`` directive.
251         * ``compiled_template_cache``: Default is ``True``; if ``False``
252           templates will be recompiled on every request.  This option
253           is new in Tornado 3.2; previously this functionality was controlled
254           by the ``debug`` setting.
255         * ``template_path``: Directory containing template files.  Can be
256           further customized by overriding `RequestHandler.get_template_path`
257         * ``template_loader``: Assign to an instance of
258           `tornado.template.BaseLoader` to customize template loading.
259           If this setting is used the ``template_path`` and ``autoescape``
260           settings are ignored.  Can be further customized by overriding
261           `RequestHandler.create_template_loader`.
262         * ``template_whitespace``: Controls handling of whitespace in
263           templates; see `tornado.template.filter_whitespace` for allowed
264           values. New in Tornado 4.3.
265
266         Static file settings:
267
268         * ``static_hash_cache``: Default is ``True``; if ``False``
269           static urls will be recomputed on every request.  This option
270           is new in Tornado 3.2; previously this functionality was controlled
271           by the ``debug`` setting.
272         * ``static_path``: Directory from which static files will be
273           served.
274         * ``static_url_prefix``:  Url prefix for static files,
275           defaults to ``"/static/"``.
276         * ``static_handler_class``, ``static_handler_args``: May be set to
277           use a different handler for static files instead of the default
278           `tornado.web.StaticFileHandler`.  ``static_handler_args``, if set,
279           should be a dictionary of keyword arguments to be passed to the
280           handler's ``initialize`` method.
281
282   .. automethod:: Application.listen
283   .. automethod:: Application.add_handlers(handlers: List[Union[Rule, Tuple]])
284   .. automethod:: Application.get_handler_delegate
285   .. automethod:: Application.reverse_url
286   .. automethod:: Application.log_request
287
288   .. autoclass:: URLSpec
289
290      The ``URLSpec`` class is also available under the name ``tornado.web.url``.
291
292   Decorators
293   ----------
294   .. autofunction:: authenticated
295   .. autofunction:: addslash
296   .. autofunction:: removeslash
297   .. autofunction:: stream_request_body
298
299   Everything else
300   ---------------
301   .. autoexception:: HTTPError
302   .. autoexception:: Finish
303   .. autoexception:: MissingArgumentError
304   .. autoclass:: UIModule
305      :members:
306
307   .. autoclass:: ErrorHandler
308   .. autoclass:: FallbackHandler
309   .. autoclass:: RedirectHandler
310   .. autoclass:: StaticFileHandler
311      :members:
312