auth Module#

auth Module#

class panel.auth.Auth0Handler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: OAuthLoginHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.AzureAdLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: OAuthLoginHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.AzureAdV2LoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: OAuthLoginHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.BasicAuthProvider(login_endpoint=None, logout_endpoint=None, login_template=None, logout_template=None, error_template=None, guest_endpoints=None)[source]#

Bases: AuthProvider

An AuthProvider which serves a simple login and logout page.

property endpoints: list[tuple[str, type[RequestHandler]]]#

URL patterns for login/logout endpoints.

property get_login_url: Callable[[HTTPServerRequest], str] | None#

A function that computes a URL to redirect unathenticated users to for login.

This property may return None, if a login_url is supplied instead.

If a function is returned, it should accept a RequestHandler and return a login URL for unathenticated users.

property get_user#

A function to get the current authenticated user.

This property may return None, if a get_user_async function is supplied instead.

If a function is returned, it should accept a RequestHandler and return the current authenticated user.

property get_user_async: Callable[[HTTPServerRequest], Awaitable[User]] | None#

An async function to get the current authenticated user.

This property may return None, if a get_user function is supplied instead.

If a function is returned, it should accept a RequestHandler and return the current authenticated user.

property login_handler#

A request handler class for a login page.

This property may return None, if login_url is supplied instead.

If a class is returned, it must be a subclass of RequestHandler, which will used for the endpoint specified by logout_url

property login_url#

A URL to redirect unauthenticated users to for login.

This proprty may return None, if a get_login_url function is supplied instead.

property logout_handler#

A request handler class for a logout page.

This property may return None.

If a class is returned, it must be a subclass of RequestHandler, which will used for the endpoint specified by logout_url

property logout_url#

A URL to redirect authenticated users to for logout.

This proprty may return None.

class panel.auth.BasicLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: RequestHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code: int, **kwargs: Any) None[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.BitbucketLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: OAuthLoginHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.CodeChallengeLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: GenericLoginHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.GenericLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: OAuthLoginHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.GitLabLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: OAuthLoginHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.GithubLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: OAuthLoginHandler

GitHub OAuth2 Authentication To authenticate with GitHub, first register your application at settings/applications to get the client ID and secret.

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.GoogleLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: OAuthLoginHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.LogoutHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: RequestHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code: int, **kwargs: Any) None[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.OAuthLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: RequestHandler, OAuth2Mixin

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.OAuthProvider(login_endpoint=None, logout_endpoint=None, login_template=None, logout_template=None, error_template=None, guest_endpoints=None)[source]#

Bases: BasicAuthProvider

An AuthProvider using specific OAuth implementation selected via the global config.oauth_provider configuration.

property endpoints: list[tuple[str, type[RequestHandler]]]#

URL patterns for login/logout endpoints.

property get_login_url: Callable[[HTTPServerRequest], str] | None#

A function that computes a URL to redirect unathenticated users to for login.

This property may return None, if a login_url is supplied instead.

If a function is returned, it should accept a RequestHandler and return a login URL for unathenticated users.

property get_user#

A function to get the current authenticated user.

This property may return None, if a get_user_async function is supplied instead.

If a function is returned, it should accept a RequestHandler and return the current authenticated user.

property get_user_async#

An async function to get the current authenticated user.

This property may return None, if a get_user function is supplied instead.

If a function is returned, it should accept a RequestHandler and return the current authenticated user.

property login_handler#

A request handler class for a login page.

This property may return None, if login_url is supplied instead.

If a class is returned, it must be a subclass of RequestHandler, which will used for the endpoint specified by logout_url

property login_url#

A URL to redirect unauthenticated users to for login.

This proprty may return None, if a get_login_url function is supplied instead.

property logout_handler#

A request handler class for a logout page.

This property may return None.

If a class is returned, it must be a subclass of RequestHandler, which will used for the endpoint specified by logout_url

property logout_url#

A URL to redirect authenticated users to for logout.

This proprty may return None.

class panel.auth.OktaLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: OAuthLoginHandler

Okta OAuth2 Authentication

To authenticate with Okta you first need to set up and configure in the Okta developer console.

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

class panel.auth.PasswordLoginHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)[source]#

Bases: GenericLoginHandler

add_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Adds the given response header and value.

Unlike set_header, add_header may be called multiple times to return multiple values for the same header.

authorize_redirect(redirect_uri: str | None = None, client_id: str | None = None, client_secret: str | None = None, extra_params: Dict[str, Any] | None = None, scope: List[str] | None = None, response_type: str = 'code') None[source]#

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

Deprecated since version 6.4: The client_secret argument (which has never had any effect) is deprecated and will be removed in Tornado 7.0.

check_etag_header() bool[source]#

