This part of the documentation covers all the interfaces of Flask. Forparts where Flask depends on external libraries, we document the mostimportant right here and provide links to the canonical documentation.
The flask object implements a WSGI application and acts as the centralobject. It is passed the name of the module or package of theapplication. Once it is created it will act as a central registry forthe view functions, the URL rules, template configuration and much more.
The name of the package is used to resolve resources from inside thepackage or the folder the module is contained in depending on if thepackage parameter resolves to an actual python package (a folder withan init.py file inside) or a standard module (just a .py file).
For more information about resource loading, see open_resource().
Usually you create a Flask instance in your main module orin the init.py file of your package like this:
from flask importFlask
app =Flask(__name__)
About the First Parameter
The idea of the first parameter is to give Flask an idea of whatbelongs to your application. This name is used to find resourceson the filesystem, can be used by extensions to improve debugginginformation and a lot more.
So it’s important what you provide there. If you are using a singlemodule, name is always the correct value. If you however areusing a package, it’s usually recommended to hardcode the name ofyour package there.
For example if your application is defined in yourapplication/app.pyyou should create it with one of the two versions below:
app =Flask('yourapplication')
app =Flask(__name__.split('.')[0])
Why is that? The application will work even with name, thanksto how resources are looked up. However it will make debugging morepainful. Certain extensions can make assumptions based on theimport name of your application. For example the Flask-SQLAlchemyextension will look for the code in your application that triggeredan SQL query in debug mode. If the import name is not properly setup, that debugging information is lost. (For example it would onlypick up SQL queries in yourapplication.app and notyourapplication.views.frontend)
Changelog
New in version 1.0: The host_matching and static_host parameters were added.
New in version 1.0: The subdomain_matching parameter was added. Subdomainmatching needs to be enabled manually now. SettingSERVER_NAME does not implicitly enable it.
New in version 0.11: The root_path parameter was added.
New in version 0.8: The instance_path and instance_relative_config parameters wereadded.
New in version 0.7: The static_url_path, static_folder, and _template_folder_parameters were added.
Parameters
import_name – the name of the application package
static_url_path – can be used to specify a different path for thestatic files on the web. Defaults to the nameof the static_folder folder.
static_folder – the folder with static files that should be servedat static_url_path. Defaults to the 'static'folder in the root path of the application.
static_host – the host to use when adding the static route.Defaults to None. Required when using host_matching=Truewith a static_folder configured.
host_matching – set url_map.host_matching attribute.Defaults to False.
subdomain_matching – consider the subdomain relative toSERVER_NAME when matching routes. Defaults to False.
template_folder – the folder that contains the templates that shouldbe used by the application. Defaults to'templates' folder in the root path of theapplication.
instance_path – An alternative instance path for the application.By default the folder 'instance' next to thepackage or module is assumed to be the instancepath.
instance_relative_config – if set to True relative filenamesfor loading the config are assumed tobe relative to the instance path insteadof the application root.
root_path – Flask by default will automatically calculate the pathto the root of the application. In certain situationsthis cannot be achieved (for instance if the packageis a Python 3 namespace package) and needs to bemanually defined.
addtemplate_filter(_f, name=None)
Register a custom template filter. Works exactly like thetemplate_filter() decorator.
Parameters
name – the optional name of the filter, otherwise thefunction name will be used.
addtemplate_global(_f, name=None)
Register a custom template global function. Works exactly like thetemplate_global() decorator.
Changelog
New in version 0.10.
-Parameters
-
name – the optional name of the global function, otherwise thefunction name will be used.
addtemplate_test(_f, name=None)
Register a custom template test. Works exactly like thetemplate_test() decorator.
Changelog
New in version 0.10.
-Parameters
-
name – the optional name of the test, otherwise thefunction name will be used.
Changed in version 0.6: OPTIONS is added automatically as method.
Changed in version 0.2: view_func parameter added.
-Parameters
-
-
rule – the URL rule as string
-
endpoint – the endpoint for the registered URL rule. Flaskitself assumes the name of the view function asendpoint
-
view_func – the function to call when serving a request to theprovided endpoint
-
provide_automatic_options – controls whether the OPTIONSmethod should be added automatically. This can also be controlledby setting the view_func.provide_automatic_options = Falsebefore adding the rule.
-
options – the options to be forwarded to the underlyingRule object. A changeto Werkzeug is handling of method options. methodsis a list of methods this rule should be limitedto (GET, POST etc.). By default a rulejust listens for GET (and implicitly HEAD).Starting with Flask 0.6, OPTIONS is implicitlyadded and handled by the standard request handling.
afterrequest(_f)
Register a function to be run after each request.
Your function must take one parameter, an instance ofresponse_class and return a new response object or thesame (see process_response()).
As of Flask 0.7 this function might not be executed at the end of therequest in case an unhandled exception occurred.
afterrequest_funcs = None_
A dictionary with lists of functions that should be called aftereach request. The key of the dictionary is the name of the blueprintthis function is active for, None for all requests. This can forexample be used to close database connections. To register a functionhere, use the after_request() decorator.
app_context()
Create an AppContext. Use as a withblock to push the context, which will make current_apppoint at this application.
An application context is automatically pushed byRequestContext.push()when handling a request, and when running a CLI command. Usethis to manually create a context outside of these situations.
Tries to locate the instance path if it was not provided to theconstructor of the application class. It will basically calculatethe path to a folder named instance next to your main file orthe package.
Changelog
New in version 0.8.
beforefirst_request(_f)
Registers a function to be run before the first request to thisinstance of the application.
The function will be called without any arguments and its returnvalue is ignored.
Changelog
New in version 0.8.
beforefirst_request_funcs = None_
A list of functions that will be called at the beginning of thefirst request to this instance. To register a function, use thebefore_first_request() decorator.
Changelog
New in version 0.8.
beforerequest(_f)
Registers a function to run before each request.
For example, this can be used to open a database connection, or to loadthe logged in user from the session.
The function will be called without any arguments. If it returns anon-None value, the value is handled as if it was the return value fromthe view, and further request handling is stopped.
beforerequest_funcs = None_
A dictionary with lists of functions that will be called at thebeginning of each request. The key of the dictionary is the name ofthe blueprint this function is active for, or None for allrequests. To register a function, use the before_request()decorator.
blueprints = None
all the attached blueprints in a dictionary by name. Blueprintscan be attached multiple times so this dictionary does not tellyou how often they got attached.
Changelog
New in version 0.7.
config = None
The configuration dictionary as Config. This behavesexactly like a regular dictionary but supports additional methodsto load a config from files.
config_class
alias of flask.config.Config
contextprocessor(_f)
Registers a template context processor function.
create_global_jinja_loader()
Creates the loader for the Jinja2 environment. Can be used tooverride just the loader and keeping the rest unchanged. It’sdiscouraged to override this function. Instead one should overridethe jinja_loader() function instead.
The global loader dispatches between the loaders of the applicationand the individual blueprints.
Changelog
New in version 0.7.
create_jinja_environment()
Create the Jinja environment based on jinja_optionsand the various Jinja-related methods of the app. Changingjinja_options after this will have no effect. Also addsFlask-related globals and filters to the environment.
Changelog
Changed in version 0.11: Environment.auto_reload set in accordance withTEMPLATES_AUTO_RELOAD configuration option.
New in version 0.5.
createurl_adapter(_request)
Creates a URL adapter for the given request. The URL adapteris created at a point where the request context is not yet setup so the request is passed explicitly.
Changelog
Changed in version 1.0: SERVER_NAME no longer implicitly enables subdomainmatching. Use subdomain_matching instead.
Changed in version 0.9: This can now also be called without a request object when theURL adapter is created for the application context.
New in version 0.6.
property debug
Whether debug mode is enabled. When using flask run to startthe development server, an interactive debugger will be shown forunhandled exceptions, and the server will be reloaded when codechanges. This maps to the DEBUG config key. This isenabled when env is 'development' and is overriddenby the FLASK_DEBUG environment variable. It may not behave asexpected if set in code.
Do not enable debug mode when deploying in production.
Default: True if env is 'development', orFalse otherwise.
Does the request dispatching. Matches the URL and returns thereturn value of the view or error handler. This does not have tobe a response object. In order to convert the return value to aproper response object, call make_response().
Changelog
Changed in version 0.7: This no longer does the exception handling, this code wasmoved to the new full_dispatch_request().
Represents a blueprint, a collection of routes and otherapp-related functions that can be registered on a real applicationlater.
A blueprint is an object that allows defining application functionswithout requiring an application object ahead of time. It uses thesame decorators as Flask, but defers the need for anapplication by recording them for later registration.
Decorating a function with a blueprint creates a deferred functionthat is called with BlueprintSetupStatewhen the blueprint is registered on an application.
Changed in version 1.1.0: Blueprints have a cli group to register nested CLI commands.The cli_group parameter controls the name of the group underthe flask command.
Changelog
New in version 0.7.
Parameters
name – The name of the blueprint. Will be prepended to eachendpoint name.
import_name – The name of the blueprint package, usuallyname. This helps locate the root_path for theblueprint.
static_folder – A folder with static files that should beserved by the blueprint’s static route. The path is relative tothe blueprint’s root path. Blueprint static files are disabledby default.
static_url_path – The url to serve static files from.Defaults to static_folder. If the blueprint does not havea url_prefix, the app’s static route will take precedence,and the blueprint’s static files won’t be accessible.
template_folder – A folder with templates that should be addedto the app’s template search path. The path is relative to theblueprint’s root path. Blueprint templates are disabled bydefault. Blueprint templates have a lower precedence than thosein the app’s templates folder.
url_prefix – A path to prepend to all of the blueprint’s URLs,to make them distinct from the rest of the app’s routes.
subdomain – A subdomain that blueprint routes will match on bydefault.
url_defaults – A dict of default values that blueprint routeswill receive by default.
root_path – By default, the blueprint will automatically thisbased on import_name. In certain situations this automaticdetection can fail, so the path can be specified manuallyinstead.
Like Flask.before_request(). Such a function is executedbefore each request, even if outside of a blueprint.
beforerequest(_f)
Like Flask.before_request() but for a blueprint. This functionis only executed before each request that is handled by a function ofthat blueprint.
contextprocessor(_f)
Like Flask.context_processor() but for a blueprint. Thisfunction is only executed for requests handled by a blueprint.
endpoint(endpoint)
Like Flask.endpoint() but for a blueprint. This does notprefix the endpoint with the blueprint name, this has to be doneexplicitly by the user of this method. If the endpoint is prefixedwith a . it will be registered to the current blueprint, otherwiseit’s an application independent endpoint.
errorhandler(code_or_exception)
Registers an error handler that becomes active for this blueprintonly. Please be aware that routing does not happen local to ablueprint so an error handler for 404 usually is not handled bya blueprint unless it is caused inside a view function. Anotherspecial case is the 500 internal server error which is always lookedup from the application.
Provides default cache_timeout for the send_file() functions.
By default, this function returns SEND_FILE_MAX_AGE_DEFAULT fromthe configuration of current_app.
Static file functions such as send_from_directory() use thisfunction, and send_file() calls this function oncurrent_app when the given cache_timeout is None. If acache_timeout is given in send_file(), that timeout is used;otherwise, this method is called.
This allows subclasses to change the behavior when sending files basedon the filename. For example, to set the cache timeout for .js filesto 60 seconds:
class MyFlask(flask.Flask):
def get_send_file_max_age(self, name):
if name.lower().endswith('.js'):
return 60
return flask.Flask.get_send_file_max_age(self, name)
Changelog
New in version 0.9.
property has_static_folder
This is True if the package bound object’s container has afolder for static files.
Changelog
New in version 0.5.
importname = None_
The name of the package or module that this app belongs to. Do notchange this once it is set by the constructor.
jinja_loader
The Jinja loader for this package bound object.
Changelog
New in version 0.5.
jsondecoder = None_
Blueprint local JSON decoder class to use.Set to None to use the app’s json_decoder.
jsonencoder = None_
Blueprint local JSON decoder class to use.Set to None to use the app’s json_encoder.
Creates an instance of BlueprintSetupState()object that is later passed to the register callback functions.Subclasses can override this to return a subclass of the setup state.
openresource(_resource, mode='rb')
Opens a resource from the application’s resource folder. To seehow this works, consider the following folder structure:
If you want to open the schema.sql file you would do thefollowing:
with app.open_resource('schema.sql') as f:
contents = f.read()
do_something_with(contents)
- Parameters
-
-
resource – the name of the resource. To access resources withinsubfolders use forward slashes as separator.
-
mode – Open file in this mode. Only reading is supported,valid values are “r” (or “rt”) and “rb”.
record(func)
Registers a function that is called when the blueprint isregistered on the application. This function is called with thestate as argument as returned by the make_setup_state()method.
recordonce(_func)
Works like record() but wraps the function in anotherfunction that will ensure the function is only called once. If theblueprint is registered a second time on the application, thefunction passed is not called.
first_registration – Whether this is the first time thisblueprint has been registered on the application.
registererror_handler(_code_or_exception, f)
Non-decorator version of the errorhandler() error attachfunction, akin to the register_error_handler()application-wide function of the Flask object butfor error handlers limited to this blueprint.
Changelog
New in version 0.11.
rootpath = None_
Absolute path to the package on the filesystem. Used to look upresources contained in the package.
route(rule, **options)
Like Flask.route() but for a blueprint. The endpoint for theurl_for() function is prefixed with the name of the blueprint.
sendstatic_file(_filename)
Function used internally to send static files from the staticfolder to the browser.
Changelog
New in version 0.5.
property static_folder
The absolute path to the configured static folder.
property static_url_path
The URL prefix that the static route will be accessible from.
If it was not configured during init, it is derived fromstatic_folder.
teardownapp_request(_f)
Like Flask.teardown_request() but for a blueprint. Such afunction is executed when tearing down each request, even if outside ofthe blueprint.
teardownrequest(_f)
Like Flask.teardown_request() but for a blueprint. Thisfunction is only executed when tearing down requests handled by afunction of that blueprint. Teardown request functions are executedwhen the request context is popped, even when no actual request wasperformed.
templatefolder = None_
Location of the template files to be added to the template lookup.None if templates should not be added.
urldefaults(_f)
Callback function for URL defaults for this blueprint. It’s calledwith the endpoint and values and should update the values passedin place.
urlvalue_preprocessor(_f)
Registers a function as URL value preprocessor for thisblueprint. It’s called before the view functions are called andcan modify the url values provided.
Incoming Request Data
class flask.Request(environ, populate_request=True, shallow=False)
The request object used by default in Flask. Remembers thematched endpoint and view arguments.
It is what ends up as request. If you want to replacethe request object used you can subclass this and setrequest_class to your subclass.
The request object is a Request subclass andprovides all of the attributes Werkzeug defines plus a few Flaskspecific ones.
environ
The underlying WSGI environment.
path
full_path
script_root
url
base_url
url_root
Provides different ways to look at the current IRI. Imagine your application islistening on the following application root:
List of charsets this client supports asCharsetAccept object.
property accept_encodings
List of encodings this client accepts. Encodings in a HTTP termare compression encodings such as gzip. For charsets have a look ataccept_charset.
property accept_languages
List of languages this client accepts asLanguageAccept object.
property accept_mimetypes
List of mimetypes this client supports asMIMEAccept object.
property access_route
If a forwarded header exists this is a list of all ip addressesfrom the client ip to the last proxy server.
classmethod application(f)
Decorate a function as responder that accepts the request asthe last argument. This works like the responder()decorator but the function is passed the request object as thelast argument and the request object will be closedautomatically:
As of Werkzeug 0.14 HTTP exceptions are automatically caught andconverted to responses instead of failing.
- Parameters
-
f – the WSGI callable to decorate
- Returns
-
a new WSGI callable
property args
The parsed URL parameters (the part in the URL after the questionmark).
By default anImmutableMultiDictis returned from this function. This can be changed by settingparameter_storage_class to a different type. This mightbe necessary if the order of the form data is important.
property authorization
The Authorization object in parsed form.
property base_url
Like url but without the querystringSee also: trusted_hosts.
Closes associated resources of this request object. Thiscloses all file handles explicitly. You can also use the requestobject in a with statement which will automatically close it.
Changelog
New in version 0.9.
content_encoding
The Content-Encoding entity-header field is used as amodifier to the media-type. When present, its value indicateswhat additional content codings have been applied to theentity-body, and thus what decoding mechanisms must be appliedin order to obtain the media-type referenced by the Content-Typeheader field.
Changelog
New in version 0.9.
property content_length
The Content-Length entity-header field indicates the size of theentity-body in bytes or, in the case of the HEAD method, the size ofthe entity-body that would have been sent had the request been aGET.
content_md5
The Content-MD5 entity-header field, as defined inRFC 1864, is an MD5 digest of the entity-body for the purpose ofproviding an end-to-end message integrity check (MIC) of theentity-body. (Note: a MIC is good for detecting accidentalmodification of the entity-body in transit, but is not proofagainst malicious attacks.)
Changelog
New in version 0.9.
content_type
The Content-Type entity-header field indicates the mediatype of the entity-body sent to the recipient or, in the case ofthe HEAD method, the media type that would have been sent hadthe request been a GET.
property cookies
A dict with the contents of all cookies transmitted withthe request.
property data
Contains the incoming request data as string in case it came witha mimetype Werkzeug does not handle.
date
The Date general-header field represents the date andtime at which the message was originated, having the samesemantics as orig-date in RFC 822.
The endpoint that matched the request. This in combination withview_args can be used to reconstruct the same or amodified URL. If an exception happened when matching, this willbe None.
property files
MultiDict object containingall uploaded files. Each key in files is the name from the<input type="file" name="">. Each value in files is aWerkzeug FileStorage object.
It basically behaves like a standard file object you know from Python,with the difference that it also has asave() function that canstore the file on the filesystem.
Note that files will only contain data if the request method wasPOST, PUT or PATCH and the <form> that posted to the request hadenctype="multipart/form-data". It will be empty otherwise.
See the MultiDict /FileStorage documentation formore details about the used data structure.
property form
The form parameters. By default anImmutableMultiDictis returned from this function. This can be changed by settingparameter_storage_class to a different type. This mightbe necessary if the order of the form data is important.
Please keep in mind that file uploads will not end up here, but insteadin the files attribute.
Changelog
Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POSTand PUT requests.
Create a new request object based on the values provided. Ifenviron is given missing values are filled from there. This method isuseful for small scripts when you need to simulate a request from an URL.Do not use this method for unittesting, there is a full featured clientobject (Client) that allows to create multipart requests,support for cookies etc.
Changed in version 0.5: This method now accepts the same arguments asEnvironBuilder. Because of this theenviron parameter is now called environ_overrides.
- Returns
-
request object
property full_path
Requested path as unicode, including the query string.
This reads the buffered incoming data from the client into onebytestring. By default this is cached but that behavior can bechanged by setting cache to False.
Usually it’s a bad idea to call this method without checking thecontent length first as a client could send dozens of megabytes or moreto cause memory problems on the server.
Note that if the form data was already parsed this method will notreturn anything as form data parsing does not cache the data likethis method does. To implicitly invoke form data parsing functionset parse_form_data to True. When this is done the return valueof this method will be an empty string if the form parser handlesthe data. This generally is not necessary as if the whole data iscached (which is the default) the form parser will used the cacheddata to parse the form data. Please be generally aware of checkingthe content length first in any case before calling this methodto avoid exhausting server memory.
If as_text is set to True the return value will be a decodedunicode string.
The parsed If-Unmodified-Since header as datetime object.
property is_json
Check if the mimetype indicates JSON data, eitherapplication/json or application/*+json.
is_multiprocess
boolean that is True if the application is served by aWSGI server that spawns multiple processes.
is_multithread
boolean that is True if the application is served by amultithreaded WSGI server.
is_run_once
boolean that is True if the application will beexecuted only once in a process lifetime. This is the case forCGI for example, but it’s not guaranteed that the execution onlyhappens one time.
property is_secure
True if the request is secure.
property is_xhr
True if the request was triggered via a JavaScript XMLHttpRequest.This only works with libraries that support the X-Requested-Withheader and set it to “XMLHttpRequest”. Libraries that do that areprototype, jQuery and Mochikit and probably some more.
Deprecated since version 0.13: X-Requested-With is not standard and is unreliable. Youmay be able to use AcceptMixin.accept_mimetypesinstead.
property json
The parsed JSON data if mimetype indicates JSON(application/json, see is_json()).
Creates the form data parser. Instantiates theform_data_parser_class with some parameters.
Changelog
New in version 0.8.
property max_content_length
Read-only view of the MAX_CONTENT_LENGTH config key.
max_forwards
The Max-Forwards request-header field provides amechanism with the TRACE and OPTIONS methods to limit the numberof proxies or gateways that can forward the request to the nextinbound server.
method
The request method. (For example 'GET' or 'POST').
property mimetype
Like content_type, but without parameters (eg, withoutcharset, type etc.) and always lowercase. For example if the contenttype is text/HTML; charset=utf-8 the mimetype would be'text/html'.
property mimetype_params
The mimetype parameters as dict. For example if the contenttype is text/html; charset=utf-8 the params would be{'charset': 'utf-8'}.
onjson_loading_failed(_e)
Called if get_json() parsing fails and isn’t silenced.If this method returns a value, it is used as the return valuefor get_json(). The default implementation raisesBadRequest.
Requested path as unicode. This works a bit like the regular pathinfo in the WSGI environment but will always include a leading slash,even if the URL root is accessed.
property pragma
The Pragma general-header field is used to includeimplementation-specific directives that might apply to any recipientalong the request/response chain. All pragma directives specifyoptional behavior from the viewpoint of the protocol; however, somesystems MAY require that behavior be consistent with the directives.
The Referer[sic] request-header field allows the clientto specify, for the server’s benefit, the address (URI) of theresource from which the Request-URI was obtained (the“referrer”, although the header field is misspelled).
property remote_addr
The remote address of the client.
remote_user
If the server supports user authentication, and thescript is protected, this attribute contains the username theuser has authenticated as.
routingexception = None_
If matching the URL failed, this is the exception that will beraised / was raised as part of the request handling. This isusually a NotFound exception orsomething similar.
scheme
URL scheme (http or https).
Changelog
New in version 0.7.
property script_root
The root path of the script without the trailing slash.
property stream
If the incoming form data was not encoded with a known mimetypethe data is stored unmodified in this stream for consumption. Mostof the time it is a better idea to use data which will giveyou that data as a string. The stream only returns the data once.
Unlike input_stream this stream is properly guarded that youcan’t accidentally read past the length of the input. Werkzeug willinternally always refer to this stream to read data which makes itpossible to wrap this object with a stream that does filtering.
Changelog
Changed in version 0.9: This stream is now always available but might be consumed by theform parser later on. Previously the stream was only set if noparsing happened.
property url
The reconstructed current URL as IRI.See also: trusted_hosts.
property url_charset
The charset that is assumed for URLs. Defaults to the valueof charset.
Changelog
New in version 0.6.
property url_root
The full URL root (with hostname), this is the applicationroot as IRI.See also: trusted_hosts.
urlrule = None_
The internal URL rule that matched the request. This can beuseful to inspect which methods are allowed for the URL froma before/after handler (request.url_rule.methods) etc.Though if the request’s method was invalid for the URL rule,the valid list is available in routing_exception.valid_methodsinstead (an attribute of the Werkzeug exceptionMethodNotAllowed)because the request was never internally bound.
A dict of view arguments that matched the request. If an exceptionhappened when matching, this will be None.
property want_form_data_parsed
Returns True if the request method carries content. As ofWerkzeug 0.9 this will be the case if a content type is transmitted.
Changelog
New in version 0.8.
flask.request
To access incoming request data, you can use the global _request_object. Flask parses incoming request data for you and gives youaccess to it through that global object. Internally Flask makessure that you always get the correct data for the active thread if youare in a multithreaded environment.
This is a proxy. See 关于代理的说明 for more information.
The request object is an instance of a Requestsubclass and provides all of the attributes Werkzeug defines. Thisjust shows a quick overview of the most important ones.
Response Objects
class flask.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)
The response object that is used by default in Flask. Works like theresponse object from Werkzeug but is set to have an HTML mimetype bydefault. Quite often you don’t have to create this object yourself becausemake_response() will take care of that for you.
If you want to replace the response object used you can subclass this andset response_class to your subclass.
Changelog
Changed in version 1.0: JSON support is added to the response, like the request. This is usefulwhen testing to get the test client response data as JSON.
Sets a cookie. The parameters are the same as in the cookie _Morsel_object in the Python standard library but it accepts unicode data, too.
A warning is raised if the size of the cookie header exceedsmax_cookie_size, but the header will still be set.
- Parameters
-
-
key – the key (name) of the cookie to be set.
-
value – the value of the cookie.
-
max_age – should be a number of seconds, or None (default) ifthe cookie should last only as long as the client’sbrowser session.
-
expires – should be a datetime object or UNIX timestamp.
-
path – limits the cookie to a given path, per default it willspan the whole domain.
-
domain – if you want to set a cross-domain cookie. For example,domain=".example.com" will set a cookie that isreadable by the domain www.example.com,foo.example.com etc. Otherwise, a cookie will onlybe readable by the domain that set it.
-
secure – If True, the cookie will only be available via HTTPS
-
httponly – disallow JavaScript to access the cookie. This is anextension to the cookie standard and probably notsupported by all browsers.
-
samesite – Limits the scope of the cookie such that it will onlybe attached to requests if those requests are“same-site”.
Sessions
If you have set Flask.secret_key (or configured it fromSECRET_KEY) you can use sessions in Flask applications. A session makesit possible to remember information from one request to another. The way Flaskdoes this is by using a signed cookie. The user can look at the sessioncontents, but can’t modify it unless they know the secret key, so make sure toset that to something complex and unguessable.
To access the current session you can use the session object:
class flask.session
The session object works pretty much like an ordinary dict, with thedifference that it keeps track on modifications.
This is a proxy. See 关于代理的说明 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 advisedthat modifications on mutable structures are not picked upautomatically, in that situation you have to explicitly set theattribute 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 forpermanent_session_lifetime seconds. Thedefault is 31 days. If set to False (which is the default) thesession will be deleted when the user closes the browser.
Session Interface
Changelog
New in version 0.8.
The session interface provides a simple way to replace the sessionimplementation that Flask is using.
class flask.sessions.SessionInterface
The basic interface you have to implement in order to replace thedefault session interface which uses werkzeug’s securecookieimplementation. The only methods you have to implement areopen_session() and save_session(), the others haveuseful defaults which you don’t need to change.
The session object returned by the open_session() method has toprovide a dictionary like interface plus the properties and methodsfrom the SessionMixin. We recommend just subclassing a dictand adding that mixin:
class Session(dict, SessionMixin):
pass
If open_session() returns None Flask will call intomake_null_session() to create a session that acts as replacementif the session support cannot work because some requirement is notfulfilled. The default NullSession class that is createdwill complain that the secret key was not set.
Returns the domain that should be set for the session cookie.
Uses SESSION_COOKIE_DOMAIN if it is configured, otherwisefalls back to detecting the domain based on SERVER_NAME.
Once detected (or if not set at all), SESSION_COOKIE_DOMAIN isupdated to avoid re-running the logic.
getcookie_httponly(_app)
Returns True if the session cookie should be httponly. Thiscurrently just returns the value of the SESSION_COOKIE_HTTPONLYconfig var.
getcookie_path(_app)
Returns the path for which the cookie should be valid. Thedefault implementation uses the value from the SESSION_COOKIE_PATHconfig var if it’s set, and falls back to APPLICATION_ROOT oruses / if it’s None.
getcookie_samesite(_app)
Return 'Strict' or 'Lax' if the cookie should use theSameSite attribute. This currently just returns the value ofthe SESSION_COOKIE_SAMESITE setting.
getcookie_secure(_app)
Returns True if the cookie should be secure. This currentlyjust returns the value of the SESSION_COOKIE_SECURE setting.
getexpiration_time(_app, session)
A helper method that returns an expiration date for the sessionor None if the session is linked to the browser session. Thedefault implementation returns now + the permanent sessionlifetime configured on the application.
isnull_session(_obj)
Checks if a given object is a null session. Null sessions arenot asked to be saved.
This checks if the object is an instance of null_session_classby default.
makenull_session(_app)
Creates a null session which acts as a replacement object if thereal session support could not be loaded due to a configurationerror. This mainly aids the user experience because the job of thenull session is to still support lookup without complaining butmodifications are answered with a helpful error message of whatfailed.
make_null_session() will look here for the class that shouldbe created when a null session is requested. Likewise theis_null_session() method will perform a typecheck againstthis type.
This method has to be implemented and must either return Nonein case the loading failed because of a configuration error or aninstance of a session object which implements a dictionary likeinterface + the methods and attributes on SessionMixin.
picklebased = False_
A flag that indicates if the session interface is pickle based.This can be used by Flask extensions to make a decision in regardsto how to deal with the session object.
Changelog
New in version 0.10.
savesession(_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 requestcontext so if you absolutely need access to the request you can dothat.
shouldset_cookie(_app, session)
Used by session backends to determine if a Set-Cookie headershould be set for this session cookie for this response. If the sessionhas been modified, the cookie is set. If the session is permanent andthe SESSION_REFRESH_EACH_REQUEST config is true, the cookie isalways set.
This check is usually skipped if the session was deleted.
Changelog
New in version 0.11.
class flask.sessions.SecureCookieSessionInterface
The default session interface that stores sessions in signed cookiesthrough the itsdangerous module.
static digest_method()
the hash function to use for the signature. The default is sha1
keyderivation = 'hmac'_
the name of the itsdangerous supported key derivation. The defaultis hmac.
opensession(_app, request)
This method has to be implemented and must either return Nonein case the loading failed because of a configuration error or aninstance of a session object which implements a dictionary likeinterface + the methods and attributes on SessionMixin.
salt = 'cookie-session'
the salt that should be applied on top of the secret key for thesigning of cookie based sessions.
savesession(_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 requestcontext so if you absolutely need access to the request you can dothat.
serializer =
A python serializer for the payload. The default is a compactJSON derived serializer with support for some extra Python typessuch as datetime objects or tuples.
class flask.sessions.SecureCookieSession(initial=None)
Base class for sessions based on signed cookies.
This session backend will set the modified andaccessed attributes. It cannot reliably track whether asession is new (vs. empty), so new remains hard coded toFalse.
accessed = False
header, which allows caching proxies to cache different pages fordifferent users.
get(key, default=None)
Return the value for key if key is in the dictionary, else default.
modified = False
When data is changed, this is set to True. Only the sessiondictionary itself is tracked; if the session contains mutabledata (for example a nested dict) then this must be set toTrue manually when modifying that data. The session cookiewill 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.
class flask.sessions.NullSession(initial=None)
Class used to generate nicer error messages if sessions are notavailable. Will still allow read-only access to the empty sessionbut fail on setting.
class flask.sessions.SessionMixin
Expands a basic dictionary with session attributes.
accessed = True
Some implementations can detect when session data is read orwritten and set this when that happens. The mixin default is hardcoded to True.
modified = True
Some implementations can detect changes to the session and setthis when that happens. The mixin default is hard coded toTrue.
property permanent
This reflects the '_permanent' key in the dict.
Notice
The PERMANENT_SESSION_LIFETIME config key can also be an integerstarting with Flask 0.8. Either catch this down yourself or usethe permanent_session_lifetime attribute on theapp which converts the result to an integer automatically.
Test Client
class flask.testing.FlaskClient(*args, **kwargs)
Works like a regular Werkzeug test client but has some knowledge abouthow Flask works to defer the cleanup of the request context stack to theend of a with body when used in a with statement. For generalinformation about how to use this class refer towerkzeug.test.Client.
Changelog
Changed in version 0.12: app.test_client() includes preset default environment, which can beset after instantiation of the app.test_client() object inclient.environ_base.
Basic usage is outlined in the 测试 Flask 应用 chapter.
open(*args, **kwargs)
Takes the same arguments as the EnvironBuilder class withsome additions: You can provide a EnvironBuilder or a WSGIenvironment as only argument instead of the EnvironBuilderarguments and two optional keyword arguments (as_tuple, buffered)that change the type of the return value or the way the application isexecuted.
Changelog
Changed in version 0.5: If a dict is provided as file in the dict for the data parameterthe content type has to be called content_type now instead ofmimetype. This change was made for consistency withwerkzeug.FileWrapper.
The follow_redirects parameter was added to open().
Additional parameters:
- Parameters
-
-
as_tuple – Returns a tuple in the form (environ, result)
-
buffered – Set this to True to buffer the application run.This will automatically close the application foryou as well.
-
follow_redirects – Set this to True if the Client shouldfollow HTTP redirects.
sessiontransaction(args, *kwargs_)
When used in combination with a with statement this opens asession transaction. This can be used to modify the session thatthe test client uses. Once the with block is left the session isstored back.
with client.session_transaction() as session:
session['value'] = 42
Internally this is implemented by going through a temporary testrequest context and since session handling could depend onrequest variables this function accepts the same arguments astest_request_context() which are directlypassed through.
To share data that is valid for one request only from one function toanother, a global variable is not good enough because it would break inthreaded environments. Flask provides you with a special object thatensures it is only valid for the active request and that will returndifferent values for each request. In a nutshell: it does the rightthing, like it does for request and session.
This is a good place to store resources during a request. Duringtesting, you can use the 伪造资源和环境 pattern topre-configure such resources.
This is a proxy. See 关于代理的说明 for more information.
Changelog
Changed in version 0.10: Bound to the application context instead of the request context.
class flask.ctx._AppCtxGlobals
A plain object. Used as a namespace for storing data during anapplication context.
Creating an app context automatically creates this object, which ismade available as the g proxy.
'key' in g
Check whether an attribute is present.
Changelog
New in version 0.10.
iter(g)
Return an iterator over the attribute names.
Changelog
New in version 0.10.
get(name, default=None)
Get an attribute by name, or a default value. Likedict.get().
Parameters
name – Name of attribute to get.
default – Value to return if the attribute is not present.
Changelog
New in version 0.10.
pop(name, default=)
Get and remove an attribute by name. Like dict.pop().
Parameters
name – Name of attribute to pop.
default – Value to return if the attribute is not present,instead of raise a KeyError.
Changelog
New in version 0.11.
setdefault(name, default=None)
Get the value of an attribute if it is present, otherwiseset and return a default value. Like dict.setdefault().
Parameters
name – Name of attribute to get.
Param
default: Value to set and return if the attribute is notpresent.
Changelog
New in version 0.11.
Useful Functions and Classes
flask.current_app
A proxy to the application handling the current request. This isuseful to access the application without needing to import it, or ifit can’t be imported, such as when using the application factorypattern or in blueprints and extensions.
This is only available when anapplication context is pushed. This happensautomatically during requests and CLI commands. It can be controlledmanually with app_context().
This is a proxy. See 关于代理的说明 for more information.
flask.has_request_context()
If you have code that wants to test if a request context is there ornot this function can be used. For instance, you may want to take advantageof request information if the request object is available, but failsilently if it is unavailable.
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and has_request_context():
remote_addr = request.remote_addr
self.remote_addr = remote_addr
Alternatively you can also just test any of the context bound objects(such as request or g) for truthness:
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and request:
remote_addr = request.remote_addr
self.remote_addr = remote_addr
Changelog
New in version 0.7.
flask.copycurrent_request_context(_f)
A helper function that decorates a function to retain the currentrequest context. This is useful when working with greenlets. The momentthe function is decorated a copy of the request context is created andthen pushed when the function is called. The current session is alsoincluded in the copied request context.
Example:
import gevent
from flask import copy_current_request_context
@app.route('/')
def index():
@copy_current_request_context
def do_some_work():
# do some work here, it can access flask.request or
# flask.session like you would otherwise in the view function.
...
gevent.spawn(do_some_work)
return 'Regular response'
Changelog
New in version 0.10.
flask.has_app_context()
Works like has_request_context() but for the applicationcontext. You can also just do a boolean check on thecurrent_app object instead.
Changelog
New in version 0.9.
flask.urlfor(_endpoint, **values)
Generates a URL to the given endpoint with the method provided.
Variable arguments that are unknown to the target endpoint are appendedto the generated URL as query arguments. If the value of a query argumentis None, the whole pair is skipped. In case blueprints are activeyou can shortcut references to the same blueprint by prefixing thelocal endpoint with a dot (.).
This will reference the index function local to the current blueprint:
url_for('.index')
For more information, head over to the Quickstart.
Configuration values APPLICATION_ROOT and SERVER_NAME are only used whengenerating URLs outside of a request context.
To integrate applications, Flask has a hook to intercept URL builderrors through Flask.url_build_error_handlers. The url_for_function results in a BuildError when the currentapp does not have a URL for the given endpoint and values. When it does, thecurrent_app calls its url_build_error_handlers ifit is not None, which can return a string to use as the result of_url_for (instead of url_for’s default to raise theBuildError 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, 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, andendpoint and values are the arguments passed into url_for. Notethat this is for building URLs outside the current application, and not forhandling 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() onBuildError.
Parameters
endpoint – the endpoint of the URL (name of the function)
values – the variable arguments of the URL rule
_external – if set to True, an absolute URL is generated. Serveraddress can be changed via SERVERNAME configuration variable whichfalls 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 defaultbehavior uses the same scheme as the current request, orPREFERRED_URL_SCHEME from the app configuration if norequest context is available. As of Werkzeug 0.10, this also can be setto 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.
flask.abort(status, *args, **kwargs)
Raises an HTTPException for the given status code or WSGIapplication:
abort(404) # 404 Not Found
abort(Response('Hello World'))
Can be passed a WSGI application or a status code. If a status code isgiven it’s looked up in the list of exceptions and will raise thatexception, if passed a WSGI application it will wrap it in a proxy WSGIexception and raise that:
abort(404)
abort(Response('Hello World'))
flask.redirect(location, code=302, Response=None)
Returns a response object (a WSGI application) that, if called,redirects the client to the target location. Supported codes are301, 302, 303, 305, 307, and 308. 300 is not supported becauseit’s not a real redirect and 304 because it’s the answer for arequest with a request with defined If-Modified-Since headers.
Changelog
New in version 0.10: The class used for the Response object can now be passed in.
New in version 0.6: The location can now be a unicode string that is encoded usingthe iri_to_uri() function.
Parameters
location – the location the response should redirect to.
code – the redirect status code. defaults to 302.
Response (class) – a Response class to use when instantiating aresponse. The default is werkzeug.wrappers.Response ifunspecified.
flask.makeresponse(*args_)
Sometimes it is necessary to set additional headers in a view. Becauseviews do not have to return response objects but can return a value thatis converted into a response object by Flask itself, it becomes tricky toadd headers to it. This function can be called instead of using a returnand you will get a response object which you can use to attach headers.
If view looked like this and you want to add a new header:
if more than one argument is passed, the arguments are passedto the flask.Flask.make_response() function as tuple.
Changelog
New in version 0.6.
flask.afterthis_request(_f)
Executes a function after this request. This is useful to modifyresponse objects. The function is passed the response object and hasto return the same or a new one.
This is more useful if a function other than the view function wants tomodify a response. For instance think of a decorator that wants to addsome headers without converting the return value into a response object.
Sends the contents of a file to the client. This will use themost efficient method available and configured. By default it willtry to use the WSGI server’s file_wrapper support. Alternativelyyou can set the application’s use_x_sendfile attributeto True to directly emit an X-Sendfile header. This howeverrequires support of the underlying webserver for X-Sendfile.
By default it will try to guess the mimetype for you, but you canalso explicitly provide one. For extra security you probably wantto send certain files as attachment (HTML for instance). The mimetypeguessing requires a filename or an attachment_filename to beprovided.
ETags will also be attached automatically if a filename is provided. Youcan turn this off by setting add_etags=False.
If conditional=True and filename is provided, this method will try toupgrade the response stream to support range requests. This will allowthe request to be answered with partial content response.
Please never pass filenames to this function from user sources;you should use send_from_directory() instead.
Changelog
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. Ifyou want to use automatic mimetype and etag support, pass a filepath viafilename_or_fp or attachment_filename.
Changed in version 0.12: The attachment_filename is preferred over filename for MIME-typedetection.
Changed in version 0.9: cache_timeout pulls its default from application config, when None.
Changed in version 0.7: mimetype guessing and etag support for file objects wasdeprecated because it was unreliable. Pass a filename if you areable to, otherwise attach an etag yourself. This functionalitywill be removed in Flask 1.0
New in version 0.5: The add_etags, cache_timeout and conditional parameters wereadded. The default behavior is now to attach etags.
New in version 0.2.
Changed in version 1.1: Filename may be a PathLike object.
New in version 1.1: Partial content supports BytesIO.
Changelog
Changed in version 1.0.3: Filenames are encoded with ASCII instead of Latin-1 for broadercompatibility with WSGI servers.
Parameters
filename_or_fp – the filename of the file to send.This is relative to the root_pathif a relative path is specified.Alternatively a file object might be provided inwhich case X-Sendfile might not work and fallback to the traditional method. Make sure that thefile pointer is positioned at the start of data tosend before calling send_file().
mimetype – the mimetype of the file if provided. If a file path isgiven, auto detection happens as fallback, otherwise anerror will be raised.
as_attachment – set to True if you want to send this file witha Content-Disposition: attachment header.
attachment_filename – the filename for the attachment if itdiffers from the file’s filename.
add_etags – set to False to disable attaching of etags.
conditional – set to True to enable conditional responses.
It is strongly recommended to activate either X-Sendfile support inyour webserver or (if no authentication happens) to tell the webserverto serve files for the given path on its own without calling into theweb application for improved performance.
Changelog
New in version 0.5.
Parameters
directory – the directory where all the files are stored.
filename – the filename relative to that directory todownload.
options – optional keyword arguments that are directlyforwarded to send_file().
flask.safejoin(_directory, *pathnames)
Safely join directory and zero or more untrusted _pathnames_components.
Example usage:
@app.route('/wiki/<path:filename>')
def wiki_page(filename):
filename = safe_join(app.config['WIKI_FOLDER'], filename)
with open(filename, 'rb') as fd:
content = fd.read() # Read and process the file content...
Parameters
directory – the trusted base directory.
pathnames – the untrusted pathnames relative to that directory.
Raises
NotFound if one or more passedpaths fall out of its boundaries.
flask.escape(s) → markup
Convert the characters &, <, >, ‘, and ” in string s to HTML-safesequences. Use this if you need to display text that might containsuch characters in HTML. Marks return value as markup string.
class flask.Markup
A string that is ready to be safely inserted into an HTML or XMLdocument, either because it was escaped or because it was markedsafe.
Passing an object to the constructor converts it to text and wrapsit to mark it safe without escaping. To escape the text, use theescape() class method instead.
This implements the html() interface that some frameworksuse. Passing an object that implements html() will wrap theoutput of that method, marking it safe.
This is a subclass of the text type (str in Python 3,unicode in Python 2). It has the same methods as that type, butall methods escape their arguments and return a Markup instance.
Flashes a message to the next request. In order to remove theflashed message from the session and to display it to the user,the template has to call get_flashed_messages().
Changelog
Changed in version 0.3: category parameter added.
Parameters
message – the message to be flashed.
category – the category for the message. The following valuesare recommended: 'message' for any kind of message,'error' for errors, 'info' for informationmessages and 'warning' for warnings. However anykind of string can be used as category.
Pulls all flashed messages from the session and returns them.Further calls in the same request to the function will returnthe same messages. By default just the messages are returned,but when with_categories is set to True, the return value willbe a list of tuples in the form (category, message) instead.
Filter the flashed messages to one or more categories by providing thosecategories in category_filter. This allows rendering categories inseparate html blocks. The with_categories and _category_filter_arguments are distinct:
with_categories controls whether categories are returned with messagetext (True gives a tuple, where False gives just the message text).
category_filter filters the messages down to only those matching theprovided categories.
Changed in version 0.9: category_filter parameter added.
Changed in version 0.3: with_categories parameter added.
Parameters
with_categories – set to True to also receive categories.
category_filter – whitelist of categories to limit return values
JSON Support
Flask uses simplejson for the JSON implementation. Since simplejsonis provided by both the standard library as well as extension, Flask willtry simplejson first and then fall back to the stdlib json module. On topof that it will delegate access to the current application’s JSON encodersand decoders for easier customization.
So for starters instead of doing:
try:
import simplejson as json
except ImportError:
import json
You can instead just do this:
from flask import json
For usage examples, read the json documentation in the standardlibrary. The following extensions are by default applied to the stdlib’sJSON module:
datetime objects are serialized as RFC 822 strings.
Any object with an html method (like Markup)will have that method called and then the return value is serializedas string.
The htmlsafe_dumps() function of this json module is also availableas filter called |tojson in Jinja2. Note that inside scripttags no escaping must take place, so make sure to disable escapingwith |safe if you intend to use it inside script tags unlessyou are using Flask 0.10 which implies that:
The configuration variable JSON_SORT_KEYS (配置管理) can beset to false to stop Flask from auto-sorting keys. By default sortingis enabled and outside of the app context sorting is turned on.
Notice that disabling key sorting can cause issues when using contentbased HTTP caches and Python’s hash randomization feature.
flask.json.jsonify(*args, **kwargs)
This function wraps dumps() to add a few enhancements that makelife easier. It turns the JSON output into a Responseobject with the application/json mimetype. For convenience, italso converts multiple arguments into an array or multiple keyword argumentsinto a dict. This means that both jsonify(1,2,3) andjsonify([1,2,3]) serialize to [1,2,3].
For clarity, the JSON serialization behavior has the following differencesfrom dumps():
Single argument: Passed straight through to dumps().
Multiple arguments: Converted to an array before being passed todumps().
Multiple keyword arguments: Converted to a dict before being passed todumps().
Both args and kwargs: Behavior undefined and will throw an exception.
Changed in version 0.11: Added support for serializing top-level arrays. This introduces asecurity risk in ancient browsers. See JSON 安全 for details.
This function’s response will be pretty printed if theJSONIFY_PRETTYPRINT_REGULAR config parameter is set to True or theFlask app is running in debug mode. Compressed (not pretty) formattingcurrently means no indents and no spaces after separators.
Changelog
New in version 0.2.
flask.json.dumps(obj, app=None, **kwargs)
Serialize obj to a JSON-formatted string. If there is anapp context pushed, use the current app’s configured encoder(json_encoder), or fall back to the defaultJSONEncoder.
Takes the same arguments as the built-in json.dumps(), anddoes some extra configuration based on the application. If thesimplejson package is installed, it is preferred.
Parameters
obj – Object to serialize to JSON.
app – App instance to use to configure the JSON encoder.Uses current_app if not given, and falls back to the defaultencoder when not in an app context.
Deserialize an object from a JSON-formatted string s. Ifthere is an app context pushed, use the current app’s configureddecoder (json_decoder), or fall back to thedefault JSONDecoder.
Takes the same arguments as the built-in json.loads(), anddoes some extra configuration based on the application. If thesimplejson package is installed, it is preferred.
Parameters
s – JSON string to deserialize.
app – App instance to use to configure the JSON decoder.Uses current_app if not given, and falls back to the defaultencoder when not in an app context.
class flask.json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
The default JSON decoder. This one does not change the behavior fromthe default simplejson decoder. Consult the json documentationfor more information. This decoder is not only used for the loadfunctions of this module but also Request.
Tagged JSON
A compact representation for lossless serialization of non-standard JSON types.SecureCookieSessionInterface uses this to serializethe session data, but it may be useful in other places. It can be extended tosupport other types.
class flask.json.tag.TaggedJSONSerializer
Serializer that uses a tag system to compactly represent objects thatare not JSON types. Passed as the intermediate serializer toitsdangerous.Serializer.
Tag classes to bind when creating the serializer. Other tags can beadded later using register().
dumps(value)
Tag the value and dump it to a compact JSON string.
loads(value)
Load data from a JSON string and deserialized any tagged objects.
register(tag_class, force=False, index=None)
Register a new tag with this serializer.
Parameters
tag_class – tag class to register. Will be instantiated with thisserializer instance.
force – overwrite an existing tag. If false (default), aKeyError is raised.
index – index to insert the new tag in the tag order. Useful whenthe 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 isnot true.
tag(value)
Convert a value to a tagged representation if necessary.
untag(value)
Convert a tagged representation back to the original type.
Check if the given value should be tagged by this tag.
key = None
The tag to mark the serialized object with. If None, this tag isonly used as an intermediate step during tagging.
tag(value)
Convert the value to a valid JSON type and add the tag structurearound it.
tojson(_value)
Convert the Python object to an object that is a valid JSON type.The tag will be added later.
topython(_value)
Convert the JSON representation back to the correct type. The tagwill already be removed.
Let’s seen an example that adds support for OrderedDict.Dicts don’t have an order in Python or JSON, so to handle this we will dumpthe items as a list of [key, value] pairs. Subclass JSONTag andgive it the new key ' od' to identify the type. The session serializerprocesses dicts first, so insert the new tag at the front of the order sinceOrderedDict must be processed before dict.
from flask.json.tag import JSONTag
class TagOrderedDict(JSONTag):
__slots__ = ('serializer',)
key = ' od'
def check(self, value):
return isinstance(value, OrderedDict)
def to_json(self, value):
return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]
def to_python(self, value):
return OrderedDict(value)
app.session_interface.serializer.register(TagOrderedDict, index=0)
Loads a macro (or variable) a template exports. This can be used toinvoke a macro from within Python code. If you for example have atemplate named _cider.html with the following contents:
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
attribute – the name of the variable of macro to access
Configuration
class flask.Config(root_path, defaults=None)
Works exactly like a dict but provides ways to fill it from filesor special dictionaries. There are two common patterns to populate theconfig.
Either you can fill the config from a config file:
app.config.from_pyfile('yourconfig.cfg')
Or alternatively you can define the configuration options in themodule that calls from_object() or provide an import path toa module that should be loaded. It is also possible to tell it touse the same module and with that provide the configuration valuesjust before the call:
In both cases (loading from any Python file or loading from modules),only uppercase keys are added to the config. This makes it possible to uselowercase values in the config file for temporary values that are not addedto the config or to define the config keys in the same file that implementsthe application.
Probably the most interesting way to load configurations is from anenvironment variable pointing to a file:
In this case before launching the application you have to set thisenvironment variable to the file you want to use. On Linux and OS Xuse the export statement:
root_path – path to which files are read relative from. When theconfig object is created by the application, this isthe application’s root_path.
defaults – an optional dictionary of default values
fromenvvar(_variable_name, silent=False)
Loads a configuration from an environment variable pointing toa configuration file. This is basically just a shortcut with nicererror messages for this line of code:
silent – set to True if you want silent failure for missingfiles.
- Returns
-
bool. True if able to load config, False otherwise.
fromjson(_filename, silent=False)
Updates the values in the config from a JSON file. This functionbehaves as if the JSON object was a dictionary and passed to thefrom_mapping() function.
Parameters
filename – the filename of the JSON file. This can either be anabsolute filename or a filename relative to theroot path.
silent – set to True if you want silent failure for missingfiles.
Changelog
New in version 0.11.
frommapping(mapping, *kwargs_)
Updates the config like update() ignoring items with non-upperkeys.
Changelog
New in version 0.11.
fromobject(_obj)
Updates the values from the given object. An object can be of oneof the following two types:
a string: in this case the object with that name will be imported
an actual object reference: that object is used directly
Objects are usually either modules or classes. from_object()loads only the uppercase attributes of the module/class. A dictobject will not work with from_object() because the keys of adict are not attributes of the dict class.
Example of module-based configuration:
app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)
Nothing is done to the object before loading. If the object is aclass and has @property attributes, it needs to beinstantiated before being passed to this method.
You should not use this function to load the actual configuration butrather configuration defaults. The actual config should be loadedwith from_pyfile() and ideally from a location not within thepackage because the package might be installed system wide.
See 开发/生产 for an example of class-based configurationusing from_object().
- Parameters
-
obj – an import name or object
frompyfile(_filename, silent=False)
Updates the values in the config from a Python file. This functionbehaves as if the file was imported as module with thefrom_object() function.
Parameters
filename – the filename of the config. This can either be anabsolute filename or a filename relative to theroot path.
silent – set to True if you want silent failure for missingfiles.
This is often useful when configuration options map directly tokeyword arguments in functions or class constructors.
- Parameters
-
-
namespace – a configuration namespace
-
lowercase – a flag indicating if the keys of the resultingdictionary should be lowercase
-
trim_namespace – a flag indicating if the keys of the resultingdictionary should not include the namespace
Changelog
New in version 0.11.
Stream Helpers
flask.streamwith_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 encountermemory leaks with badly written WSGI middlewares. The downside is that ifyou are using streamed responses, the generator cannot access request boundinformation any more.
This function however can help you keep the context around for longer:
class flask.ctx.RequestContext(app, environ, request=None, session=None)
The request context contains all request relevant information. It iscreated at the beginning of the request and pushed to the_request_ctx_stack and removed at the end of it. It will create theURL adapter and request object for the WSGI environment provided.
When the request context is popped, it will evaluate all thefunctions registered on the application for teardown execution(teardown_request()).
The request context is automatically popped at the end of the requestfor you. In debug mode the request context is kept around ifexceptions happen so that interactive debuggers have a chance tointrospect the data. With 0.4 this can also be forced for requeststhat did not fail and outside of DEBUG mode. By setting'flask._preserve_context' to True on the WSGI environment thecontext will not pop itself at the end of the request. This is used bythe test_client() for example to implement thedeferred cleanup functionality.
You might find this helpful for unittests where you need theinformation from the context local around for a little longer. Makesure to properly pop() the stack yourself inthat situation, otherwise your unittests will leak memory.
copy()
Creates a copy of this request context with the same request object.This can be used to move a request context to a different greenlet.Because the actual request object is the same this cannot be used tomove a request context to a different thread unless access to therequest object is locked.
Changed in version 1.1: The current session object is used instead of reloading the originaldata. This prevents flask.session pointing to an out-of-date object.
Changelog
New in version 0.10.
match_request()
Can be overridden by a subclass to hook into the matchingof the request.
pop(exc=)
Pops the request context and unbinds it by doing that. This willalso trigger the execution of functions registered by theteardown_request() decorator.
Changelog
Changed in version 0.9: Added the exc argument.
push()
Binds the request context to the current context.
flask._request_ctx_stack
The internal LocalStack that holdsRequestContext instances. Typically, therequest and session proxies should be accessedinstead of the stack. It may be useful to access the stack inextension code.
The following attributes are always present on each layer of thestack:
app
the active Flask application.
url_adapter
the URL adapter that was used to match the request.
request
the current request object.
session
the active session object.
g
an object with all the attributes of the flask.g object.
flashes
an internal cache for the flashed messages.
Example usage:
from flask import _request_ctx_stack
def get_session():
ctx = _request_ctx_stack.top
if ctx is not None:
return ctx.session
class flask.ctx.AppContext(app)
The application context binds an application object implicitlyto the current thread or greenlet, similar to how theRequestContext binds request information. The applicationcontext is also implicitly created if a request context is createdbut the application is not on top of the individual applicationcontext.
pop(exc=)
Pops the app context.
push()
Binds the app context to the current context.
flask._app_ctx_stack
The internal LocalStack that holdsAppContext instances. Typically, thecurrent_app and g proxies should be accessed insteadof the stack. Extensions can access the contexts on the stack as anamespace to store data.
Changelog
New in version 0.9.
class flask.blueprints.BlueprintSetupState(blueprint, app, options, first_registration)
Temporary holder object for registering a blueprint with theapplication. An instance of this class is created by themake_setup_state() method and later passedto all register callback functions.
A helper method to register a rule (and optionally a view function)to the application. The endpoint is automatically prefixed with theblueprint’s name.
app = None
a reference to the current application
blueprint = None
a reference to the blueprint that created this setup state.
firstregistration = None_
as blueprints can be registered multiple times with theapplication and not everything wants to be registeredmultiple times on it, this attribute can be used to figureout if the blueprint was registered in the past already.
options = None
a dictionary with all options that were passed to theregister_blueprint() method.
subdomain = None
The subdomain that the blueprint should be active for, Noneotherwise.
urldefaults = None_
A dictionary with URL defaults that is added to each and everyURL that was defined with the blueprint.
urlprefix = None_
The prefix that should be used for all URLs defined on theblueprint.
Signals
Changelog
New in version 0.6.
signals.signals_available
True if the signaling system is available. This is the casewhen blinker is installed.
The following signals exist in Flask:
flask.template_rendered
This signal is sent when a template was successfully rendered. Thesignal is invoked with the instance of the template as template_and the context as dictionary (named _context).
Example subscriber:
def log_template_renders(sender, template, context, **extra):
sender.logger.debug('Rendering template "%s" with context %s',
template.name or 'string template',
context)
from flask import template_rendered
template_rendered.connect(log_template_renders, app)
flask.before_render_template
This signal is sent before template rendering process. Thesignal is invoked with the instance of the template as template_and the context as dictionary (named _context).
Example subscriber:
def log_template_renders(sender, template, context, **extra):
sender.logger.debug('Rendering template "%s" with context %s',
template.name or 'string template',
context)
from flask import before_render_template
before_render_template.connect(log_template_renders, app)
flask.request_started
This signal is sent when the request context is set up, beforeany request processing happens. Because the request context is alreadybound, the subscriber can access the request with the standard globalproxies such as request.
Example subscriber:
def log_request(sender, **extra):
sender.logger.debug('Request context is set up')
from flask import request_started
request_started.connect(log_request, app)
flask.request_finished
This signal is sent right before the response is sent to the client.It is passed the response to be sent named response.
Example subscriber:
def log_response(sender, response, **extra):
sender.logger.debug('Request context is about to close down. '
'Response: %s', response)
from flask import request_finished
request_finished.connect(log_response, app)
flask.got_request_exception
This signal is sent when an exception happens during request processing.It is sent before the standard exception handling kicks in and evenin debug mode, where no exception handling happens. The exceptionitself is passed to the subscriber as exception.
Example subscriber:
def log_exception(sender, exception, **extra):
sender.logger.debug('Got exception during processing: %s', exception)
from flask import got_request_exception
got_request_exception.connect(log_exception, app)
flask.request_tearing_down
This signal is sent when the request is tearing down. This is alwayscalled, even if an exception is caused. Currently functions listeningto this signal are called after the regular teardown handlers, but thisis not something you can rely on.
Example subscriber:
def close_db_connection(sender, **extra):
session.close()
from flask import request_tearing_down
request_tearing_down.connect(close_db_connection, app)
As of Flask 0.9, this will also be passed an exc keyword argumentthat has a reference to the exception that caused the teardown ifthere was one.
flask.appcontext_tearing_down
This signal is sent when the app context is tearing down. This is alwayscalled, even if an exception is caused. Currently functions listeningto this signal are called after the regular teardown handlers, but thisis not something you can rely on.
Example subscriber:
def close_db_connection(sender, **extra):
session.close()
from flask import appcontext_tearing_down
appcontext_tearing_down.connect(close_db_connection, app)
This will also be passed an exc keyword argument that has a referenceto the exception that caused the teardown if there was one.
flask.appcontext_pushed
This signal is sent when an application context is pushed. The senderis the application. This is usually useful for unittests in order totemporarily hook in information. For instance it can be used toset a resource early onto the g object.
Example usage:
from contextlib import contextmanager
from flask import appcontext_pushed
@contextmanager
def user_set(app, user):
def handler(sender, **kwargs):
g.user = user
with appcontext_pushed.connected_to(handler, app):
yield
And in the testcode:
def test_user_me(self):
with user_set(app, 'john'):
c = app.test_client()
resp = c.get('/users/me')
assert resp.data == 'username=john'
Changelog
New in version 0.10.
flask.appcontext_popped
This signal is sent when an application context is popped. The senderis the application. This usually falls in line with theappcontext_tearing_down signal.
Changelog
New in version 0.10.
flask.message_flashed
This signal is sent when the application is flashing a message. Themessages is sent as message keyword argument and the category ascategory.
Example subscriber:
recorded = []
def record(sender, message, category, **extra):
recorded.append((message, category))
from flask import message_flashed
message_flashed.connect(record, app)
Changelog
New in version 0.10.
class signals.Namespace
An alias for blinker.base.Namespace if blinker is available,otherwise a dummy class that creates fake signals. This class isavailable for Flask extensions that want to provide the same fallbacksystem as Flask itself.
signal(name, doc=None)
Creates a new signal for this namespace if blinker is available,otherwise returns a fake signal that has a send method that willdo nothing but will fail with a RuntimeError for all otheroperations, including connecting.
Class-Based Views
Changelog
New in version 0.7.
class flask.views.View
Alternative way to use view functions. A subclass has to implementdispatch_request() which is called with the view arguments fromthe URL routing system. If methods is provided the methodsdo not have to be passed to the add_url_rule()method explicitly:
class MyView(View):
methods = ['GET']
def dispatch_request(self, name):
return 'Hello %s!' % name
app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))
When you want to decorate a pluggable view you will have to either do thatwhen the view function is created (by wrapping the return value ofas_view()) or you can use the decorators attribute:
The decorators stored in the decorators list are applied one after anotherwhen the view function is created. Note that you can not use the classbased decorators since those would decorate the view class and not thegenerated view function!
Converts the class into an actual view function that can be usedwith the routing system. Internally this generates a function on thefly which will instantiate the View on each request and callthe dispatch_request() method on it.
The arguments passed to as_view() are forwarded to theconstructor of the class.
decorators = ()
The canonical way to decorate class-based views is to decorate thereturn value of as_view(). However since this moves parts of thelogic from the class declaration to the place where it’s hookedinto the routing system.
You can place one or more decorators in this list and whenever theview function is created the result is automatically decorated.
Changelog
New in version 0.8.
dispatch_request()
Subclasses have to override this method to implement theactual view function code. This method is called with allthe arguments from the URL rule.
methods = None
A list of methods this view can handle.
provideautomatic_options = None_
Setting this disables or force-enables the automatic options handling.
class flask.views.MethodView
A class-based view that dispatches request methods to the correspondingclass methods. For example, if you implement a get method, it will beused to handle GET requests.
You can directly access the underlying Werkzeug routing systemwhich is exposed as flask.Flask.url_map.
Variable parts in the route can be specified with angular brackets(/user/<username>). By default a variable part in the URL accepts anystring without a slash however a different converter can be specified aswell by using <converter:name>.
Variable parts are passed to the view function as keyword arguments.
An important detail to keep in mind is how Flask deals with trailingslashes. The idea is to keep each URL unique so the following rulesapply:
If a rule ends with a slash and is requested without a slash by theuser, the user is automatically redirected to the same page with atrailing slash attached.
If a rule does not end with a trailing slash and the user requests thepage with a trailing slash, a 404 not found is raised.
This is consistent with how web servers deal with static files. Thisalso makes it possible to use relative link targets safely.
You can also define multiple rules for the same function. They have to beunique however. Defaults can also be specified. Here for example is adefinition for a URL that accepts an optional page:
This specifies that /users/ will be the URL for page one and/users/page/N will be the URL for page N.
If a URL contains a default value, it will be redirected to its simplerform with a 301 redirect. In the above example, /users/page/1 willbe redirected to /users/. If your route handles GET and POSTrequests, make sure the default route only handles GET, as redirectscan’t preserve form data.
Here are the parameters that route() andadd_url_rule() accept. The only difference is thatwith the route parameter the view function is defined with the decoratorinstead of the view_func parameter.
rule
the URL rule as string
endpoint
the endpoint for the registered URL rule. Flask itselfassumes that the name of the view function is the nameof the endpoint if not explicitly stated.
view_func
the function to call when serving a request to theprovided endpoint. If this is not provided one canspecify the function later by storing it in theview_functions dictionary with theendpoint as key.
defaults
A dictionary with defaults for this rule. See theexample above for how defaults work.
subdomain
specifies the rule for the subdomain in case subdomainmatching is in use. If not specified the defaultsubdomain is assumed.
**options
the options to be forwarded to the underlyingRule object. A change toWerkzeug is handling of method options. methods is a listof methods this rule should be limited to (GET, POSTetc.). By default a rule just listens for GET (andimplicitly HEAD). Starting with Flask 0.6, OPTIONS isimplicitly added and handled by the standard requesthandling. They have to be specified as keyword arguments.
View Function Options
For internal usage the view functions can have some attributes attached tocustomize behavior the view function would normally not have control over.The following attributes can be provided optionally to either overridesome defaults to add_url_rule() or general behavior:
name: The name of a function is by default used as endpoint. Ifendpoint is provided explicitly this value is used. Additionally thiswill be prefixed with the name of the blueprint by default whichcannot be customized from the function itself.
methods: If methods are not provided when the URL rule is added,Flask will look on the view function object itself if a _methods_attribute exists. If it does, it will pull the information for themethods from there.
provide_automatic_options: if this attribute is set Flask willeither force enable or disable the automatic implementation of theHTTP OPTIONS response. This can be useful when working withdecorators that want to customize the OPTIONS response on a per-viewbasis.
required_methods: if this attribute is set, Flask will always addthese methods when registering a URL rule even if the methods wereexplicitly overridden in the route() call.
New in version 0.8: The provide_automatic_options functionality was added.
Command Line Interface
class flask.cli.FlaskGroup(add_default_commands=True, create_app=None, add_version_option=True, load_dotenv=True, set_debug_flag=True, **extra)
Special subclass of the AppGroup group that supportsloading more commands from the configured Flask app. Normally adeveloper does not have to interface with this class but there aresome very advanced use cases for which it makes sense to create aninstance of this.
For information as of why this is useful see 自定义脚本.
Parameters
add_default_commands – if this is True then the default run andshell commands will be added.
add_version_option – adds the —version option.
create_app – an optional callback that is passed the script info andreturns the loaded app.
load_dotenv – Load the nearest .env and .flaskenvfiles to set environment variables. Will also change the workingdirectory to the directory containing the first file found.
set_debug_flag – Set the app’s debug flag based on the activeenvironment
Changelog
Changed in version 1.0: If installed, python-dotenv will be used to load environment variablesfrom .env and .flaskenv files.
getcommand(_ctx, name)
Given a context and a command name, this returns aCommand object if it exists or returns None.
listcommands(_ctx)
Returns a list of subcommand names in the order they shouldappear.
main(*args, **kwargs)
This is the way to invoke a script with all the bells andwhistles as a command line application. This will always terminatethe application after a call. If this is not wanted, SystemExitneeds to be caught.
This method is also available by directly calling the instance ofa Command.
New in version 3.0: Added the standalone_mode flag to control the standalone mode.
- Parameters
-
-
args – the arguments that should be used for parsing. If notprovided, sys.argv[1:] is used.
-
prog_name – the program name that should be used. By defaultthe program name is constructed by taking the filename from sys.argv[0].
-
complete_var – the environment variable that controls thebash completion support. The default is"_<prog_name>_COMPLETE" with prog_name inuppercase.
-
standalone_mode – the default behavior is to invoke the scriptin standalone mode. Click will thenhandle exceptions and convert them intoerror messages and the function will neverreturn but shut down the interpreter. Ifthis is set to False they will bepropagated to the caller and the returnvalue of this function is the return valueof invoke().
-
extra – extra keyword arguments are forwarded to the contextconstructor. See Context for more information.
class flask.cli.AppGroup(name=None, commands=None, **attrs)
This works similar to a regular click Group but itchanges the behavior of the command() decorator so that itautomatically wraps the functions in with_appcontext().
This works exactly like the method of the same name on a regularclick.Group but it wraps callbacks in with_appcontext()unless it’s disabled by passing with_appcontext=False.
group(*args, **kwargs)
This works exactly like the method of the same name on a regularclick.Group but it defaults the group class toAppGroup.
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 notnecessary to interface with as it’s used internally in the dispatchingto click. In future versions of Flask this object will most likely playa bigger role. Typically it’s created automatically by theFlaskGroup but you can also manually create it and pass itonwards as click object.
appimport_path = None_
Optionally the import path for the Flask application.
createapp = None_
Optionally a function that is passed the script info to createthe instance of the application.
data = None
A dictionary with arbitrary data that can be associated withthis script info.
load_app()
Loads the Flask app (if not yet loaded) and returns it. Callingthis multiple times will just result in the already loaded app tobe returned.
flask.cli.loaddotenv(_path=None)
Load “dotenv” files in order of precedence to set environment variables.
If an env var is already set it is not overwritten, so earlier files in thelist are preferred over later files.
Changes the current working directory to the location of the first filefound, with the assumption that it is in the top level project directoryand will be where the Python path should import local packages from.
path – Load the file at this location instead of searching.
Returns
True if a file was loaded.
Changed in version 1.1.0: Returns False when python-dotenv is not installed, or whenthe given path isn’t a file.
Changelog
New in version 1.0.
flask.cli.withappcontext(_f)
Wraps a callback so that it’s guaranteed to be executed with thescript’s application context. If callbacks are registered directlyto the app.cli object then they are wrapped with this functionby default unless it’s disabled.
flask.cli.passscript_info(_f)
Marks a function so that an instance of ScriptInfo is passedas first argument to the click callback.
flask.cli.runcommand = _
Run a local development server.
This server is for development purposes only. It does not providethe stability, security, or performance of production WSGI servers.
The reloader and debugger are enabled by default ifFLASK_ENV=development or FLASK_DEBUG=1.
flask.cli.shellcommand = _
Run an interactive Python shell in the context of a givenFlask application. The application will populate the defaultnamespace of this shell according to it’s configuration.
This is useful for executing small snippets of management codewithout having to manually configure the application.