doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
call_on_close(func) Adds a function to the internal list of functions that should be called as part of closing down the response. Since 0.7 this function also returns the function that was passed so that this can be used as a decorator. Changelog New in version 0.6. Parameters func (Callable[[], Any]) – Return type Callable[[], Any]
flask.api.index#flask.Response.call_on_close
close() Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it. Changelog New in version 0.9: Can now be used in a with statement. Return type None
flask.api.index#flask.Response.close
content_encoding The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.
flask.api.index#flask.Response.content_encoding
content_length The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
flask.api.index#flask.Response.content_length
content_location The Content-Location entity-header field MAY be used to supply the resource location for the entity enclosed in the message when that entity is accessible from a location separate from the requested resource’s URI.
flask.api.index#flask.Response.content_location
content_md5 The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)
flask.api.index#flask.Response.content_md5
content_security_policy The Content-Security-Policy header adds an additional layer of security to help detect and mitigate certain types of attacks.
flask.api.index#flask.Response.content_security_policy
content_security_policy_report_only The Content-Security-Policy-Report-Only header adds a csp policy that is not enforced but is reported thereby helping detect certain types of attacks.
flask.api.index#flask.Response.content_security_policy_report_only
content_type The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
flask.api.index#flask.Response.content_type
cross_origin_embedder_policy Prevents a document from loading any cross-origin resources that do not explicitly grant the document permission. Values must be a member of the werkzeug.http.COEP enum.
flask.api.index#flask.Response.cross_origin_embedder_policy
cross_origin_opener_policy Allows control over sharing of browsing context group with cross-origin documents. Values must be a member of the werkzeug.http.COOP enum.
flask.api.index#flask.Response.cross_origin_opener_policy
date The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822. Changed in version 2.0: The datetime object is timezone-aware.
flask.api.index#flask.Response.date
delete_cookie(key, path='/', domain=None, secure=False, httponly=False, samesite=None) Delete a cookie. Fails silently if key doesn’t exist. Parameters key (str) – the key (name) of the cookie to be deleted. path (str) – if the cookie that should be deleted was limited to a path, the path has to be defined here. domain (Optional[str]) – if the cookie that should be deleted was limited to a domain, that domain has to be defined here. secure (bool) – If True, the cookie will only be available via HTTPS. httponly (bool) – Disallow JavaScript access to the cookie. samesite (Optional[str]) – Limit the scope of the cookie to only be attached to requests that are “same-site”. Return type None
flask.api.index#flask.Response.delete_cookie
direct_passthrough Pass the response body directly through as the WSGI iterable. This can be used when the body is a binary file or other iterator of bytes, to skip some unnecessary checks. Use send_file() instead of setting this manually.
flask.api.index#flask.Response.direct_passthrough
expires The Expires entity-header field gives the date/time after which the response is considered stale. A stale cache entry may not normally be returned by a cache. Changed in version 2.0: The datetime object is timezone-aware.
flask.api.index#flask.Response.expires
classmethod force_type(response, environ=None) Enforce that the WSGI response is a response object of the current type. Werkzeug will use the Response internally in many situations like the exceptions. If you call get_response() on an exception you will get back a regular Response object, even if you are using a custom subclass. This method can enforce a given response type, and it will also convert arbitrary WSGI callables into response objects if an environ is provided: # convert a Werkzeug response object into an instance of the # MyResponseClass subclass. response = MyResponseClass.force_type(response) # convert any WSGI application into a response object response = MyResponseClass.force_type(response, environ) This is especially useful if you want to post-process responses in the main dispatcher and use functionality provided by your subclass. Keep in mind that this will modify response objects in place if possible! Parameters response (Response) – a response object or wsgi application. environ (Optional[WSGIEnvironment]) – a WSGI environment object. Returns a response object. Return type Response
flask.api.index#flask.Response.force_type
freeze(no_etag=None) Make the response object ready to be pickled. Does the following: Buffer the response into a list, ignoring implicity_sequence_conversion and direct_passthrough. Set the Content-Length header. Generate an ETag header if one is not already set. Changed in version 2.0: An ETag header is added, the no_etag parameter is deprecated and will be removed in Werkzeug 2.1. Changelog Changed in version 0.6: The Content-Length header is set. Parameters no_etag (None) – Return type None
flask.api.index#flask.Response.freeze
classmethod from_app(app, environ, buffered=False) Create a new response object from an application output. This works best if you pass it an application that returns a generator all the time. Sometimes applications may use the write() callable returned by the start_response function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should set buffered to True which enforces buffering. Parameters app (WSGIApplication) – the WSGI application to execute. environ (WSGIEnvironment) – the WSGI environment to execute against. buffered (bool) – set to True to enforce buffering. Returns a response object. Return type Response
flask.api.index#flask.Response.from_app
get_app_iter(environ) Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response. If the request method is HEAD or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned. Changelog New in version 0.6. Parameters environ (WSGIEnvironment) – the WSGI environment of the request. Returns a response iterable. Return type Iterable[bytes]
flask.api.index#flask.Response.get_app_iter
get_data(as_text=False) The string representation of the response body. Whenever you call this property the response iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data. This behavior can be disabled by setting implicit_sequence_conversion to False. If as_text is set to True the return value will be a decoded string. Changelog New in version 0.9. Parameters as_text (bool) – Return type Union[bytes, str]
flask.api.index#flask.Response.get_data
get_etag() Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None). Return type Union[Tuple[str, bool], Tuple[None, None]]
flask.api.index#flask.Response.get_etag
get_json(force=False, silent=False) Parse data as JSON. Useful during testing. If the mimetype does not indicate JSON (application/json, see is_json()), this returns None. Unlike Request.get_json(), the result is not cached. Parameters force (bool) – Ignore the mimetype and always try to parse JSON. silent (bool) – Silence parsing errors and return None instead. Return type Optional[Any]
flask.api.index#flask.Response.get_json
get_wsgi_headers(environ) This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary. For example the location header (if present) is joined with the root URL of the environment. Also the content length is automatically set to zero here for certain status codes. Changelog Changed in version 0.6: Previously that function was called fix_headers and modified the response object in place. Also since 0.6, IRIs in location and content-location headers are handled properly. Also starting with 0.6, Werkzeug will attempt to set the content length if it is able to figure it out on its own. This is the case if all the strings in the response iterable are already encoded and the iterable is buffered. Parameters environ (WSGIEnvironment) – the WSGI environment of the request. Returns returns a new Headers object. Return type werkzeug.datastructures.Headers
flask.api.index#flask.Response.get_wsgi_headers
get_wsgi_response(environ) Returns the final WSGI response as tuple. The first item in the tuple is the application iterator, the second the status and the third the list of headers. The response returned is created specially for the given environment. For example if the request method in the WSGI environment is 'HEAD' the response will be empty and only the headers and status code will be present. Changelog New in version 0.6. Parameters environ (WSGIEnvironment) – the WSGI environment of the request. Returns an (app_iter, status, headers) tuple. Return type Tuple[Iterable[bytes], str, List[Tuple[str, str]]]
flask.api.index#flask.Response.get_wsgi_response
iter_encoded() Iter the response encoded with the encoding of the response. If the response object is invoked as WSGI application the return value of this method is used as application iterator unless direct_passthrough was activated. Return type Iterator[bytes]
flask.api.index#flask.Response.iter_encoded
last_modified The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified. Changed in version 2.0: The datetime object is timezone-aware.
flask.api.index#flask.Response.last_modified
location The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource.
flask.api.index#flask.Response.location
make_conditional(request_or_environ, accept_ranges=False, complete_length=None) Make the response conditional to the request. This method works best if an etag was defined for the response already. The add_etag method can be used to do that. If called without etag just the date header is set. This does nothing if the request method in the request or environ is anything but GET or HEAD. For optimal performance when handling range requests, it’s recommended that your response data object implements seekable, seek and tell methods as described by io.IOBase. Objects returned by wrap_file() automatically implement those methods. It does not remove the body of the response because that’s something the __call__() function does for us automatically. Returns self so that you can do return resp.make_conditional(req) but modifies the object in-place. Parameters request_or_environ (WSGIEnvironment) – a request object or WSGI environment to be used to make the response conditional against. accept_ranges (Union[bool, str]) – This parameter dictates the value of Accept-Ranges header. If False (default), the header is not set. If True, it will be set to "bytes". If None, it will be set to "none". If it’s a string, it will use this value. complete_length (Optional[int]) – Will be used only in valid Range Requests. It will set Content-Range complete length value and compute Content-Length real value. This parameter is mandatory for successful Range Requests completion. Raises RequestedRangeNotSatisfiable if Range header could not be parsed or satisfied. Return type Response Changed in version 2.0: Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error.
flask.api.index#flask.Response.make_conditional
make_sequence() Converts the response iterator in a list. By default this happens automatically if required. If implicit_sequence_conversion is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items. Changelog New in version 0.6. Return type None
flask.api.index#flask.Response.make_sequence
set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None) Sets a cookie. A warning is raised if the size of the cookie header exceeds max_cookie_size, but the header will still be set. Parameters key (str) – the key (name) of the cookie to be set. value (str) – the value of the cookie. max_age (Optional[Union[datetime.timedelta, int]]) – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session. expires (Optional[Union[str, datetime.datetime, int, float]]) – should be a datetime object or UNIX timestamp. path (Optional[str]) – limits the cookie to a given path, per default it will span the whole domain. domain (Optional[str]) – if you want to set a cross-domain cookie. For example, domain=".example.com" will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it. secure (bool) – If True, the cookie will only be available via HTTPS. httponly (bool) – Disallow JavaScript access to the cookie. samesite (Optional[str]) – Limit the scope of the cookie to only be attached to requests that are “same-site”. Return type None
flask.api.index#flask.Response.set_cookie
set_data(value) Sets a new string as response. The value must be a string or bytes. If a string is set it’s encoded to the charset of the response (utf-8 by default). Changelog New in version 0.9. Parameters value (Union[bytes, str]) – Return type None
flask.api.index#flask.Response.set_data
set_etag(etag, weak=False) Set the etag, and override the old one if there was one. Parameters etag (str) – weak (bool) – Return type None
flask.api.index#flask.Response.set_etag
flask.safe_join(directory, *pathnames) Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory. Parameters directory (str) – The trusted base directory. pathnames (str) – The untrusted path components relative to the base directory. Returns A safe path, otherwise None. Return type str
flask.api.index#flask.safe_join
class flask.cli.ScriptInfo(app_import_path=None, create_app=None, set_debug_flag=True) Helper object to deal with Flask applications. This is usually not necessary to interface with as it’s used internally in the dispatching to click. In future versions of Flask this object will most likely play a bigger role. Typically it’s created automatically by the FlaskGroup but you can also manually create it and pass it onwards as click object. app_import_path Optionally the import path for the Flask application. create_app Optionally a function that is passed the script info to create the instance of the application. data A dictionary with arbitrary data that can be associated with this script info. load_app() Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned.
flask.api.index#flask.cli.ScriptInfo
app_import_path Optionally the import path for the Flask application.
flask.api.index#flask.cli.ScriptInfo.app_import_path
create_app Optionally a function that is passed the script info to create the instance of the application.
flask.api.index#flask.cli.ScriptInfo.create_app
data A dictionary with arbitrary data that can be associated with this script info.
flask.api.index#flask.cli.ScriptInfo.data
load_app() Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned.
flask.api.index#flask.cli.ScriptInfo.load_app
SECRET_KEY A secret key that will be used for securely signing the session cookie and can be used for any other security related needs by extensions or your application. It should be a long random bytes or str. For example, copy the output of this to your config: $ python -c 'import os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/' Do not reveal the secret key when posting questions or committing code. Default: None
flask.config.index#SECRET_KEY
class flask.sessions.SecureCookieSession(initial=None) Base class for sessions based on signed cookies. This session backend will set the modified and accessed attributes. It cannot reliably track whether a session is new (vs. empty), so new remains hard coded to False. Parameters initial (Any) – Return type None accessed = False header, which allows caching proxies to cache different pages for different users. get(key, default=None) Return the value for key if key is in the dictionary, else default. Parameters key (str) – default (Optional[Any]) – Return type Any modified = False When data is changed, this is set to True. Only the session dictionary itself is tracked; if the session contains mutable data (for example a nested dict) then this must be set to True manually when modifying that data. The session cookie will only be written to the response if this is True. setdefault(key, default=None) Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. Parameters key (str) – default (Optional[Any]) – Return type Any
flask.api.index#flask.sessions.SecureCookieSession
accessed = False header, which allows caching proxies to cache different pages for different users.
flask.api.index#flask.sessions.SecureCookieSession.accessed
get(key, default=None) Return the value for key if key is in the dictionary, else default. Parameters key (str) – default (Optional[Any]) – Return type Any
flask.api.index#flask.sessions.SecureCookieSession.get
modified = False When data is changed, this is set to True. Only the session dictionary itself is tracked; if the session contains mutable data (for example a nested dict) then this must be set to True manually when modifying that data. The session cookie will only be written to the response if this is True.
flask.api.index#flask.sessions.SecureCookieSession.modified
setdefault(key, default=None) Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. Parameters key (str) – default (Optional[Any]) – Return type Any
flask.api.index#flask.sessions.SecureCookieSession.setdefault
class flask.sessions.SecureCookieSessionInterface The default session interface that stores sessions in signed cookies through the itsdangerous module. static digest_method() the hash function to use for the signature. The default is sha1 key_derivation = 'hmac' the name of the itsdangerous supported key derivation. The default is hmac. open_session(app, request) This method has to be implemented and must either return None in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on SessionMixin. Parameters app (Flask) – request (Request) – Return type Optional[flask.sessions.SecureCookieSession] salt = 'cookie-session' the salt that should be applied on top of the secret key for the signing of cookie based sessions. save_session(app, session, response) This is called for actual sessions returned by open_session() at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that. Parameters app (Flask) – session (flask.sessions.SessionMixin) – response (Response) – Return type None serializer = <flask.json.tag.TaggedJSONSerializer object> A python serializer for the payload. The default is a compact JSON derived serializer with support for some extra Python types such as datetime objects or tuples. session_class alias of flask.sessions.SecureCookieSession
flask.api.index#flask.sessions.SecureCookieSessionInterface
static digest_method() the hash function to use for the signature. The default is sha1
flask.api.index#flask.sessions.SecureCookieSessionInterface.digest_method
key_derivation = 'hmac' the name of the itsdangerous supported key derivation. The default is hmac.
flask.api.index#flask.sessions.SecureCookieSessionInterface.key_derivation
open_session(app, request) This method has to be implemented and must either return None in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on SessionMixin. Parameters app (Flask) – request (Request) – Return type Optional[flask.sessions.SecureCookieSession]
flask.api.index#flask.sessions.SecureCookieSessionInterface.open_session
salt = 'cookie-session' the salt that should be applied on top of the secret key for the signing of cookie based sessions.
flask.api.index#flask.sessions.SecureCookieSessionInterface.salt
save_session(app, session, response) This is called for actual sessions returned by open_session() at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that. Parameters app (Flask) – session (flask.sessions.SessionMixin) – response (Response) – Return type None
flask.api.index#flask.sessions.SecureCookieSessionInterface.save_session
serializer = <flask.json.tag.TaggedJSONSerializer object> A python serializer for the payload. The default is a compact JSON derived serializer with support for some extra Python types such as datetime objects or tuples.
flask.api.index#flask.sessions.SecureCookieSessionInterface.serializer
session_class alias of flask.sessions.SecureCookieSession
flask.api.index#flask.sessions.SecureCookieSessionInterface.session_class
flask.send_file(path_or_file, mimetype=None, as_attachment=False, download_name=None, attachment_filename=None, conditional=True, etag=True, add_etags=None, last_modified=None, max_age=None, cache_timeout=None) Send the contents of a file to the client. The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with io.BytesIO. Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn’t intend. Use send_from_directory() to safely serve user-requested paths from within a directory. If the WSGI server sets a file_wrapper in environ, it is used, otherwise Werkzeug’s built-in wrapper is used. Alternatively, if the HTTP server supports X-Sendfile, configuring Flask with USE_X_SENDFILE = True will tell the server to send the given path, which is much more efficient than reading it in Python. Parameters path_or_file – The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data. mimetype – The MIME type to send for the file. If not provided, it will try to detect it from the file name. as_attachment – Indicate to a browser that it should offer to save the file instead of displaying it. download_name – The default name browsers will use when saving the file. Defaults to the passed file name. conditional – Enable conditional and range responses based on request headers. Requires passing a file path and environ. etag – Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead. last_modified – The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path. max_age – How long the client should cache the file, in seconds. If set, Cache-Control will be public, otherwise it will be no-cache to prefer conditional caching. Changed in version 2.0: download_name replaces the attachment_filename parameter. If as_attachment=False, it is passed with Content-Disposition: inline instead. Changed in version 2.0: max_age replaces the cache_timeout parameter. conditional is enabled and max_age is not set by default. Changed in version 2.0: etag replaces the add_etags parameter. It can be a string to use instead of generating one. Changed in version 2.0: Passing a file-like object that inherits from TextIOBase will raise a ValueError rather than sending an empty file. New in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments. Changelog Changed in version 1.1: filename may be a PathLike object. Changed in version 1.1: Passing a BytesIO object supports range requests. Changed in version 1.0.3: Filenames are encoded with ASCII instead of Latin-1 for broader compatibility with WSGI servers. Changed in version 1.0: UTF-8 filenames as specified in RFC 2231 are supported. Changed in version 0.12: The filename is no longer automatically inferred from file objects. If you want to use automatic MIME and etag support, pass a filename via filename_or_fp or attachment_filename. Changed in version 0.12: attachment_filename is preferred over filename for MIME detection. Changed in version 0.9: cache_timeout defaults to Flask.get_send_file_max_age(). Changed in version 0.7: MIME guessing and etag support for file-like objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself. Changed in version 0.5: The add_etags, cache_timeout and conditional parameters were added. The default behavior is to add etags. New in version 0.2.
flask.api.index#flask.send_file
SEND_FILE_MAX_AGE_DEFAULT When serving files, set the cache control max age to this number of seconds. Can be a datetime.timedelta or an int. Override this value on a per-file basis using get_send_file_max_age() on the application or blueprint. If None, send_file tells the browser to use conditional requests will be used instead of a timed cache, which is usually preferable. Default: None
flask.config.index#SEND_FILE_MAX_AGE_DEFAULT
flask.send_from_directory(directory, path, filename=None, **kwargs) Send a file from within a directory using send_file(). @app.route("/uploads/<path:name>") def download_file(name): return send_from_directory( app.config['UPLOAD_FOLDER'], name, as_attachment=True ) This is a secure way to serve files from a folder, such as static files or uploads. Uses safe_join() to ensure the path coming from the client is not maliciously crafted to point outside the specified directory. If the final path does not point to an existing regular file, raises a 404 NotFound error. Parameters directory (str) – The directory that path must be located under. path (str) – The path to the file to send, relative to directory. kwargs (Any) – Arguments to pass to send_file(). filename (Optional[str]) – Return type Response Changed in version 2.0: path replaces the filename parameter. New in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments. Changelog New in version 0.5.
flask.api.index#flask.send_from_directory
SERVER_NAME Inform the application what host and port it is bound to. Required for subdomain route matching support. If set, will be used for the session cookie domain if SESSION_COOKIE_DOMAIN is not set. Modern web browsers will not allow setting cookies for domains without a dot. To use a domain locally, add any names that should route to the app to your hosts file. 127.0.0.1 localhost.dev If set, url_for can generate external URLs with only an application context instead of a request context. Default: None
flask.config.index#SERVER_NAME
class flask.session The session object works pretty much like an ordinary dict, with the difference that it keeps track of modifications. This is a proxy. See Notes On Proxies for more information. The following attributes are interesting: new True if the session is new, False otherwise. modified True if the session object detected a modification. Be advised that modifications on mutable structures are not picked up automatically, in that situation you have to explicitly set the attribute to True yourself. Here an example: # this change is not picked up because a mutable object (here # a list) is changed. session['objects'].append(42) # so mark it as modified yourself session.modified = True permanent If set to True the session lives for permanent_session_lifetime seconds. The default is 31 days. If set to False (which is the default) the session will be deleted when the user closes the browser.
flask.api.index#flask.session
modified True if the session object detected a modification. Be advised that modifications on mutable structures are not picked up automatically, in that situation you have to explicitly set the attribute to True yourself. Here an example: # this change is not picked up because a mutable object (here # a list) is changed. session['objects'].append(42) # so mark it as modified yourself session.modified = True
flask.api.index#flask.session.modified
new True if the session is new, False otherwise.
flask.api.index#flask.session.new
permanent If set to True the session lives for permanent_session_lifetime seconds. The default is 31 days. If set to False (which is the default) the session will be deleted when the user closes the browser.
flask.api.index#flask.session.permanent
class flask.sessions.SessionInterface The basic interface you have to implement in order to replace the default session interface which uses werkzeug’s securecookie implementation. The only methods you have to implement are open_session() and save_session(), the others have useful defaults which you don’t need to change. The session object returned by the open_session() method has to provide a dictionary like interface plus the properties and methods from the SessionMixin. We recommend just subclassing a dict and adding that mixin: class Session(dict, SessionMixin): pass If open_session() returns None Flask will call into make_null_session() to create a session that acts as replacement if the session support cannot work because some requirement is not fulfilled. The default NullSession class that is created will complain that the secret key was not set. To replace the session interface on an application all you have to do is to assign flask.Flask.session_interface: app = Flask(__name__) app.session_interface = MySessionInterface() Changelog New in version 0.8. get_cookie_domain(app) Returns the domain that should be set for the session cookie. Uses SESSION_COOKIE_DOMAIN if it is configured, otherwise falls back to detecting the domain based on SERVER_NAME. Once detected (or if not set at all), SESSION_COOKIE_DOMAIN is updated to avoid re-running the logic. Parameters app (Flask) – Return type Optional[str] get_cookie_httponly(app) Returns True if the session cookie should be httponly. This currently just returns the value of the SESSION_COOKIE_HTTPONLY config var. Parameters app (Flask) – Return type bool get_cookie_name(app) Returns the name of the session cookie. Uses app.session_cookie_name which is set to SESSION_COOKIE_NAME Parameters app (Flask) – Return type str get_cookie_path(app) Returns the path for which the cookie should be valid. The default implementation uses the value from the SESSION_COOKIE_PATH config var if it’s set, and falls back to APPLICATION_ROOT or uses / if it’s None. Parameters app (Flask) – Return type str get_cookie_samesite(app) Return 'Strict' or 'Lax' if the cookie should use the SameSite attribute. This currently just returns the value of the SESSION_COOKIE_SAMESITE setting. Parameters app (Flask) – Return type str get_cookie_secure(app) Returns True if the cookie should be secure. This currently just returns the value of the SESSION_COOKIE_SECURE setting. Parameters app (Flask) – Return type bool get_expiration_time(app, session) A helper method that returns an expiration date for the session or None if the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application. Parameters app (Flask) – session (flask.sessions.SessionMixin) – Return type Optional[datetime.datetime] is_null_session(obj) Checks if a given object is a null session. Null sessions are not asked to be saved. This checks if the object is an instance of null_session_class by default. Parameters obj (object) – Return type bool make_null_session(app) Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed. This creates an instance of null_session_class by default. Parameters app (Flask) – Return type flask.sessions.NullSession null_session_class make_null_session() will look here for the class that should be created when a null session is requested. Likewise the is_null_session() method will perform a typecheck against this type. alias of flask.sessions.NullSession open_session(app, request) This method has to be implemented and must either return None in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on SessionMixin. Parameters app (Flask) – request (Request) – Return type Optional[flask.sessions.SessionMixin] pickle_based = False A flag that indicates if the session interface is pickle based. This can be used by Flask extensions to make a decision in regards to how to deal with the session object. Changelog New in version 0.10. save_session(app, session, response) This is called for actual sessions returned by open_session() at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that. Parameters app (Flask) – session (flask.sessions.SessionMixin) – response (Response) – Return type None should_set_cookie(app, session) Used by session backends to determine if a Set-Cookie header should be set for this session cookie for this response. If the session has been modified, the cookie is set. If the session is permanent and the SESSION_REFRESH_EACH_REQUEST config is true, the cookie is always set. This check is usually skipped if the session was deleted. Changelog New in version 0.11. Parameters app (Flask) – session (flask.sessions.SessionMixin) – Return type bool
flask.api.index#flask.sessions.SessionInterface
get_cookie_domain(app) Returns the domain that should be set for the session cookie. Uses SESSION_COOKIE_DOMAIN if it is configured, otherwise falls back to detecting the domain based on SERVER_NAME. Once detected (or if not set at all), SESSION_COOKIE_DOMAIN is updated to avoid re-running the logic. Parameters app (Flask) – Return type Optional[str]
flask.api.index#flask.sessions.SessionInterface.get_cookie_domain
get_cookie_httponly(app) Returns True if the session cookie should be httponly. This currently just returns the value of the SESSION_COOKIE_HTTPONLY config var. Parameters app (Flask) – Return type bool
flask.api.index#flask.sessions.SessionInterface.get_cookie_httponly
get_cookie_name(app) Returns the name of the session cookie. Uses app.session_cookie_name which is set to SESSION_COOKIE_NAME Parameters app (Flask) – Return type str
flask.api.index#flask.sessions.SessionInterface.get_cookie_name
get_cookie_path(app) Returns the path for which the cookie should be valid. The default implementation uses the value from the SESSION_COOKIE_PATH config var if it’s set, and falls back to APPLICATION_ROOT or uses / if it’s None. Parameters app (Flask) – Return type str
flask.api.index#flask.sessions.SessionInterface.get_cookie_path
get_cookie_samesite(app) Return 'Strict' or 'Lax' if the cookie should use the SameSite attribute. This currently just returns the value of the SESSION_COOKIE_SAMESITE setting. Parameters app (Flask) – Return type str
flask.api.index#flask.sessions.SessionInterface.get_cookie_samesite
get_cookie_secure(app) Returns True if the cookie should be secure. This currently just returns the value of the SESSION_COOKIE_SECURE setting. Parameters app (Flask) – Return type bool
flask.api.index#flask.sessions.SessionInterface.get_cookie_secure
get_expiration_time(app, session) A helper method that returns an expiration date for the session or None if the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application. Parameters app (Flask) – session (flask.sessions.SessionMixin) – Return type Optional[datetime.datetime]
flask.api.index#flask.sessions.SessionInterface.get_expiration_time
is_null_session(obj) Checks if a given object is a null session. Null sessions are not asked to be saved. This checks if the object is an instance of null_session_class by default. Parameters obj (object) – Return type bool
flask.api.index#flask.sessions.SessionInterface.is_null_session
make_null_session(app) Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed. This creates an instance of null_session_class by default. Parameters app (Flask) – Return type flask.sessions.NullSession
flask.api.index#flask.sessions.SessionInterface.make_null_session
null_session_class make_null_session() will look here for the class that should be created when a null session is requested. Likewise the is_null_session() method will perform a typecheck against this type. alias of flask.sessions.NullSession
flask.api.index#flask.sessions.SessionInterface.null_session_class
open_session(app, request) This method has to be implemented and must either return None in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on SessionMixin. Parameters app (Flask) – request (Request) – Return type Optional[flask.sessions.SessionMixin]
flask.api.index#flask.sessions.SessionInterface.open_session
pickle_based = False A flag that indicates if the session interface is pickle based. This can be used by Flask extensions to make a decision in regards to how to deal with the session object. Changelog New in version 0.10.
flask.api.index#flask.sessions.SessionInterface.pickle_based
save_session(app, session, response) This is called for actual sessions returned by open_session() at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that. Parameters app (Flask) – session (flask.sessions.SessionMixin) – response (Response) – Return type None
flask.api.index#flask.sessions.SessionInterface.save_session
should_set_cookie(app, session) Used by session backends to determine if a Set-Cookie header should be set for this session cookie for this response. If the session has been modified, the cookie is set. If the session is permanent and the SESSION_REFRESH_EACH_REQUEST config is true, the cookie is always set. This check is usually skipped if the session was deleted. Changelog New in version 0.11. Parameters app (Flask) – session (flask.sessions.SessionMixin) – Return type bool
flask.api.index#flask.sessions.SessionInterface.should_set_cookie
class flask.sessions.SessionMixin Expands a basic dictionary with session attributes. accessed = True Some implementations can detect when session data is read or written and set this when that happens. The mixin default is hard coded to True. modified = True Some implementations can detect changes to the session and set this when that happens. The mixin default is hard coded to True. property permanent: bool This reflects the '_permanent' key in the dict.
flask.api.index#flask.sessions.SessionMixin
accessed = True Some implementations can detect when session data is read or written and set this when that happens. The mixin default is hard coded to True.
flask.api.index#flask.sessions.SessionMixin.accessed
modified = True Some implementations can detect changes to the session and set this when that happens. The mixin default is hard coded to True.
flask.api.index#flask.sessions.SessionMixin.modified
SESSION_COOKIE_DOMAIN The domain match rule that the session cookie will be valid for. If not set, the cookie will be valid for all subdomains of SERVER_NAME. If False, the cookie’s domain will not be set. Default: None
flask.config.index#SESSION_COOKIE_DOMAIN
SESSION_COOKIE_HTTPONLY Browsers will not allow JavaScript access to cookies marked as “HTTP only” for security. Default: True
flask.config.index#SESSION_COOKIE_HTTPONLY
SESSION_COOKIE_NAME The name of the session cookie. Can be changed in case you already have a cookie with the same name. Default: 'session'
flask.config.index#SESSION_COOKIE_NAME
SESSION_COOKIE_PATH The path that the session cookie will be valid for. If not set, the cookie will be valid underneath APPLICATION_ROOT or / if that is not set. Default: None
flask.config.index#SESSION_COOKIE_PATH
SESSION_COOKIE_SAMESITE Restrict how cookies are sent with requests from external sites. Can be set to 'Lax' (recommended) or 'Strict'. See Set-Cookie options. Default: None Changelog New in version 1.0.
flask.config.index#SESSION_COOKIE_SAMESITE
SESSION_COOKIE_SECURE Browsers will only send cookies with requests over HTTPS if the cookie is marked “secure”. The application must be served over HTTPS for this to make sense. Default: False
flask.config.index#SESSION_COOKIE_SECURE
SESSION_REFRESH_EACH_REQUEST Control whether the cookie is sent with every response when session.permanent is true. Sending the cookie every time (the default) can more reliably keep the session from expiring, but uses more bandwidth. Non-permanent sessions are not affected. Default: True
flask.config.index#SESSION_REFRESH_EACH_REQUEST
Signals Changelog New in version 0.6. Starting with Flask 0.6, there is integrated support for signalling in Flask. This support is provided by the excellent blinker library and will gracefully fall back if it is not available. What are signals? Signals help you decouple applications by sending notifications when actions occur elsewhere in the core framework or another Flask extensions. In short, signals allow certain senders to notify subscribers that something happened. Flask comes with a couple of signals and other extensions might provide more. Also keep in mind that signals are intended to notify subscribers and should not encourage subscribers to modify data. You will notice that there are signals that appear to do the same thing like some of the builtin decorators do (eg: request_started is very similar to before_request()). However, there are differences in how they work. The core before_request() handler, for example, is executed in a specific order and is able to abort the request early by returning a response. In contrast all signal handlers are executed in undefined order and do not modify any data. The big advantage of signals over handlers is that you can safely subscribe to them for just a split second. These temporary subscriptions are helpful for unit testing for example. Say you want to know what templates were rendered as part of a request: signals allow you to do exactly that. Subscribing to Signals To subscribe to a signal, you can use the connect() method of a signal. The first argument is the function that should be called when the signal is emitted, the optional second argument specifies a sender. To unsubscribe from a signal, you can use the disconnect() method. For all core Flask signals, the sender is the application that issued the signal. When you subscribe to a signal, be sure to also provide a sender unless you really want to listen for signals from all applications. This is especially true if you are developing an extension. For example, here is a helper context manager that can be used in a unit test to determine which templates were rendered and what variables were passed to the template: from flask import template_rendered from contextlib import contextmanager @contextmanager def captured_templates(app): recorded = [] def record(sender, template, context, **extra): recorded.append((template, context)) template_rendered.connect(record, app) try: yield recorded finally: template_rendered.disconnect(record, app) This can now easily be paired with a test client: with captured_templates(app) as templates: rv = app.test_client().get('/') assert rv.status_code == 200 assert len(templates) == 1 template, context = templates[0] assert template.name == 'index.html' assert len(context['items']) == 10 Make sure to subscribe with an extra **extra argument so that your calls don’t fail if Flask introduces new arguments to the signals. All the template rendering in the code issued by the application app in the body of the with block will now be recorded in the templates variable. Whenever a template is rendered, the template object as well as context are appended to it. Additionally there is a convenient helper method (connected_to()) that allows you to temporarily subscribe a function to a signal with a context manager on its own. Because the return value of the context manager cannot be specified that way, you have to pass the list in as an argument: from flask import template_rendered def captured_templates(app, recorded, **extra): def record(sender, template, context): recorded.append((template, context)) return template_rendered.connected_to(record, app) The example above would then look like this: templates = [] with captured_templates(app, templates, **extra): ... template, context = templates[0] Blinker API Changes The connected_to() method arrived in Blinker with version 1.1. Creating Signals If you want to use signals in your own application, you can use the blinker library directly. The most common use case are named signals in a custom Namespace.. This is what is recommended most of the time: from blinker import Namespace my_signals = Namespace() Now you can create new signals like this: model_saved = my_signals.signal('model-saved') The name for the signal here makes it unique and also simplifies debugging. You can access the name of the signal with the name attribute. For Extension Developers If you are writing a Flask extension and you want to gracefully degrade for missing blinker installations, you can do so by using the flask.signals.Namespace class. Sending Signals If you want to emit a signal, you can do so by calling the send() method. It accepts a sender as first argument and optionally some keyword arguments that are forwarded to the signal subscribers: class Model(object): ... def save(self): model_saved.send(self) Try to always pick a good sender. If you have a class that is emitting a signal, pass self as sender. If you are emitting a signal from a random function, you can pass current_app._get_current_object() as sender. Passing Proxies as Senders Never pass current_app as sender to a signal. Use current_app._get_current_object() instead. The reason for this is that current_app is a proxy and not the real application object. Signals and Flask’s Request Context Signals fully support The Request Context when receiving signals. Context-local variables are consistently available between request_started and request_finished, so you can rely on flask.g and others as needed. Note the limitations described in Sending Signals and the request_tearing_down signal. Decorator Based Signal Subscriptions With Blinker 1.1 you can also easily subscribe to signals by using the new connect_via() decorator: from flask import template_rendered @template_rendered.connect_via(app) def when_template_rendered(sender, template, context, **extra): print f'Template {template.name} is rendered with {context}' Core Signals Take a look at Signals for a list of all builtin signals.
flask.signals.index
flask.stream_with_context(generator_or_function) Request contexts disappear when the response is started on the server. This is done for efficiency reasons and to make it less likely to encounter memory leaks with badly written WSGI middlewares. The downside is that if you are using streamed responses, the generator cannot access request bound information any more. This function however can help you keep the context around for longer: from flask import stream_with_context, request, Response @app.route('/stream') def streamed_response(): @stream_with_context def generate(): yield 'Hello ' yield request.args['name'] yield '!' return Response(generate()) Alternatively it can also be used around a specific generator: from flask import stream_with_context, request, Response @app.route('/stream') def streamed_response(): def generate(): yield 'Hello ' yield request.args['name'] yield '!' return Response(stream_with_context(generate())) Changelog New in version 0.9. Parameters generator_or_function (Union[Generator, Callable]) – Return type Generator
flask.api.index#flask.stream_with_context
class flask.json.tag.TaggedJSONSerializer Serializer that uses a tag system to compactly represent objects that are not JSON types. Passed as the intermediate serializer to itsdangerous.Serializer. The following extra types are supported: dict tuple bytes Markup UUID datetime Return type None default_tags = [<class 'flask.json.tag.TagDict'>, <class 'flask.json.tag.PassDict'>, <class 'flask.json.tag.TagTuple'>, <class 'flask.json.tag.PassList'>, <class 'flask.json.tag.TagBytes'>, <class 'flask.json.tag.TagMarkup'>, <class 'flask.json.tag.TagUUID'>, <class 'flask.json.tag.TagDateTime'>] Tag classes to bind when creating the serializer. Other tags can be added later using register(). dumps(value) Tag the value and dump it to a compact JSON string. Parameters value (Any) – Return type str loads(value) Load data from a JSON string and deserialized any tagged objects. Parameters value (str) – Return type Any register(tag_class, force=False, index=None) Register a new tag with this serializer. Parameters tag_class (Type[flask.json.tag.JSONTag]) – tag class to register. Will be instantiated with this serializer instance. force (bool) – overwrite an existing tag. If false (default), a KeyError is raised. index (Optional[int]) – index to insert the new tag in the tag order. Useful when the new tag is a special case of an existing tag. If None (default), the tag is appended to the end of the order. Raises KeyError – if the tag key is already registered and force is not true. Return type None tag(value) Convert a value to a tagged representation if necessary. Parameters value (Any) – Return type Dict[str, Any] untag(value) Convert a tagged representation back to the original type. Parameters value (Dict[str, Any]) – Return type Any
flask.api.index#flask.json.tag.TaggedJSONSerializer
default_tags = [<class 'flask.json.tag.TagDict'>, <class 'flask.json.tag.PassDict'>, <class 'flask.json.tag.TagTuple'>, <class 'flask.json.tag.PassList'>, <class 'flask.json.tag.TagBytes'>, <class 'flask.json.tag.TagMarkup'>, <class 'flask.json.tag.TagUUID'>, <class 'flask.json.tag.TagDateTime'>] Tag classes to bind when creating the serializer. Other tags can be added later using register().
flask.api.index#flask.json.tag.TaggedJSONSerializer.default_tags
dumps(value) Tag the value and dump it to a compact JSON string. Parameters value (Any) – Return type str
flask.api.index#flask.json.tag.TaggedJSONSerializer.dumps
loads(value) Load data from a JSON string and deserialized any tagged objects. Parameters value (str) – Return type Any
flask.api.index#flask.json.tag.TaggedJSONSerializer.loads
register(tag_class, force=False, index=None) Register a new tag with this serializer. Parameters tag_class (Type[flask.json.tag.JSONTag]) – tag class to register. Will be instantiated with this serializer instance. force (bool) – overwrite an existing tag. If false (default), a KeyError is raised. index (Optional[int]) – index to insert the new tag in the tag order. Useful when the new tag is a special case of an existing tag. If None (default), the tag is appended to the end of the order. Raises KeyError – if the tag key is already registered and force is not true. Return type None
flask.api.index#flask.json.tag.TaggedJSONSerializer.register
tag(value) Convert a value to a tagged representation if necessary. Parameters value (Any) – Return type Dict[str, Any]
flask.api.index#flask.json.tag.TaggedJSONSerializer.tag
untag(value) Convert a tagged representation back to the original type. Parameters value (Dict[str, Any]) – Return type Any
flask.api.index#flask.json.tag.TaggedJSONSerializer.untag
Templates Flask leverages Jinja2 as its template engine. You are obviously free to use a different template engine, but you still have to install Jinja2 to run Flask itself. This requirement is necessary to enable rich extensions. An extension can depend on Jinja2 being present. This section only gives a very quick introduction into how Jinja2 is integrated into Flask. If you want information on the template engine’s syntax itself, head over to the official Jinja2 Template Documentation for more information. Jinja Setup Unless customized, Jinja2 is configured by Flask as follows: autoescaping is enabled for all templates ending in .html, .htm, .xml as well as .xhtml when using render_template(). autoescaping is enabled for all strings when using render_template_string(). a template has the ability to opt in/out autoescaping with the {% autoescape %} tag. Flask inserts a couple of global functions and helpers into the Jinja2 context, additionally to the values that are present by default. Standard Context The following global variables are available within Jinja2 templates by default: config The current configuration object (flask.config) Changelog Changed in version 0.10: This is now always available, even in imported templates. New in version 0.6. request The current request object (flask.request). This variable is unavailable if the template was rendered without an active request context. session The current session object (flask.session). This variable is unavailable if the template was rendered without an active request context. g The request-bound object for global variables (flask.g). This variable is unavailable if the template was rendered without an active request context. url_for() The flask.url_for() function. get_flashed_messages() The flask.get_flashed_messages() function. The Jinja Context Behavior These variables are added to the context of variables, they are not global variables. The difference is that by default these will not show up in the context of imported templates. This is partially caused by performance considerations, partially to keep things explicit. What does this mean for you? If you have a macro you want to import, that needs to access the request object you have two possibilities: you explicitly pass the request to the macro as parameter, or the attribute of the request object you are interested in. you import the macro “with context”. Importing with context looks like this: {% from '_helpers.html' import my_macro with context %} Controlling Autoescaping Autoescaping is the concept of automatically escaping special characters for you. Special characters in the sense of HTML (or XML, and thus XHTML) are &, >, <, " as well as '. Because these characters carry specific meanings in documents on their own you have to replace them by so called “entities” if you want to use them for text. Not doing so would not only cause user frustration by the inability to use these characters in text, but can also lead to security problems. (see Cross-Site Scripting (XSS)) Sometimes however you will need to disable autoescaping in templates. This can be the case if you want to explicitly inject HTML into pages, for example if they come from a system that generates secure HTML like a markdown to HTML converter. There are three ways to accomplish that: In the Python code, wrap the HTML string in a Markup object before passing it to the template. This is in general the recommended way. Inside the template, use the |safe filter to explicitly mark a string as safe HTML ({{ myvariable|safe }}) Temporarily disable the autoescape system altogether. To disable the autoescape system in templates, you can use the {% autoescape %} block: {% autoescape false %} <p>autoescaping is disabled here <p>{{ will_not_be_escaped }} {% endautoescape %} Whenever you do this, please be very cautious about the variables you are using in this block. Registering Filters If you want to register your own filters in Jinja2 you have two ways to do that. You can either put them by hand into the jinja_env of the application or use the template_filter() decorator. The two following examples work the same and both reverse an object: @app.template_filter('reverse') def reverse_filter(s): return s[::-1] def reverse_filter(s): return s[::-1] app.jinja_env.filters['reverse'] = reverse_filter In case of the decorator the argument is optional if you want to use the function name as name of the filter. Once registered, you can use the filter in your templates in the same way as Jinja2’s builtin filters, for example if you have a Python list in context called mylist: {% for x in mylist | reverse %} {% endfor %} Context Processors To inject new variables automatically into the context of a template, context processors exist in Flask. Context processors run before the template is rendered and have the ability to inject new values into the template context. A context processor is a function that returns a dictionary. The keys and values of this dictionary are then merged with the template context, for all templates in the app: @app.context_processor def inject_user(): return dict(user=g.user) The context processor above makes a variable called user available in the template with the value of g.user. This example is not very interesting because g is available in templates anyways, but it gives an idea how this works. Variables are not limited to values; a context processor can also make functions available to templates (since Python allows passing around functions): @app.context_processor def utility_processor(): def format_price(amount, currency="€"): return f"{amount:.2f}{currency}" return dict(format_price=format_price) The context processor above makes the format_price function available to all templates: {{ format_price(0.33) }} You could also build format_price as a template filter (see Registering Filters), but this demonstrates how to pass functions in a context processor.
flask.templating.index
TEMPLATES_AUTO_RELOAD Reload templates when they are changed. If not set, it will be enabled in debug mode. Default: None
flask.config.index#TEMPLATES_AUTO_RELOAD
TESTING Enable testing mode. Exceptions are propagated rather than handled by the the app’s error handlers. Extensions may also change their behavior to facilitate easier testing. You should enable this in your own tests. Default: False
flask.config.index#TESTING
TRAP_BAD_REQUEST_ERRORS Trying to access a key that doesn’t exist from request dicts like args and form will return a 400 Bad Request error page. Enable this to treat the error as an unhandled exception instead so that you get the interactive debugger. This is a more specific version of TRAP_HTTP_EXCEPTIONS. If unset, it is enabled in debug mode. Default: None
flask.config.index#TRAP_BAD_REQUEST_ERRORS
TRAP_HTTP_EXCEPTIONS If there is no handler for an HTTPException-type exception, re-raise it to be handled by the interactive debugger instead of returning it as a simple error response. Default: False
flask.config.index#TRAP_HTTP_EXCEPTIONS
flask.url_for(endpoint, **values) Generates a URL to the given endpoint with the method provided. Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments. If the value of a query argument is None, the whole pair is skipped. In case blueprints are active you can shortcut references to the same blueprint by prefixing the local endpoint with a dot (.). This will reference the index function local to the current blueprint: url_for('.index') See URL Building. Configuration values APPLICATION_ROOT and SERVER_NAME are only used when generating URLs outside of a request context. To integrate applications, Flask has a hook to intercept URL build errors through Flask.url_build_error_handlers. The url_for function results in a BuildError when the current app does not have a URL for the given endpoint and values. When it does, the current_app calls its url_build_error_handlers if it is not None, which can return a string to use as the result of url_for (instead of url_for’s default to raise the BuildError exception) or re-raise the exception. An example: def external_url_handler(error, endpoint, values): "Looks up an external URL when `url_for` cannot build a URL." # This is an example of hooking the build_error_handler. # Here, lookup_url is some utility function you've built # which looks up the endpoint in some external URL registry. url = lookup_url(endpoint, **values) if url is None: # External lookup did not have a URL. # Re-raise the BuildError, in context of original traceback. exc_type, exc_value, tb = sys.exc_info() if exc_value is error: raise exc_type(exc_value).with_traceback(tb) else: raise error # url_for will use this result, instead of raising BuildError. return url app.url_build_error_handlers.append(external_url_handler) Here, error is the instance of BuildError, and endpoint and values are the arguments passed into url_for. Note that this is for building URLs outside the current application, and not for handling 404 NotFound errors. Changelog New in version 0.10: The _scheme parameter was added. New in version 0.9: The _anchor and _method parameters were added. New in version 0.9: Calls Flask.handle_build_error() on BuildError. Parameters endpoint (str) – the endpoint of the URL (name of the function) values (Any) – the variable arguments of the URL rule _external – if set to True, an absolute URL is generated. Server address can be changed via SERVER_NAME configuration variable which falls back to the Host header, then to the IP and port of the request. _scheme – a string specifying the desired URL scheme. The _external parameter must be set to True or a ValueError is raised. The default behavior uses the same scheme as the current request, or PREFERRED_URL_SCHEME if no request context is available. This also can be set to an empty string to build protocol-relative URLs. _anchor – if provided this is added as anchor to the URL. _method – if provided this explicitly specifies an HTTP method. Return type str
flask.api.index#flask.url_for