Checks the Etag header against requests’s If-None-Match.

Returns True if the request’s Etag matches and a 304 should be returned. 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 override compute_etag and want to do an early check for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

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-cookie field with all POST requests. If the two do not match, we reject 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

clear() None[source]#

Resets all headers and content for this response.

clear_all_cookies(**kwargs: Any) None[source]#

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

clear_header(name: str) None[source]#

Clears an outgoing header, undoing a previous set_header call.

Note that this method does not apply to multi-valued headers set by add_header.

compute_etag() str | None[source]#

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.

property cookies: Dict[str, Morsel]#

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

create_signed_value(name: str, value: str | bytes, version: int | None = None) bytes[source]#

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

create_template_loader(template_path: str) BaseLoader[source]#

Returns a new template loader for the given path.

May be overridden by subclasses. By default returns a directory-based loader on the given path, using the autoescape and template_whitespace application settings. If a template_loader application setting is supplied, uses that instead.

property current_user: Any#

The authenticated user for this request.

This is set in one of two ways:

  • A subclass may override get_current_user(), which will be called automatically 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_signed_cookie("user")
        if user_cookie:
            return json.loads(user_cookie)
        return None
    
  • It may be set as a normal variable, typically from an overridden prepare():

    @gen.coroutine
    def prepare(self):
        user_id_cookie = self.get_signed_cookie("user_id")
        if user_id_cookie:
            self.current_user = yield load_user(user_id_cookie)
    

Note that prepare() may be a coroutine while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may be any type of the application’s choosing.

data_received(chunk: bytes) Awaitable[None] | None[source]#

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

May be a coroutine for flow control.

decode_argument(value: bytes, name: str | None = None) str[source]#

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 returns a unicode string, but this may be overridden in subclasses.

This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.

The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).

detach() IOStream[source]#

Take control of the underlying stream.

Returns the underlying .IOStream object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.

This method is only supported when HTTP/1.1 is used.

Added in version 5.1.

finish(chunk: str | bytes | dict | None = None) Future[None][source]#

Finishes this response, ending the HTTP request.

Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.

Returns a .Future which may optionally be awaited to track the sending of the response to the client. This .Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.

Changed in version 5.1: Now returns a .Future instead of None.

flush(include_footers: bool = False) Future[None][source]#

Flushes the current output buffer to the network.

Changed in version 4.0: Now returns a .Future if no callback is given.

Changed in version 6.0: The callback argument was removed.

get_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the request more than once, we return the last value.

This method searches both the query and body arguments.

get_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

This method searches both the query and body arguments.

get_auth_http_client() AsyncHTTPClient[source]#

Returns the .AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

Added in version 4.3.

async get_authenticated_user(redirect_uri, client_id, state, client_secret=None, code=None)[source]#

Fetches the authenticated user

Arguments#

redirect_uri: (str)

The OAuth redirect URI

client_id: (str)

The OAuth client ID

state: (str)

The unguessable random string to protect against cross-site request forgery attacks

client_secret: (str, optional)

The client secret

code: (str, optional)

The response code from the server

get_body_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request body.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_body_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the body arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

get_browser_locale(default: str = 'en_US') Locale[source]#

Determines the user’s locale from Accept-Language header.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

get_current_user() Any[source]#

Override to determine the current user from, e.g., a cookie.

This method may not be a coroutine.

get_login_url() str[source]#

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

get_query_argument(name: str, default: None | str | ~tornado.web._ArgDefaultMarker = <tornado.web._ArgDefaultMarker object>, strip: bool = True) str | None[source]#

Returns the value of the argument with the given name from the request query string.

If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.

If the argument appears in the url more than once, we return the last value.

Added in version 3.2.

get_query_arguments(name: str, strip: bool = True) List[str][source]#

Returns a list of the query arguments with the given name.

If the argument is not present, returns an empty list.

Added in version 3.2.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Get OAuth state from cookies To be compared with the value in redirect URL

get_status() int[source]#

Returns the status code for our response.

get_template_namespace() Dict[str, Any][source]#

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 additional defaults in the tornado.template module and keyword arguments to render or render_string.

get_template_path() str | None[source]#

Override to customize template path for each handler.

By default, we use the template_path application setting. Return None to load templates relative to the calling file.

get_user_locale() Locale | None[source]#

Override to determine the locale from the authenticated user.

If None is returned, we fall back to get_browser_locale().

This method should return a tornado.locale.Locale object, most likely obtained via a call like tornado.locale.get("en")

initialize() None[source]#
property locale: Locale#

The locale for the current session.

Determined by either get_user_locale, which you can override to set the locale based on, e.g., a user preference stored in a database, or get_browser_locale, which uses the Accept-Language header.

