API¶
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.
Application Object¶
- class
flask.
Flask
(import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None)¶
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 withaninit.py
file inside) or a standard module (just a.py
file).
For more information about resource loading, seeopen_resource()
.
Usually you create aFlask
instance in your main module orin theinit.py
file of your package like this:- from flask import Flask
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 inyourapplication/app.py
you 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: Thehostmatching
andstatic_host
parameters were added.
New in version 1.0: Thesubdomain_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 hostmatching=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.add_template_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.
addurl_rule
(_rule, endpoint=None, view_func=None, provide_automatic_options=None, **options)¶
Connects a URL rule. Works exactly like theroute()
decorator. If a viewfunc is provided it will be registered with theendpoint.
Basically this example:- @app.route('/')
def index():
pass
Is equivalent to the following:- def index():
pass
app.add_url_rule('/', 'index', index)
If the view_func is not provided you will need to connect the endpointto a view function like so:- app.view_functions['index'] = index
Internallyroute()
invokesadd_url_rule()
so if you wantto customize the behavior via subclassing you only need to changethis method.
For more information refer to URL Route Registrations.Changelog
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 viewfunc.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.- @app.route('/')
after_request
(_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 (seeprocess_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 theafter_request()
decorator.
app_context
()¶
Create anAppContext
. Use as awith
block to push the context, which will makecurrent_app
point 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.- with app.app_context():
init_db()
See 应用情境.Changelog
New in version 0.9.- with app.app_context():
app_ctx_globals_class
¶
alias offlask.ctx._AppCtxGlobals
auto_find_instance_path
()¶
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 namedinstance
next to your main file orthe package.Changelog
New in version 0.8.
before_first_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.
before_request
(_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, orNone
for allrequests. To register a function, use thebefore_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.
cli
= None¶
The click command line context for this application. Commandsregistered here show up in the flask command once theapplication has been discovered. The default commands areprovided by Flask itself and can be overridden.
This is an instance of aclick.Group
object.
config
= None¶
The configuration dictionary asConfig
. This behavesexactly like a regular dictionary but supports additional methodsto load a config from files.
config_class
¶
alias offlask.config.Config
context_processor
(_f)¶
Registers a template context processor function.
createglobal_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 overridethejinja_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
()¶
Creates the Jinja2 environment based onjinja_options
andselect_jinja_autoescape()
. Since 0.7 this also addsthe Jinja2 globals and filters after initialization. Overridethis function to customize the behavior.Changelog
Changed in version 0.11:Environment.auto_reload
set in accordance withTEMPLATES_AUTO_RELOAD
configuration option.
New in version 0.5.
create_url_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. Usesubdomainmatching
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.
debug
¶
Whether debug mode is enabled. When usingflask run
to startthe development server, an interactive debugger will be shown forunhandled exceptions, and the server will be reloaded when codechanges. This maps to theDEBUG
config key. This isenabled whenenv
is'development'
and is overriddenby theFLASK_DEBUG
environment variable. It may not behave asexpected if set in code.
Do not enable debug mode when deploying in production.
Default:True
ifenv
is'development'
, orFalse
otherwise.
default_config
= {'APPLICATIONROOT': '/', 'DEBUG': None, 'ENV': None, 'EXPLAIN_TEMPLATE_LOADING': False, 'JSONIFY_MIMETYPE': 'application/json', 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'MAX_CONTENT_LENGTH': None, 'MAX_COOKIE_SIZE': 4093, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(31), 'PREFERRED_URL_SCHEME': 'http', 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PROPAGATE_EXCEPTIONS': None, 'SECRET_KEY': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(0, 43200), 'SERVER_NAME': None, 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'TEMPLATES_AUTO_RELOAD': None, 'TESTING': False, 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'USE_X_SENDFILE': False}¶
Default configuration parameters.
dispatchrequest
()¶
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, callmake_response()
.Changelog
Changed in version 0.7: This no longer does the exception handling, this code wasmoved to the newfull_dispatch_request()
.
do_teardown_appcontext
(_exc=<object object>)¶
Called right before the application context is popped.
When handling a request, the application context is poppedafter the request context. Seedo_teardown_request()
.
This calls all functions decorated withteardown_appcontext()
. Then theappcontext_tearing_down
signal is sent.
This is called byAppContext.pop()
.Changelog
New in version 0.9.
doteardown_request
(_exc=<object object>)¶
Called after the request is dispatched and the response isreturned, right before the request context is popped.
This calls all functions decorated withteardown_request()
, andBlueprint.teardown_request()
if a blueprint handled the request. Finally, therequest_tearing_down
signal is sent.
This is called byRequestContext.pop()
,which may be delayed during testing to maintain access toresources.
|Parameters:
|——-
|exc – An unhandled exception raised while dispatching therequest. Detected from the current exception information ifnot passed. Passed to each teardown function.Changelog
Changed in version 0.9: Added theexc
argument.
endpoint
(endpoint)¶
A decorator to register a function as an endpoint.Example:- @app.endpoint('example.endpoint')
def example():
return "example"
|Parameters:
|——-
|endpoint – the name of the endpoint- @app.endpoint('example.endpoint')
env
¶
What environment the app is running in. Flask and extensions mayenable behaviors based on the environment, such as enabling debugmode. This maps to theENV
config key. This is set by theFLASKENV
environment variable and may not behave asexpected if set in code.
Do not enable development when deploying in production.
Default:'production'
error_handler_spec
= None¶
A dictionary of all registered error handlers. The key isNone
for error handlers active on the application, otherwise the key isthe name of the blueprint. Each key points to another dictionarywhere the key is the status code of the http exception. Thespecial keyNone
points to a list of tuples where the first itemis the class for the instance check and the second the error handlerfunction.
To register an error handler, use theerrorhandler()
decorator.
errorhandler
(_code_or_exception)¶
Register a function to handle errors by code or exception class.
A decorator that is used to register a function given anerror code. Example:- @app.errorhandler(404)
def pagenot_found(error):
return 'This page does not exist', 404
You can also register handlers for arbitrary exceptions:- @app.errorhandler(DatabaseError)
def special_exception_handler(error):
return 'Database connection failed', 500
Changelog
New in version 0.7: Useregister_error_handler()
instead of modifyingerror_handler_spec
directly, for application wide errorhandlers.
New in version 0.7: One can now additionally also register custom exception typesthat do not necessarily have to be a subclass of theHTTPException
class.
|Parameters:
|——-
|code_or_exception – the code as integer for the handler, oran arbitrary exception- @app.errorhandler(404)
extensions
= None¶
a place where extensions can store application specific state. Forexample this is where an extension could store database engines andsimilar things. For backwards compatibility extensions should registerthemselves like this:- if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['extensionname'] = SomeObject()
The key must match the name of the extension module. For example incase of a “Flask-Foo” extension in _flask_foo, the key would be'foo'
.Changelog
New in version 0.7.- if not hasattr(app, 'extensions'):
fulldispatch_request
()¶
Dispatches the request and on top of that performs requestpre and postprocessing as well as HTTP exception catching anderror handling.Changelog
New in version 0.7.
get_send_file_max_age
(_filename)¶
Provides default cachetimeout for thesend_file()
functions.
By default, this function returnsSEND_FILE_MAX_AGE_DEFAULT
fromthe configuration ofcurrent_app
.
Static file functions such assend_from_directory()
use thisfunction, andsend_file()
calls this function oncurrent_app
when the given cache_timeout isNone
. If acache_timeout is given insend_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.- class MyFlask(flask.Flask):
got_first_request
¶
This attribute is set toTrue
if the application startedhandling the first request.Changelog
New in version 0.8.
handle_exception
(_e)¶
Default exception handling that kicks in when an exceptionoccurs that is not caught. In debug mode the exception willbe re-raised immediately, otherwise it is logged and the handlerfor a 500 internal server error is used. If no such handlerexists, a default 500 internal server error message is displayed.Changelog
New in version 0.3.
handlehttp_exception
(_e)¶
Handles an HTTP exception. By default this will invoke theregistered error handlers and fall back to returning theexception as response.Changelog
New in version 0.3.
handleuser_exception
(_e)¶
This method is called whenever an exception occurs that should behandled. A special case areHTTPException
s which are forwarded bythis function to thehandle_http_exception()
method. Thisfunction will either return a response value or reraise theexception with the same traceback.Changelog
Changed in version 1.0: Key errors raised from request data likeform
show the the badkey in debug mode rather than a generic bad request message.
New in version 0.7.
hasstatic_folder
¶
This isTrue
if the package bound object’s container has afolder for static files.Changelog
New in version 0.5.
import_name
= None¶
The name of the package or module that this app belongs to. Do notchange this once it is set by the constructor.
inject_url_defaults
(_endpoint, values)¶
Injects the URL defaults for the given endpoint directly intothe values dictionary passed. This is used internally andautomatically called on URL building.Changelog
New in version 0.7.
instancepath
= None¶
Holds the path to the instance folder.Changelog
New in version 0.8.
iter_blueprints
()¶
Iterates over all blueprints by the order they were registered.Changelog
New in version 0.11.
jinja_env
¶
The Jinja2 environment used to load templates.
jinja_environment
¶
alias offlask.templating.Environment
jinja_loader
¶
The Jinja loader for this package bound object.Changelog
New in version 0.5.
jinja_options
= {'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with']}¶
Options that are passed directly to the Jinja2 environment.
jsondecoder
¶
alias offlask.json.JSONDecoder
json_encoder
¶
alias offlask.json.JSONEncoder
log_exception
(_exc_info)¶
Logs an exception. This is called byhandle_exception()
if debugging is disabled and right before the handler is called.The default implementation logs the exception as error on thelogger
.Changelog
New in version 0.8.
logger
¶
The'flask.app'
logger, a standard PythonLogger
.
In debug mode, the logger’slevel
will be settoDEBUG
.
If there are no handlers configured, a default handler will be added.See 日志 for more information.Changelog
Changed in version 1.0: Behavior was simplified. The logger is always namedflask.app
. The level is only set during configuration, itdoesn’t checkapp.debug
each time. Only one format is used,not different ones depending onapp.debug
. No handlers areremoved, and a handler is only added if no handlers are alreadyconfigured.
New in version 0.3.
makeconfig
(_instance_relative=False)¶
Used to create the config attribute by the Flask constructor.The instance_relative parameter is passed in from the constructorof Flask (there named instance_relative_config) and indicates ifthe config should be relative to the instance path or the root pathof the application.Changelog
New in version 0.8.
makedefault_options_response
()¶
This method is called to create the defaultOPTIONS
response.This can be changed through subclassing to change the defaultbehavior ofOPTIONS
responses.Changelog
New in version 0.7.
make_null_session
()¶
Creates a new instance of a missing session. Instead of overridingthis method we recommend replacing thesession_interface
.Changelog
New in version 0.7.
make_response
(_rv)¶
Convert the return value from a view function to an instance ofresponse_class
.
|Parameters:
|——-
|rv –
the return value from the view function. The view functionmust return a response. ReturningNone
, or the view endingwithout returning, is not allowed. The following types are allowedforview_rv
:str
(unicode
in Python 2)- A response object is created with the string encoded to UTF-8as the body.
bytes
(str
in Python 2)- A response object is created with the bytes as the body.
tuple
- Either
(body, status, headers)
,(body, status)
, or(body, headers)
, wherebody
is any of the other typesallowed here,status
is a string or an integer, andheaders
is a dictionary or a list of(key, value)
tuples. Ifbody
is aresponse_class
instance,status
overwrites the exiting value andheaders
areextended. response_class
- The object is returned unchanged.
- other
Response
class - The object is coerced to
response_class
. callable()
- The function is called as a WSGI application. The result isused to create a response object.
Changelog
Changed in version 0.9: Previously a tuple was interpreted as the arguments for theresponse object.
makeshell_context
()¶
Returns the shell context for an interactive shell for thisapplication. This runs all the registered shell contextprocessors.Changelog
New in version 0.11.
name
¶
The name of the application. This is usually the import namewith the difference that it’s guessed from the run file if theimport name is main. This name is used as a display name whenFlask needs the name of the application. It can be set and overriddento change the value.Changelog
New in version 0.8.
open_instance_resource
(_resource, mode='rb')¶
Opens a resource from the application’s instance folder(instance_path
). Otherwise works likeopen_resource()
. Instance resources can also be opened forwriting.
|Parameters:
|——-
|
- resource – the name of the resource. To access resources withinsubfolders use forward slashes as separator.
- mode – resource file opening mode, default is ‘rb’.
openresource
(_resource, mode='rb')¶
Opens a resource from the application’s resource folder. To seehow this works, consider the following folder structure:- /myapplication.py
/schema.sql
/static
/style.css
/templates
/layout.html
/index.html
If you want to open theschema.sql
file you would do thefollowing:- with app.openresource('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 – resource file opening mode, default is ‘rb’.- /myapplication.py
open_session
(_request)¶
Creates or opens a new session. Default implementation stores allsession data in a signed cookie. This requires that thesecret_key
is set. Instead of overriding this methodwe recommend replacing thesession_interface
.
|Parameters:
|——-
|request – an instance ofrequest_class
.
permanentsession_lifetime
¶
Atimedelta
which is used to set the expirationdate of a permanent session. The default is 31 days which makes apermanent session survive for roughly one month.
This attribute can also be configured from the config with thePERMANENT_SESSION_LIFETIME
configuration key. Defaults totimedelta(days=31)
preprocess_request
()¶
Called before the request is dispatched. Callsurl_value_preprocessors
registered with the app and thecurrent blueprint (if any). Then callsbefore_request_funcs
registered with the app and the blueprint.
If anybefore_request()
handler returns a non-None value, thevalue is handled as if it was the return value from the view, andfurther request handling is stopped.
preserve_context_on_exception
¶
Returns the value of thePRESERVE_CONTEXT_ON_EXCEPTION
configuration value in case it’s set, otherwise a sensible defaultis returned.Changelog
New in version 0.7.
process_response
(_response)¶
Can be overridden in order to modify the response objectbefore it’s sent to the WSGI server. By default this willcall all theafter_request()
decorated functions.Changelog
Changed in version 0.5: As of Flask 0.5 the functions registered for after requestexecution are called in reverse order of registration.
|Parameters:
|——-
|response – aresponse_class
object.
|Returns:
|——-
|a new response object or the same, has to be aninstance ofresponse_class
.
propagateexceptions
¶
Returns the value of thePROPAGATE_EXCEPTIONS
configurationvalue in case it’s set, otherwise a sensible default is returned.Changelog
New in version 0.7.
register_blueprint
(_blueprint, **options)¶
Register aBlueprint
on the application. Keywordarguments passed to this method will override the defaults set on theblueprint.
Calls the blueprint’sregister()
method afterrecording the blueprint in the application’sblueprints
.
|Parameters:
|——-
|
- blueprint – The blueprint to register.
- url_prefix – Blueprint routes will be prefixed with this.
- subdomain – Blueprint routes will match on this subdomain.
- url_defaults – Blueprint routes will use these default values forview arguments.
- options – Additional keyword arguments are passed toBlueprintSetupState. They can beaccessed in record() callbacks.Changelog
New in version 0.7.
registererror_handler
(_code_or_exception, f)¶
Alternative error attach function to theerrorhandler()
decorator that is more straightforward to use for non decoratorusage.Changelog
New in version 0.7.
requestclass
¶
alias offlask.wrappers.Request
request_context
(_environ)¶
Create aRequestContext
representing aWSGI environment. Use awith
block to push the context,which will makerequest
point at this request.
See 请求情境.
Typically you should not call this from your own code. A requestcontext is automatically pushed by thewsgi_app()
whenhandling a request. Usetest_request_context()
to createan environment and context instead of this method.
|Parameters:
|——-
|environ – a WSGI environment
responseclass
¶
alias offlask.wrappers.Response
root_path
= None¶
Absolute path to the package on the filesystem. Used to look upresources contained in the package.
route
(_rule, **options)¶
A decorator that is used to register a view function for agiven URL rule. This does the same thing asadd_url_rule()
but is intended for decorator usage:- @app.route('/')
def index():
return 'Hello World'
For more information refer to URL Route Registrations.
|Parameters:
|——-
|
- rule – the URL rule as string
- endpoint – the endpoint for the registered URL rule. Flaskitself assumes the name of the view function asendpoint
- 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.- @app.route('/')
run
(host=None, port=None, debug=None, load_dotenv=True, **options)¶
Runs the application on a local development server.
Do not userun()
in a production setting. It is not intended tomeet security and performance requirements for a production server.Instead, see 部署方式 for WSGI server recommendations.
If thedebug
flag is set the server will automatically reloadfor code changes and show a debugger in case an exception happened.
If you want to run the application in debug mode, but disable thecode execution on the interactive debugger, you can passuseevalex=False
as parameter. This will keep the debugger’straceback screen active, but disable code execution.
It is not recommended to use this function for development withautomatic reloading as this is badly supported. Instead you shouldbe using the flask command line script’srun
support.
Keep in Mind
Flask will suppress any server error with a generic error pageunless it is in debug mode. As such to enable just theinteractive debugger without the code reloading, you have toinvokerun()
withdebug=True
anduse_reloader=False
.Settinguse_debugger
toTrue
without being in debug modewon’t catch any exceptions because there won’t be any tocatch.
|Parameters:
|——-
|
- host – the hostname to listen on. Set this to '0.0.0.0' tohave the server available externally as well. Defaults to'127.0.0.1' or the host in the SERVER_NAME config variableif present.
- port – the port of the webserver. Defaults to 5000 or theport defined in the SERVER_NAME config variable if present.
- debug – if given, enable or disable debug mode. Seedebug.
- 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.
- options – the options to be forwarded to the underlying Werkzeugserver. See werkzeug.serving.run_simple() for moreinformation.Changelog
Changed in version 1.0: If installed, python-dotenv will be used to load environmentvariables from.env
and.flaskenv
files.
If set, theFLASK_ENV
andFLASK_DEBUG
environment variables will overrideenv
anddebug
.
Threaded mode is enabled by default.
Changed in version 0.10: The default port is now picked from theSERVER_NAME
variable.
save_session
(_session, response)¶
Saves the session if it needs updates. For the defaultimplementation, checkopen_session()
. Instead of overriding thismethod we recommend replacing thesession_interface
.
|Parameters:
|——-
|
- session – the session to be saved (aSecureCookieobject)
- response – an instance of response_class
secretkey
¶
If a secret key is set, cryptographic components can use this tosign cookies and other things. Set this to a complex random valuewhen you want to use the secure cookie for instance.
This attribute can also be configured from the config with theSECRET_KEY
configuration key. Defaults toNone
.
select_jinja_autoescape
(_filename)¶
ReturnsTrue
if autoescaping should be active for the giventemplate name. If no template name is given, returns True.Changelog
New in version 0.5.
sendfile_max_age_default
¶
Atimedelta
which is used as default cache_timeoutfor thesend_file()
functions. The default is 12 hours.
This attribute can also be configured from the config with theSEND_FILE_MAX_AGE_DEFAULT
configuration key. This configurationvariable can also be set with an integer value used as seconds.Defaults totimedelta(hours=12)
send_static_file
(_filename)¶
Function used internally to send static files from the staticfolder to the browser.Changelog
New in version 0.5.
The secure cookie uses this for the name of the session cookie.
This attribute can also be configured from the config with theSESSION_COOKIE_NAME
configuration key. Defaults to'session'
session_interface
= <flask.sessions.SecureCookieSessionInterface object>¶
the session interface to use. By default an instance ofSecureCookieSessionInterface
is used here.Changelog
New in version 0.8.
shell_context_processor
(_f)¶
Registers a shell context processor function.Changelog
New in version 0.11.
shellcontext_processors
= None¶
A list of shell context processor functions that should be runwhen a shell context is created.Changelog
New in version 0.11.
should_ignore_error
(_error)¶
This is called to figure out if an error should be ignoredor not as far as the teardown system is concerned. If thisfunction returnsTrue
then the teardown handlers will not bepassed the error.Changelog
New in version 0.10.
staticfolder
¶
The absolute path to the configured static folder.
static_url_path
¶
The URL prefix that the static route will be registered for.
teardown_appcontext
(_f)¶
Registers a function to be called when the application contextends. These functions are typically also called when the requestcontext is popped.
Example:- ctx = app.appcontext()
ctx.push()
…
ctx.pop()
Whenctx.pop()
is executed in the above example, the teardownfunctions are called just before the app context moves from thestack of active contexts. This becomes relevant if you are usingsuch constructs in tests.
Since a request context typically also manages an applicationcontext it would also be called when you pop a request context.
When a teardown function was called because of an unhandled exceptionit will be passed an error object. If anerrorhandler()
isregistered, it will handle the exception and the teardown will notreceive it.
The return values of teardown functions are ignored.Changelog
New in version 0.9.- ctx = app.appcontext()
teardown_appcontext_funcs
= None¶
A list of functions that are called when the application contextis destroyed. Since the application context is also torn downif the request ends this is the place to store code that disconnectsfrom databases.Changelog
New in version 0.9.
teardown_request
(_f)¶
Register a function to be run at the end of each request,regardless of whether there was an exception or not. These functionsare executed when the request context is popped, even if not anactual request was performed.
Example:- ctx = app.testrequest_context()
ctx.push()
…
ctx.pop()
Whenctx.pop()
is executed in the above example, the teardownfunctions are called just before the request context moves from thestack of active contexts. This becomes relevant if you are usingsuch constructs in tests.
Generally teardown functions must take every necessary step to avoidthat they will fail. If they do execute code that might fail theywill have to surround the execution of these code by try/exceptstatements and log occurring errors.
When a teardown function was called because of an exception it willbe passed an error object.
The return values of teardown functions are ignored.
Debug Note
In debug mode Flask will not tear down a request on an exceptionimmediately. Instead it will keep it alive so that the interactivedebugger can still access it. This behavior can be controlledby thePRESERVE_CONTEXT_ON_EXCEPTION
configuration variable.- ctx = app.testrequest_context()
teardown_request_funcs
= None¶
A dictionary with lists of functions that are called aftereach request, even if an exception has occurred. The key of thedictionary is the name of the blueprint this function is active for,None
for all requests. These functions are not allowed to modifythe request, and their return values are ignored. If an exceptionoccurred while processing the request, it gets passed to eachteardown_request function. To register a function here, use theteardown_request()
decorator.Changelog
New in version 0.7.
template_context_processors
= None¶
A dictionary with list of functions that are called without argumentto populate the template context. The key of the dictionary is thename of the blueprint this function is active for,None
for allrequests. Each returns a dictionary that the template context isupdated with. To register a function here, use thecontext_processor()
decorator.
template_filter
(_name=None)¶
A decorator that is used to register custom template filter.You can specify a name for the filter, otherwise the functionname will be used. Example:- @app.templatefilter()
def reverse(s):
return s[::-1]
|Parameters:
|——-
|name – the optional name of the filter, otherwise thefunction name will be used.- @app.templatefilter()
template_folder
= None¶
Location of the template files to be added to the template lookup.None
if templates should not be added.
template_global
(_name=None)¶
A decorator that is used to register a custom template global function.You can specify a name for the global function, otherwise the functionname will be used. Example:- @app.templateglobal()
def double(n):
return 2 n
Changelog
New in version 0.10.
|Parameters:
|——-
|*name – the optional name of the global function, otherwise thefunction name will be used.- @app.templateglobal()
template_test
(_name=None)¶
A decorator that is used to register custom template test.You can specify a name for the test, otherwise the functionname will be used. Example:- @app.templatetest()
def is_prime(n):
if n == 2:
return True
for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
if n % i == 0:
return False
return True
Changelog
New in version 0.10.
|Parameters:
|——-
|name – the optional name of the test, otherwise thefunction name will be used.- @app.templatetest()
templates_auto_reload
¶
Reload templates when they are changed. Used bycreate_jinja_environment()
.
This attribute can be configured withTEMPLATES_AUTO_RELOAD
. Ifnot set, it will be enabled in debug mode.Changelog
New in version 1.0: This property was added but the underlying config and behavioralready existed.
test_cli_runner
(kwargs)¶
Create a CLI runner for testing CLI commands.See 测试 CLI 命令.
Returns an instance oftest_cli_runner_class
, by defaultFlaskCliRunner
. The Flask app object ispassed as the first argument.Changelog
New in version 1.0.
test_cli_runner_class
= None¶
TheCliRunner
subclass, by defaultFlaskCliRunner
that is used bytest_cli_runner()
. Itsinit
method should take aFlask app object as the first argument.Changelog
New in version 1.0.
test_client
(_use_cookies=True, _kwargs)¶
Creates a test client for this application. For informationabout unit testing head over to 测试 Flask 应用.
Note that if you are testing for assertions or exceptions in yourapplication code, you must setapp.testing = True
in order for theexceptions to propagate to the test client. Otherwise, the exceptionwill be handled by the application (not visible to the test client) andthe only indication of an AssertionError or other exception will be a500 status code response to the test client. See thetesting
attribute. For example:- app.testing = True
client = app.testclient()
The test client can be used in awith
block to defer the closing downof the context until the end of thewith
block. This is useful ifyou want to access the context locals for testing:- with app.testclient() as c:
rv = c.get('/?vodka=42')
assert request.args['vodka'] == '42'
Additionally, you may pass optional keyword arguments that will thenbe passed to the application’stest_client_class
constructor.For example:- from flask.testing import FlaskClient
class CustomClient(FlaskClient):
def init(self, args, *kwargs):
self._authentication = kwargs.pop("authentication")
super(CustomClient,self).__init( args, *kwargs)
app.test_client_class = CustomClient
client = app.test_client(authentication='Basic ….')
SeeFlaskClient
for more information.Changelog
Changed in version 0.11: Added kwargs to support passing additional keyword arguments tothe constructor oftest_client_class
.
New in version 0.7: The _use_cookies parameter was added as well as the abilityto override the client to be used by setting thetest_client_class
attribute.
Changed in version 0.4: added support forwith
block usage for the client.- app.testing = True
testclient_class
= None¶
the test client that is used with when _test_client is used.Changelog
New in version 0.7.
testrequest_context
(*args, kwargs)¶
Create aRequestContext
for a WSGIenvironment created from the given values. This is mostly usefulduring testing, where you may want to run a function that usesrequest data without dispatching a full request.
See 请求情境.
Use awith
block to push the context, which will makerequest
point at the request for the createdenvironment.- with test_request_context(…):
generate_report()
When using the shell, it may be easier to push and pop thecontext manually to avoid indentation.- ctx = app.test_request_context(…)
ctx.push()
…
ctx.pop()
Takes the same arguments as Werkzeug’sEnvironBuilder
, with some defaults fromthe application. See the linked Werkzeug docs for most of theavailable arguments. Flask-specific behavior is listed here.
|Parameters:
|——-
|
- path – URL path being requested.
- base_url – Base URL where the app is being served, whichpath is relative to. If not given, built fromPREFERRED_URL_SCHEME, subdomain,SERVER_NAME, and APPLICATION_ROOT.
- subdomain – Subdomain name to append toSERVER_NAME.
- url_scheme – Scheme to use instead ofPREFERRED_URL_SCHEME.
- data – The request body, either as a string or a dict ofform keys and values.
- json – If given, this is serialized as JSON and passed asdata. Also defaults content_type toapplication/json.
- args – other positional arguments passed toEnvironBuilder.
- kwargs – other keyword arguments passed toEnvironBuilder.- with test_request_context(…):
testing
¶
The testing flag. Set this toTrue
to enable the test mode ofFlask extensions (and in the future probably also Flask itself).For example this might activate test helpers that have anadditional runtime cost which should not be enabled by default.
If this is enabled and PROPAGATE_EXCEPTIONS is not changed from thedefault it’s implicitly enabled.
This attribute can also be configured from the config with theTESTING
configuration key. Defaults toFalse
.
trap_http_exception
(_e)¶
Checks if an HTTP exception should be trapped or not. By defaultthis will returnFalse
for all exceptions except for a bad requestkey error ifTRAPBAD_REQUEST_ERRORS
is set toTrue
. Italso returnsTrue
ifTRAP_HTTP_EXCEPTIONS
is set toTrue
.
This is called for all HTTP exceptions raised by a view function.If it returnsTrue
for any exception the error handler for thisexception is not called and it shows up as regular exception in thetraceback. This is helpful for debugging implicitly raised HTTPexceptions.Changelog
Changed in version 1.0: Bad request errors are not trapped by default in debug mode.
New in version 0.8.
update_template_context
(_context)¶
Update the template context with some commonly used variables.This injects request, session, config and g into the templatecontext as well as everything template context processors wantto inject. Note that the as of Flask 0.6, the original valuesin the context will not be overridden if a context processordecides to return a value with the same key.
|Parameters:
|——-
|context – the context as a dictionary that is updated in placeto add extra variables.
urlbuild_error_handlers
= None¶
A list of functions that are called whenurl_for()
raises aBuildError
. Each function registered hereis called with _error, endpoint and values. If a functionreturnsNone
or raises aBuildError
the next function istried.Changelog
New in version 0.9.
urldefault_functions
= None¶
A dictionary with lists of functions that can be used as URL valuepreprocessors. The keyNone
here is used for application widecallbacks, otherwise the key is the name of the blueprint.Each of these functions has the chance to modify the dictionaryof URL values before they are used as the keyword arguments of theview function. For each function registered this one should alsoprovide aurl_defaults()
function that adds the parametersautomatically again that were removed that way.Changelog
New in version 0.7.
url_defaults
(_f)¶
Callback function for URL defaults for all view functions of theapplication. It’s called with the endpoint and values and shouldupdate the values passed in place.
urlmap
= None¶
TheMap
for this instance. You can usethis to change the routing converters after the class was createdbut before any routes are connected. Example:- from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter):
def topython(self, value):
return value.split(',')
def tourl(self, values):
return ','.join(super(ListConverter, self).to_url(value)
for value in values)
app = Flask(__name)
app.url_map.converters['list'] = ListConverter
- from werkzeug.routing import BaseConverter
url_rule_class
¶
alias ofwerkzeug.routing.Rule
url_value_preprocessor
(_f)¶
Register a URL value preprocessor function for all viewfunctions in the application. These functions will be called before thebefore_request()
functions.
The function can modify the values captured from the matched url beforethey are passed to the view. For example, this can be used to pop acommon language code value and place it ing
rather than pass it toevery view.
The function is passed the endpoint name and values dict. The returnvalue is ignored.
urlvalue_preprocessors
= None¶
A dictionary with lists of functions that are called before thebefore_request_funcs
functions. The key of the dictionary isthe name of the blueprint this function is active for, orNone
for all requests. To register a function, useurl_value_preprocessor()
.Changelog
New in version 0.7.
use_x_sendfile
¶
Enable this if you want to use the X-Sendfile feature. Keep inmind that the server has to support this. This only affects filessent with thesend_file()
method.Changelog
New in version 0.2.
This attribute can also be configured from the config with theUSE_X_SENDFILE
configuration key. Defaults toFalse
.
view_functions
= None¶
A dictionary of all view functions registered. The keys willbe function names which are also used to generate URLs andthe values are the function objects themselves.To register a view function, use theroute()
decorator.
wsgi_app
(_environ, start_response)¶
The actual WSGI application. This is not implemented incall()
so that middlewares can be applied withoutlosing a reference to the app object. Instead of doing this:- app = MyMiddleware(app)
It’s a better idea to do this instead:- app.wsgiapp = MyMiddleware(app.wsgi_app)
Then you still have the original application object around andcan continue to call methods on it.Changelog
Changed in version 0.7: Teardown events for the request and app contexts are calledeven if an unhandled error occurs. Other events may not becalled depending on when an error occurs during dispatch.See 回调和错误.
|Parameters:
|——-
|
- environ – A WSGI environment.
- start_response – A callable accepting a status code,a list of headers, and an optional exception context tostart the response.- app = MyMiddleware(app)
- from flask import Flask
## Blueprint Objects¶
- _class
flask.
Blueprint
(name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None)¶
Represents a blueprint. A blueprint is an object that recordsfunctions that will be called with theBlueprintSetupState
later to register functionsor other things on the main application. See 使用蓝图的模块化应用 for moreinformation.Changelog
New in version 0.7.addapp_template_filter
(_f, name=None)¶
Register a custom template filter, available application wide. LikeFlask.add_template_filter()
but for a blueprint. Works exactlylike theapp_template_filter()
decorator.
|Parameters:
|——-
|name – the optional name of the filter, otherwise thefunction name will be used.
addapp_template_global
(_f, name=None)¶
Register a custom template global, available application wide. LikeFlask.add_template_global()
but for a blueprint. Works exactlylike theapp_template_global()
decorator.Changelog
New in version 0.10.
|Parameters:
|——-
|name – the optional name of the global, otherwise thefunction name will be used.
addapp_template_test
(_f, name=None)¶
Register a custom template test, available application wide. LikeFlask.add_template_test()
but for a blueprint. Works exactlylike theapp_template_test()
decorator.Changelog
New in version 0.10.
|Parameters:
|——-
|name – the optional name of the test, otherwise thefunction name will be used.
addurl_rule
(_rule, endpoint=None, view_func=None, **options)¶
LikeFlask.add_url_rule()
but for a blueprint. The endpoint fortheurl_for()
function is prefixed with the name of the blueprint.
afterapp_request
(_f)¶
LikeFlask.after_request()
but for a blueprint. Such a functionis executed after each request, even if outside of the blueprint.
afterrequest
(_f)¶
LikeFlask.after_request()
but for a blueprint. This functionis only executed after each request that is handled by a function ofthat blueprint.
appcontext_processor
(_f)¶
LikeFlask.context_processor()
but for a blueprint. Such afunction is executed each request, even if outside of the blueprint.
apperrorhandler
(_code)¶
LikeFlask.errorhandler()
but for a blueprint. Thishandler is used for all requests, even if outside of the blueprint.
apptemplate_filter
(_name=None)¶
Register a custom template filter, available application wide. LikeFlask.template_filter()
but for a blueprint.
|Parameters:
|——-
|name – the optional name of the filter, otherwise thefunction name will be used.
apptemplate_global
(_name=None)¶
Register a custom template global, available application wide. LikeFlask.template_global()
but for a blueprint.Changelog
New in version 0.10.
|Parameters:
|——-
|name – the optional name of the global, otherwise thefunction name will be used.
apptemplate_test
(_name=None)¶
Register a custom template test, available application wide. LikeFlask.template_test()
but for a blueprint.Changelog
New in version 0.10.
|Parameters:
|——-
|name – the optional name of the test, otherwise thefunction name will be used.
appurl_defaults
(_f)¶
Same asurl_defaults()
but application wide.
appurl_value_preprocessor
(_f)¶
Same asurl_value_preprocessor()
but application wide.
beforeapp_first_request
(_f)¶
LikeFlask.before_first_request()
. Such a function isexecuted before the first request to the application.
beforeapp_request
(_f)¶
LikeFlask.before_request()
. Such a function is executedbefore each request, even if outside of a blueprint.
beforerequest
(_f)¶
LikeFlask.before_request()
but for a blueprint. This functionis only executed before each request that is handled by a function ofthat blueprint.
contextprocessor
(_f)¶
LikeFlask.context_processor()
but for a blueprint. Thisfunction is only executed for requests handled by a blueprint.
endpoint
(endpoint)¶
LikeFlask.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.
Otherwise works as theerrorhandler()
decoratorof theFlask
object.
getsend_file_max_age
(_filename)¶
Provides default cachetimeout for thesend_file()
functions.
By default, this function returnsSEND_FILE_MAX_AGE_DEFAULT
fromthe configuration ofcurrent_app
.
Static file functions such assend_from_directory()
use thisfunction, andsend_file()
calls this function oncurrent_app
when the given cache_timeout isNone
. If acache_timeout is given insend_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.- class MyFlask(flask.Flask):
has_static_folder
¶
This isTrue
if the package bound object’s container has afolder for static files.Changelog
New in version 0.5.
import_name
= 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.
json_decoder
= None¶
Blueprint local JSON decoder class to use.Set toNone
to use the app’sjson_decoder
.
json_encoder
= None¶
Blueprint local JSON decoder class to use.Set toNone
to use the app’sjson_encoder
.
make_setup_state
(_app, options, first_registration=False)¶
Creates an instance ofBlueprintSetupState()
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:- /myapplication.py
/schema.sql
/static
/style.css
/templates
/layout.html
/index.html
If you want to open theschema.sql
file you would do thefollowing:- with app.openresource('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 – resource file opening mode, default is ‘rb’.- /myapplication.py
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 themake_setup_state()
method.
recordonce
(_func)¶
Works likerecord()
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.
register
(app, options, first_registration=False)¶
Called byFlask.register_blueprint()
to register all viewsand callbacks registered on the blueprint with the application. CreatesaBlueprintSetupState
and calls eachrecord()
callbackwith it.
|Parameters:
|——-
|
- app – The application this blueprint is being registered with.
- options – Keyword arguments forwarded fromregister_blueprint().
- 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 theerrorhandler()
error attachfunction, akin to theregister_error_handler()
application-wide function of theFlask
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)¶
LikeFlask.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.
staticfolder
¶
The absolute path to the configured static folder.
static_url_path
¶
The URL prefix that the static route will be registered for.
teardown_app_request
(_f)¶
LikeFlask.teardown_request()
but for a blueprint. Such afunction is executed when tearing down each request, even if outside ofthe blueprint.
teardownrequest
(_f)¶
LikeFlask.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.
url_defaults
(_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 asrequest
. If you want to replacethe request object used you can subclass this and setrequest_class
to your subclass.
The request object is aRequest
subclass andprovides all of the attributes Werkzeug defines plus a few Flaskspecific ones.environ
¶
The underlying WSGI environment.
path
¶
fullpath
¶
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:
And a user requests the following URI:
In this case the values of the above mentioned attributes would bethe following:
|_path|u'/π/page.html'
|full_path|u'/π/page.html?x=y'
|script_root|u'/myapplication'
|base_url|u'http://www.example.com/myapplication/π/page.html'
|url|u'http://www.example.com/myapplication/π/page.html?x=y'
|url_root|u'http://www.example.com/myapplication/'
acceptcharsets
¶
List of charsets this client supports asCharsetAccept
object.
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
.
accept_languages
¶
List of languages this client accepts asLanguageAccept
object.
accept_mimetypes
¶
List of mimetypes this client supports asMIMEAccept
object.
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 as firstargument. This works like theresponder()
decorator but thefunction is passed the request object as first argument and therequest object will be closed automatically:- @Request.application
def mywsgi_app(request):
return Response('Hello World!')
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- @Request.application
args
¶
The parsed URL parameters (the part in the URL after the questionmark).
By default anImmutableMultiDict
is 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.
The _Authorization object in parsed form.
baseurl
Likeurl
but without the querystringSee also:trusted_hosts
.
blueprint
¶
The name of the current blueprint
cache_control
¶
ARequestCacheControl
objectfor the incoming cache control headers.
close
()¶
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 a modifier to themedia-type. When present, its value indicates what additional contentcodings have been applied to the entity-body, and thus what decodingmechanisms must be applied in order to obtain the media-typereferenced by the Content-Type header field.Changelog
New in version 0.9.
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 in RFC 1864, is anMD5 digest of the entity-body for the purpose of providing anend-to-end message integrity check (MIC) of the entity-body. (Note:a MIC is good for detecting accidental modification of theentity-body in transit, but is not proof against malicious attacks.)
Changelog
New in version 0.9.
content_type
¶
The Content-Type entity-header field indicates the media type ofthe entity-body sent to the recipient or, in the case of the HEADmethod, the media type that would have been sent had the requestbeen a GET.
Adict
with the contents of all cookies transmitted withthe request.
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 and time at whichthe message was originated, having the same semantics as orig-datein RFC 822.
dict_storage_class
¶
alias ofwerkzeug.datastructures.ImmutableTypeConversionDict
endpoint
¶
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 willbeNone
.
files
¶MultiDict
object containingall uploaded files. Each key infiles
is the name from the<input type="file" name="">
. Each value infiles
is aWerkzeugFileStorage
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 thatfiles
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 theMultiDict
/FileStorage
documentation formore details about the used data structure.
form
¶
The form parameters. By default anImmutableMultiDict
is 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 thefiles
attribute.Changelog
Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POSTand PUT requests.
form_data_parser_class
¶
alias ofwerkzeug.formparser.FormDataParser
- _classmethod
fromvalues
(args, kwargs)¶
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.
This accepts the same options as theEnvironBuilder
.Changelog
Changed in version 0.5: This method now accepts the same arguments asEnvironBuilder
. Because of this the_environ parameter is now called environ_overrides.
|Returns:
|——-
|request object
fullpath
Requested path as unicode, including the query string.
get_data
(_cache=True, as_text=False, parse_form_data=False)¶
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.Changelog
New in version 0.9.
getjson
(_force=False, silent=False, cache=True)¶
Parse and return the data as JSON. If the mimetype does notindicate JSON (application/json, seeis_json()
), this returnsNone
unlessforce
istrue. If parsing fails,on_json_loading_failed()
is calledand its return value is used as the return value.
|Parameters:
|——-
|
- force – Ignore the mimetype and always try to parse JSON.
- silent – Silence parsing errors and return Noneinstead.
- cache** – Store the parsed JSON to return for subsequentcalls.
headers
¶
The headers from the WSGI environ as immutableEnvironHeaders
.
host
¶
Just the host including the port if available.See also:trustedhosts
.
host_url
¶
Just the host with scheme as IRI.See also:trusted_hosts
.
ifmodified_since
¶
The parsed _If-Modified-Since header as datetime object.
ifnone_match
¶
An object containing all the etags in the _If-None-Match header.
|Return type:
|——-
|ETags
ifunmodified_since
¶
The parsed _If-Unmodified-Since header as datetime object.
isjson
¶
Check if the mimetype indicates JSON data, either_application/json or _application/+json.Changelog
New in version 0.11.
is_multiprocess
¶
boolean that is _True if the application is served bya WSGI server that spawns multiple processes.
ismultithread
¶
boolean that is _True if the application is served bya multithreaded WSGI server.
isrun_once
¶
boolean that is _True if the application will be executed onlyonce in a process lifetime. This is the case for CGI for example,but it’s not guaranteed that the execution only happens one time.
issecure
¶
_True if the request is secure.
isxhr
¶
True if the request was triggered via a JavaScript XMLHttpRequest.This only works with libraries that support theX-Requested-With
header 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.Changelog
json
¶
This will contain the parsed JSON data if the mimetype indicatesJSON (_application/json, seeis_json()
), otherwise itwill beNone
.
liststorage_class
¶
alias ofwerkzeug.datastructures.ImmutableList
make_form_data_parser
()¶
Creates the form data parser. Instantiates theform_data_parser_class
with some parameters.Changelog
New in version 0.8.
max_content_length
¶
Read-only view of theMAX_CONTENT_LENGTH
config key.
max_forwards
¶
The Max-Forwards request-header field provides a mechanism with theTRACE and OPTIONS methods to limit the number of proxies or gatewaysthat can forward the request to the next inbound server.
method
¶
The request method. (For example'GET'
or'POST'
).
mimetype
¶
Likecontent_type
, but without parameters (eg, withoutcharset, type etc.) and always lowercase. For example if the contenttype istext/HTML; charset=utf-8
the mimetype would be'text/html'
.
mimetype_params
¶
The mimetype parameters as dict. For example if the contenttype istext/html; charset=utf-8
the params would be{'charset': 'utf-8'}
.
on_json_loading_failed
(_e)¶
Called ifget_json()
parsing fails and isn’t silenced. Ifthis method returns a value, it is used as the return value forget_json()
. The default implementation raises aBadRequest
exception.Changelog
Changed in version 0.10: Raise aBadRequest
error instead of returning an errormessage as JSON. If you want that behavior you can add it bysubclassing.
New in version 0.8.
parameterstorage_class
¶
alias ofwerkzeug.datastructures.ImmutableMultiDict
path
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.
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.
query_string
¶
The URL parameters as raw bytestring.
referrer
¶
The Referer[sic] request-header field allows the client to specify,for the server’s benefit, the address (URI) of the resource from whichthe Request-URI was obtained (the “referrer”, although the headerfield is misspelled).
remoteaddr
¶
The remote address of the client.
remote_user
¶
If the server supports user authentication, and the script isprotected, this attribute contains the username the user hasauthenticated as.
routing_exception
= None¶
If matching the URL failed, this is the exception that will beraised / was raised as part of the request handling. This isusually aNotFound
exception orsomething similar.
scheme
¶
URL scheme (http or https).Changelog
New in version 0.7.
script_root
The root path of the script without the trailing slash.
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 usedata
which will giveyou that data as a string. The stream only returns the data once.
Unlikeinput_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.
url
The reconstructed current URL as IRI.See also:trusted_hosts
.
url_charset
¶
The charset that is assumed for URLs. Defaults to the valueofcharset
.Changelog
New in version 0.6.
url_root
The full URL root (with hostname), this is the applicationroot as IRI.See also:trusted_hosts
.
url_rule
= 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 inrouting_exception.valid_methods
instead (an attribute of the Werkzeug exceptionMethodNotAllowed
)because the request was never internally bound.Changelog
New in version 0.6.
user_agent
¶
The current user agent.
values
¶
Awerkzeug.datastructures.CombinedMultiDict
that combinesargs
andform
.
view_args
= None¶
A dict of view arguments that matched the request. If an exceptionhappened when matching, this will beNone
.
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 aRequest
subclass 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 andsetresponse_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.
Changed in version 1.0: Addedmax_cookie_size
.status
¶
A string with a response status.
statuscode
¶
The response status as integer.
data
¶
A descriptor that callsget_data()
andset_data()
. Thisshould not be used and will eventually get deprecated.
get_json
(_force=False, silent=False, cache=True)¶
Parse and return the data as JSON. If the mimetype does notindicate JSON (application/json, seeis_json()
), this returnsNone
unlessforce
istrue. If parsing fails,onjson_loading_failed()
is calledand its return value is used as the return value.
|Parameters:
|——-
|
- force – Ignore the mimetype and always try to parse JSON.
- silent – Silence parsing errors and return Noneinstead.
- cache – Store the parsed JSON to return for subsequentcalls.
is_json
¶
Check if the mimetype indicates JSON data, either_application/json or application/*+json.Changelog
New in version 0.11.
Read-only view of theMAX_COOKIE_SIZE
config key.
Seemax_cookie_size
inWerkzeug’s docs.
mimetype
¶
The mimetype (content type without charset etc.)
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 toTrue
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
- # this change is not picked up because a mutable object (here
permanent
¶
If set toTrue
the session lives forpermanent_session_lifetime
seconds. Thedefault is 31 days. If set toFalse
(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()
andsave_session()
, the others haveuseful defaults which you don’t need to change.
The session object returned by theopen_session()
method has toprovide a dictionary like interface plus the properties and methodsfrom theSessionMixin
. We recommend just subclassing a dictand adding that mixin:- class Session(dict, SessionMixin):
pass
Ifopen_session()
returnsNone
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 defaultNullSession
class that is createdwill complain that the secret key was not set.
To replace the session interface on an application all you have to dois to assignflask.Flask.session_interface
:- app = Flask(name)
app.sessioninterface = MySessionInterface()
Changelog
New in version 0.8.
Returns the domain that should be set for the session cookie.
UsesSESSIONCOOKIE_DOMAIN
if it is configured, otherwisefalls back to detecting the domain based onSERVER_NAME
.
Once detected (or if not set at all),SESSION_COOKIE_DOMAIN
isupdated to avoid re-running the logic.
Returns True if the session cookie should be httponly. Thiscurrently just returns the value of theSESSIONCOOKIE_HTTPONLY
config var.
Returns the path for which the cookie should be valid. Thedefault implementation uses the value from theSESSIONCOOKIE_PATH
config var if it’s set, and falls back toAPPLICATION_ROOT
oruses/
if it’sNone
.
Return'Strict'
or'Lax'
if the cookie should use theSameSite
attribute. This currently just returns the value oftheSESSION_COOKIE_SAMESITE
setting.
Returns True if the cookie should be secure. This currentlyjust returns the value of theSESSIONCOOKIE_SECURE
setting.
get_expiration_time
(_app, session)¶
A helper method that returns an expiration date for the sessionorNone
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 ofnull_session_class
by 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.
This creates an instance ofnull_session_class
by default.
nullsession_class
¶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.
alias ofNullSession
open_session
(_app, request)¶
This method has to be implemented and must either returnNone
in case the loading failed because of a configuration error or aninstance of a session object which implements a dictionary likeinterface + the methods and attributes onSessionMixin
.
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.
save_session
(_app, session, response)¶
This is called for actual sessions returned byopen_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.
Used by session backends to determine if aSet-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 andtheSESSIONREFRESH_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 Session(dict, SessionMixin):
- _class
flask.sessions.
SecureCookieSessionInterface
¶
The default session interface that stores sessions in signed cookiesthrough theitsdangerous
module.- static
digestmethod
()¶
the hash function to use for the signature. The default is sha1
key_derivation
= 'hmac'¶
the name of the itsdangerous supported key derivation. The defaultis hmac.
open_session
(_app, request)¶
This method has to be implemented and must either returnNone
in case the loading failed because of a configuration error or aninstance of a session object which implements a dictionary likeinterface + the methods and attributes onSessionMixin
.
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 byopen_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
= <flask.json.tag.TaggedJSONSerializer object>¶
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.
sessionclass
¶
alias ofSecureCookieSession
- static
- _class
flask.sessions.
SecureCookieSession
(initial=None)¶
Base class for sessions based on signed cookies.
This session backend will set themodified
andaccessed
attributes. It cannot reliably track whether asession is new (vs. empty), sonew
remains hard coded toFalse
.accessed
= False¶
header, which allows caching proxies to cache different pages fordifferent users.
get
(k[, d]) → D[k] if k in D, else d. d defaults to None.¶
modified
= False¶
When data is changed, this is set toTrue
. 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 isTrue
.
setdefault
(k[, d]) → D.get(k,d), also set D[k]=d if k not in D¶
- 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 toTrue
.
modified
= True¶
Some implementations can detect changes to the session and setthis when that happens. The mixin default is hard coded toTrue
.
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 awith
body when used in awith
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 theEnvironBuilder
class withsome additions: You can provide aEnvironBuilder
or a WSGIenvironment as only argument instead of theEnvironBuilder
arguments 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 awith
statement this opens asession transaction. This can be used to modify the session thatthe test client uses. Once thewith
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.- with client.session_transaction() as session:
## Test CLI Runner¶
- _class
flask.testing.
FlaskCliRunner
(app, _kwargs)¶
ACliRunner
for testing a Flask app’sCLI commands. Typically created usingtest_cli_runner()
. See 测试 CLI 命令.invoke
(_cli=None, args=None, **kwargs)¶
Invokes a CLI command in an isolated environment. SeeCliRunner.invoke
forfull method documentation. See 测试 CLI 命令 for examples.
If theobj
argument is not given, passes an instance ofScriptInfo
that knows how to load the Flaskapp being tested.
|Parameters:
|——-
|
- cli – Command object to invoke. Default is the app’scli group.
- args – List of strings to invoke the command with.
|Returns:
|——-
|
aResult
object.
## Application Globals¶
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
.flask.
g
¶
A namespace object that can store data during anapplication context. This is an instance ofFlask.app_ctx_globals_class
, which defaults toctx._AppCtxGlobals
.
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 theg
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=<object object>)¶
Get and remove an attribute by name. Likedict.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. Likedict.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.
currentapp
¶
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 withapp_context()
.
This is a proxy. See 关于代理的说明 for more information.
flask.
hasrequestcontext
()¶
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 asrequest
org
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.- class User(db.Model):
flask.
copy_current_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.
Example:- import gevent
from flask import copycurrent_request_context
@app.route('/')
def index():
@copy_current_request_context
def do_some_work():
# do some work here, it can access flask.request like you
# would otherwise in the view function.
…
gevent.spawn(do_some_work)
return 'Regular response'
Changelog
New in version 0.10.- import gevent
flask.
has_app_context
()¶
Works likehas_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.
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 appendedto the generated URL as query arguments. If the value of a query argumentisNone
, 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:- urlfor('.index')
For more information, head over to the Quickstart.
To integrate applications,Flask
has a hook to intercept URL builderrors throughFlask.url_build_error_handlers
. The _url_for_function results in aBuildError
when the currentapp does not have a URL for the given endpoint and values. When it does, thecurrent_app
calls itsurl_build_error_handlers
ifit is notNone
, 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 externalurl_handler(error, endpoint, values):
"Looks up an external URL whenurl_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 ofBuildError
, 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: CallsFlask.handlebuild_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 SERVER_NAME configuration variable whichdefaults to _localhost.
- _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.- urlfor('.index')
flask.
abort
(_status, _args, kwargs)¶
Raises anHTTPException
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'))
- abort(404) # 404 Not Found
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 are 301,302, 303, 305, and 307. 300 is not supported because it’s not a realredirect and 304 because it’s the answer for a request with a requestwith 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 usingtheiri_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:- def index():
return render_template('index.html', foo=42)
You can now do something like this:- def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Parachutes'] = 'parachutes are cool'
return response
This function accepts the very same arguments you can return from aview function. This for example creates a response with a 404 errorcode:- response = make_response(render_template('not_found.html'), 404)
The other use case of this function is to force the return value of aview function into a response which is helpful with viewdecorators:- response = make_response(view_function())
response.headers['X-Parachutes'] = 'parachutes are cool'
Internally this function does the following things:
- if no arguments are passed, it creates a new response argument
- if one argument is passed, flask.Flask.make_response()is invoked with it.
- 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.- def index():
flask.
after_this_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.
Example:- @app.route('/')
def index():
@afterthis_request
def add_header(response):
response.headers['X-Foo'] = 'Parachute'
return response
return 'Hello World!'
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.Changelog
New in version 0.9.- @app.route('/')
flask.
send_file
(_filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=None, conditional=False, last_modified=None)¶
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 filewrapper support. Alternativelyyou can set the application’suse_x_sendfile
attributetoTrue
to directly emit anX-Sendfile
header. This howeverrequires support of the underlying webserver forX-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 usesend_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: cachetimeout 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.
|Parameters:
|——-
|
- filenameor_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.
- cache_timeout – the timeout in seconds for the headers. When None(default), this value is set byget_send_file_max_age() ofcurrent_app.
- last_modified** – set the Last-Modified header to this value,a datetime or timestamp.If a file was passed, this overrides its mtime.
flask.
send_from_directory
(_directory, filename, **options)¶
Send a file from a given directory withsend_file()
. Thisis a secure way to quickly expose static files from an upload folderor something similar.
Example usage:- @app.route('/uploads/<path:filename>')
def downloadfile(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename, as_attachment=True)
Sending files and Performance
It is strongly recommended to activate eitherX-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().- @app.route('/uploads/<path:filename>')
flask.
safe_join
(_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.- @app.route('/wiki/<path:filename>')
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
¶
Marks a string as being safe for inclusion in HTML/XML output withoutneeding to be escaped. This implements the html interface a coupleof frameworks and web applications use.Markup
is a directsubclass of unicode and provides all the methods of unicode just thatit escapes arguments passed and always returns Markup.
The escape function returns markup objects so that double escaping can’thappen.
The constructor of theMarkup
class can be used for threedifferent things: When passed an unicode object it’s assumed to be safe,when passed an object with an HTML representation (has an htmlmethod) that representation is used, otherwise the object passed isconverted into a unicode string and then assumed to be safe:- >>> Markup("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
>>> class Foo(object):
… def html(self):
… return '<a href="#">foo</a>'
…
>>> Markup(Foo())
Markup(u'<a href="#">foo</a>')
If you want object passed being always treated as unsafe you can use theescape()
classmethod to create aMarkup
object:- >>> Markup.escape("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
Operations on a markup string are markup aware which means that allarguments are passed through theescape()
function:- >>> em = Markup("<em>%s</em>")
>>> em % "foo & bar"
Markup(u'<em>foo & bar</em>')
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {'text': '<blink>hacker here</blink>'}
Markup(u'<strong><blink>hacker here</blink></strong>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u'<em>Hello</em> <foo>')
- classmethod
escape
(s)¶
Escape the string. Works likeescape()
with the differencethat for subclasses ofMarkup
this function would return thecorrect subclass.
Unescape markup into an texttype string and strip all tags. Thisalso resolves known HTML4 and XHTML entities. Whitespace isnormalized to one:- >>> Markup("Main » <em>About</em>").striptags()
u'Main \xbb About'
- >>> Markup("Main » <em>About</em>").striptags()
unescape
()¶
Unescape markup again into an text_type string. This also resolvesknown HTML4 and XHTML entities:- >>> Markup("Main » <em>About</em>").unescape()
u'Main \xbb <em>About</em>'
- >>> Markup("Main » <em>About</em>").unescape()
- >>> Markup("Hello <em>World</em>!")
## Message Flashing¶
flask.
flash
(_message, category='message')¶
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 callget_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.
flask.
getflashed_messages
(_with_categories=False, category_filter=[])¶
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 toTrue
, 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.
See 消息闪现 for examples.Changelog
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
htmlsafedumps()
function of this json module is also availableas filter called |tojson
in Jinja2. Note that inside script
tags 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:
- <script type=text/javascript>
doSomethingWith({{ user.username|tojson|safe }});
</script>
Auto-Sort JSON Keys
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 wrapsdumps()
to add a few enhancements that makelife easier. It turns the JSON output into aResponse
object with the _application/json mimetype. For convenience, italso converts multiple arguments into an array or multiple keyword argumentsinto a dict. This means that bothjsonify(1,2,3)
andjsonify([1,2,3])
serialize to[1,2,3]
.
For clarity, the JSON serialization behavior has the following differencesfromdumps()
:
- 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.
Example usage:- from flask import jsonify
@app.route('/get_current_user')
def get_current_user():
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
This will send a JSON response like this to the browser:- {
"username": "admin",
"email": "admin@localhost",
"id": 42
}
Changelog
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.- from flask import jsonify
flask.json.
dumps
(_obj, _kwargs)¶
Serializeobj
to a JSON formattedstr
by using the application’sconfigured encoder (json_encoder
) if there is anapplication on the stack.
This function can returnunicode
strings or ascii-only bytestrings bydefault which coerce into unicode strings automatically. That behavior bydefault is controlled by theJSON_AS_ASCII
configuration variableand can be overridden by the simplejsonensure_ascii
parameter.
flask.json.
loads
(s, **kwargs)¶
Unserialize a JSON object from a strings
by using the application’sconfigured decoder (json_decoder
) if there is anapplication on the stack.
- class
flask.json.
JSONEncoder
(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶
The default Flask JSON encoder. This one extends the default simplejsonencoder by also supportingdatetime
objects,UUID
as well asMarkup
objects which are serialized as RFC 822 datetime strings (sameas the HTTP date format). In order to support more data types override thedefault()
method.default
(o)¶
Implement this method in a subclass such that it returns aserializable object foro
, or calls the base implementation (toraise aTypeError
).
For example, to support arbitrary iterators, you could implementdefault like this:- def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
- def default(self, o):
- 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 thejson
documentationfor more information. This decoder is not only used for the loadfunctions of this module but alsoRequest
.
### 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
.
The following extra types are supported:
- dict
- tuple
- bytes
- Markup
- UUID
- datetime
Tag classes to bind when creating the serializer. Other tags can beadded later usingregister()
.
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 andforce
isnot true.
tag
(value)¶
Convert a value to a tagged representation if necessary.
untag
(value)¶
Convert a tagged representation back to the original type.
- class
flask.json.tag.
JSONTag
(serializer)¶
Base class for defining type tags forTaggedJSONSerializer
.check
(value)¶
Check if the given value should be tagged by this tag.
key
= None¶
The tag to mark the serialized object with. IfNone
, 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 tojson(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)
## Template Rendering¶
flask.
render_template
(_template_name_or_list, **context)¶
Renders a template from the template folder with the givencontext.
|Parameters:
|——-
|
- template_name_or_list – the name of the template to berendered, or an iterable with template namesthe first one existing will be rendered
- context – the variables that should be available in thecontext of the template.
flask.
rendertemplate_string
(_source, **context)¶
Renders a template from the given template source stringwith the given context. Template variables will be autoescaped.
|Parameters:
|——-
|
- source – the source code of the template to berendered
- context – the variables that should be available in thecontext of the template.
flask.
gettemplate_attribute
(_template_name, attribute)¶
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 namedcider.html
with the following contents:- {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
You can access this from Python code like this:- hello = get_template_attribute('_cider.html', 'hello')
return hello('World')
Changelog
New in version 0.2.
|Parameters:
|——-
|
- template_name – the name of the template
- attribute – the name of the variable of macro to access- {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
## 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.frompyfile('yourconfig.cfg')
Or alternatively you can define the configuration options in themodule that callsfrom_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:- DEBUG = True
SECRETKEY = 'development key'
app.config.fromobject(__name)
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:- app.config.from_envvar('YOURAPPLICATION_SETTINGS')
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:- export YOURAPPLICATION_SETTINGS='/path/to/config/file'
On windows use _set instead.
|Parameters:
|——-
|
- 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 valuesfromenvvar
(_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:- app.config.frompyfile(os.environ['YOURAPPLICATION_SETTINGS'])
|Parameters:
|——-
|
- variable_name – name of the environment variable
- silent – set to True if you want silent failure for missingfiles.
|Returns:
|——-
|
bool.True
if able to load config,False
otherwise.- app.config.frompyfile(os.environ['YOURAPPLICATION_SETTINGS'])
from_json
(_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 likeupdate()
ignoring items with non-upperkeys.Changelog
New in version 0.11.
from_object
(_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. Adict
object will not work withfrom_object()
because the keys of adict
are not attributes of thedict
class.
Example of module-based configuration:- app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)
You should not use this function to load the actual configuration butrather configuration defaults. The actual config should be loadedwithfrom_pyfile()
and ideally from a location not within thepackage because the package might be installed system wide.
See 开发/生产 for an example of class-based configurationusingfrom_object()
.
|Parameters:
|——-
|obj – an import name or object- app.config.from_object('yourapplication.default_config')
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.Changelog
New in version 0.7: silent parameter.
getnamespace
(_namespace, lowercase=True, trim_namespace=True)¶
Returns a dictionary containing a subset of configuration optionsthat match the specified namespace/prefix. Example usage:- app.config['IMAGESTORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE')
The resulting dictionary image_store_config would look like:- {
'type': 'fs',
'path': '/var/app/images',
'base_url': 'http://img.website.com'
}
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
- trimnamespace** – a flag indicating if the keys of the resultingdictionary should not include the namespaceChangelog
New in version 0.11.- app.config['IMAGESTORE_TYPE'] = 'fs'
- app.config.frompyfile('yourconfig.cfg')
## Stream Helpers¶
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 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:- from flask import streamwith_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.- from flask import streamwith_context, request, Response
## Useful Internals¶
- _class
flask.ctx.
RequestContext
(app, environ, request=None)¶
The request context contains all request relevant information. It iscreated at the beginning of the request and pushed to therequestctx_stack and removed at the end of it. It will create theURL adapter and request object for the WSGI environment provided.
Do not attempt to use this class directly, instead usetest_request_context()
andrequest_context()
to create this object.
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 ofDEBUG
mode. By setting'flask.preserve_context'
toTrue
on the WSGI environment thecontext will not pop itself at the end of the request. This is used bythetest_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 properlypop()
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.Changelog
New in version 0.10.
match_request
()¶
Can be overridden by a subclass to hook into the matchingof the request.
pop
(_exc=<object object>)¶
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 internalLocalStack
that holdsRequestContext
instances. Typically, therequest
andsession
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=<object object>)¶
Pops the app context.
push
()¶
Binds the app context to the current context.
flask.
app_ctx_stack
¶
The internalLocalStack
that holdsAppContext
instances. Typically, thecurrent_app
andg
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.addurl_rule
(_rule, endpoint=None, view_func=None, **options)¶
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,None
otherwise.
url_defaults
= None¶
A dictionary with URL defaults that is added to each and everyURL that was defined with the blueprint.
## 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 logtemplate_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)
- def logtemplate_renders(sender, template, context, **extra):
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 logtemplate_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)
- def logtemplate_renders(sender, template, context, extra):
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 asrequest
.
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)
- def log_request(sender, extra):
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 logresponse(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)
- def logresponse(sender, response, **extra):
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 logexception(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)
- def logexception(sender, exception, extra):
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.- def close_db_connection(sender, extra):
flask.
appcontexttearing_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.- def close_db_connection(sender, **extra):
flask.
appcontextpushed
¶
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 appcontextpushed
@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.- from contextlib import contextmanager
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 messageflashed
message_flashed.connect(record, app)
Changelog
New in version 0.10.- recorded = []
- _class
signals.
Namespace
¶
An alias forblinker.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 aRuntimeError
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. Ifmethods
is provided the methodsdo not have to be passed to theadd_url_rule()
method explicitly:- class MyView(View):
methods = ['GET']
def dispatchrequest(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 thedecorators
attribute:- class SecretView(View):
methods = ['GET']
decorators = [superuser_required]
def dispatch_request(self):
…
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!- classmethod
asview
(_name, *class_args, _classkwargs)¶
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 theView
on each request and callthedispatch_request()
method on it.
The arguments passed toas_view()
are forwarded to theconstructor of the class.
decorators
= ()¶
The canonical way to decorate class-based views is to decorate thereturn value of asview(). 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.
provide_automatic_options
= None¶
Setting this disables or force-enables the automatic options handling.
- class MyView(View):
- _class
flask.views.
MethodView
¶
A class-based view that dispatches request methods to the correspondingclass methods. For example, if you implement aget
method, it will beused to handleGET
requests.- class CounterAPI(MethodView):
def get(self):
return session.get('counter', 0)
def post(self):
session['counter'] = session.get('counter', 0) + 1
return 'OK'
app.addurl_rule('/counter', view_func=CounterAPI.as_view('counter'))
dispatch_request
(args, *kwargs)¶
Subclasses have to override this method to implement theactual view function code. This method is called with allthe arguments from the URL rule.
- class CounterAPI(MethodView):
## URL Route Registrations¶
Generally there are three ways to define rules for the routing system:
- You can use the flask.Flask.route() decorator.
- You can use the flask.Flask.add_url_rule() function.
- 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.
The following converters are available:
|_string|accepts any text without a slash (the default)
|int|accepts integers
|float|like int but for floating point values
|path|like the default but also accepts slashes
|any|matches one of the items provided
|uuid|accepts UUID strings
Custom converters can be defined using
flask.Flask.url_map
.Here are some examples:
- @app.route('/')
def index():
pass
@app.route('/<username>')
def showuser(username):
pass
@app.route('/post/<int:post_id>')
def show_post(post_id):
pass
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:
- @app.route('/users/', defaults={'page': 1})
@app.route('/users/page/<int:page>')
def show_users(page):
pass
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 POST
requests, make sure the default route only handles GET
, as redirectscan’t preserve form data.
- @app.route('/region/', defaults={'id': 1})
@app.route('/region/<id>', methods=['GET', 'POST'])
def region(id):
pass
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 the
view_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 underlying
Rule
object. A change toWerkzeug is handling of method options. methods is a listof methods this rule should be limited to (GET
, POST
etc.). 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.
Full example:
- def index():
if request.method == 'OPTIONS':
# custom options handling here
…
return 'Hello World!'
index.provideautomatic_options = False
index.methods = ['GET', 'OPTIONS']
app.add_url_rule('/', index)
Changelog
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, **extra)¶
Special subclass of theAppGroup
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 wil 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.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,SystemExit
needs to be caught.
This method is also available by directly calling the instance ofaCommand
.
New in version 3.0: Added the standalone_mode flag to control the standalone mode.Changelog
|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"_COMPLETE" with prog name inuppercase. they will bepropagated to the caller and the returnvalue of this function is the return valueof invoke().
- 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
- 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 clickGroup
but itchanges the behavior of thecommand()
decorator so that itautomatically wraps the functions inwith_appcontext()
.
Not to be confused withFlaskGroup
.command
(*args, **kwargs)¶
This works exactly like the method of the same name on a regularclick.Group
but it wraps callbacks inwith_appcontext()
unless it’s disabled by passingwithappcontext=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)¶
Help 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.
create_app
= 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.
load_dotenv
(_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.
This is a no-op if python-dotenv is not installed.
|Parameters:
|——-
|path* – Load the file at this location instead of searching.
|Returns:
|——-
|True
if a file was loaded.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 theapp.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 ofScriptInfo
is passedas first argument to the click callback.
flask.cli.
runcommand
= <click.core.Command object>¶
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.
shell_command
= <click.core.Command object>_¶
Runs 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.