log_exception(typ: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) None[source]#

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

Added in version 3.1.

async oauth2_request(url: str, access_token: str | None = None, post_args: Dict[str, Any] | None = None, **args: Any) Any[source]#

Fetches the given URL auth an OAuth2 access token.

If the request is a POST, post_args should be provided. Query string arguments should be given as keyword arguments.

Example usage:

..testcode:

class MainHandler(tornado.web.RequestHandler,
                  tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    async def get(self):
        new_entry = await self.oauth2_request(
            "https://graph.facebook.com/me/feed",
            post_args={"message": "I am posting from my Tornado application!"},
            access_token=self.current_user["access_token"])

        if not new_entry:
            # Call failed; perhaps missing permission?
            self.authorize_redirect()
            return
        self.finish("Posted a message!")

Added in version 4.3.

on_connection_close() None[source]#

Called in async handlers if the client closed the connection.

Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override on_finish instead.

Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.

on_finish() None[source]#

Called after the end of a request.

Override this method to perform cleanup, logging, etc. This method is a counterpart to prepare. on_finish may not produce any output, as it is called after the response has been sent to the client.

prepare() Awaitable[None] | None[source]#

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.

Asynchronous support: Use async def or decorate this method with .gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.

Added in version 3.1: Asynchronous support.

redirect(url: str, permanent: bool = False, status: int | None = None) None[source]#

Sends a redirect to the given (optionally relative) URL.

If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).

render(template_name: str, **kwargs: Any) Future[None][source]#

Renders the template with the given arguments as the response.

render() calls finish(), so no other output methods can be called after it.

Returns a .Future with the same semantics as the one returned by finish. Awaiting this .Future is optional.

Changed in version 5.1: Now returns a .Future instead of None.

render_embed_css(css_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded css for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_embed_js(js_embed: Iterable[bytes]) bytes[source]#

Default method used to render the final embedded js for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_css(css_files: Iterable[str]) str[source]#

Default method used to render the final css links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_linked_js(js_files: Iterable[str]) str[source]#

Default method used to render the final js links for the rendered webpage.

Override this method in a sub-classed controller to change the output.

render_string(template_name: str, **kwargs: Any) bytes[source]#

Generate the given template with the given arguments.

We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.

require_setting(name: str, feature: str = 'this feature') None[source]#

Raises an exception if the given app setting is not defined.

reverse_url(name: str, *args: Any) str[source]#

Alias for Application.reverse_url.

send_error(status_code: int = 500, **kwargs: Any) None[source]#

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

set_default_headers() None[source]#

Override this to set HTTP headers at the beginning of the request.

For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.

set_etag_header() None[source]#

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

set_header(name: str, value: bytes | str | int | Integral | datetime) None[source]#

Sets the given response header name and value.

All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

set_status(status_code: int, reason: str | None = None) None[source]#

Sets the status code for our response.

Parameters:
  • status_code (int) – Response status code.

  • reason (str) – Human-readable reason phrase describing the status code. If None, it will be filled in from http.client.responses or “Unknown”.

Changed in version 5.0: No longer validates that the response code is in http.client.responses.

property settings: Dict[str, Any]#

An alias for self.application.settings <Application.settings>.

static_url(path: str, include_host: bool | None = None, **kwargs: Any) str[source]#

Returns a static URL for the given relative static file path.

This method requires you set the static_path setting in your application (which specifies the root directory of your static files).

This method returns a versioned url (by default appending ?v=<signature>), which allows the static files to be cached indefinitely. This can be disabled by passing include_version=False (in the default implementation; other static file implementations are not required to support this, but they may support other options).

By default this method returns URLs relative to the current host, but if include_host is true the URL returned will be absolute. If this handler has an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.

write(chunk: str | bytes | dict) None[source]#

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 set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and facebook/tornado#1009

write_error(status_code, **kwargs)[source]#

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

xsrf_form_html() str[source]#

An HTML <input/> element to be included with all POST forms.

It defines the _xsrf input value, which we check on all POST requests to prevent cross-site request forgery. If you have set the xsrf_cookies application setting, you must include this HTML within all of your HTML forms.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.

property xsrf_token: bytes#

The XSRF-prevention token for the current user/session.

To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

This property is of type bytes, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.

Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the xsrf_cookie_version Application setting is set to 1.

Changed in version 4.3: The xsrf_cookie_kwargs Application setting may be used to supply additional cookie options (which will be passed directly to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

panel.auth.decode_response_body(response)[source]#

Decodes the JSON-format response body

Arguments#

response: tornado.httpclient.HTTPResponse

Returns#

Decoded response content

panel.auth.extract_urlparam(args, key)[source]#

Extracts a request argument from a urllib.parse.parse_qs dict.