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¶
- classflask.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 withan
__init__.py
file inside) or a standard module (just a.py
file).For more information about resource loading, see
open_resource()
.Usually you create a
Flask
instance in your main module orin the__init__.py
file of your package like this:fromflaskimportFlaskapp=Flask(__name__)
About the First Parameter
The idea of the first parameter is to give Flask an idea of whatbelongs to your application. This name is used to find resourceson the filesystem, can be used by extensions to improve debugginginformation and a lot more.
So it's important what you provide there. If you are using a singlemodule,__name__ is always the correct value. If you however areusing a package, it's usually recommended to hardcode the name ofyour package there.
For example if your application is defined in
yourapplication/app.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 inyourapplication.app and notyourapplication.views.frontend)
Changelog
バージョン 1.0 で追加:The
host_matching
andstatic_host
parameters were added.バージョン 1.0 で追加:The
subdomain_matching
parameter was added. Subdomainmatching needs to be enabled manually now. SettingSERVER_NAME
does not implicitly enable it.バージョン 0.11 で追加:Theroot_path parameter was added.
バージョン 0.8 で追加:Theinstance_path andinstance_relative_config parameters wereadded.
バージョン 0.7 で追加:Thestatic_url_path,static_folder, andtemplate_folderparameters were added.
- パラメータ
import_name (str) -- the name of the application package
static_url_path (Optional[str]) -- can be used to specify a different path for thestatic files on the web. Defaults to the nameof thestatic_folder folder.
static_folder (Optional[Union[str,os.PathLike]]) -- The folder with static files that is served at
static_url_path
. Relative to the applicationroot_path
or an absolute path. Defaults to'static'
.static_host (Optional[str]) -- the host to use when adding the static route.Defaults to None. Required when using
host_matching=True
with astatic_folder
configured.host_matching (bool) -- set
url_map.host_matching
attribute.Defaults to False.subdomain_matching (bool) -- consider the subdomain relative to
SERVER_NAME
when matching routes. Defaults to False.template_folder (Optional[str]) -- the folder that contains the templates that shouldbe used by the application. Defaults to
'templates'
folder in the root path of theapplication.instance_path (Optional[str]) -- 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 (bool) -- if set to
True
relative filenamesfor loading the config are assumed tobe relative to the instance path insteadof the application root.root_path (Optional[str]) -- The path to the root of the application files.This should only be set manually when it can't be detectedautomatically, such as for namespace packages.
- aborter¶
An instance of
aborter_class
created bymake_aborter()
. This is called byflask.abort()
to raise HTTP errors, and can be called directly as well.バージョン 2.2 で追加:Moved from
flask.abort
, which calls this object.
- add_template_filter(f,name=None)¶
Register a custom template filter. Works exactly like the
template_filter()
decorator.
- add_template_global(f,name=None)¶
Register a custom template global function. Works exactly like the
template_global()
decorator.Changelog
バージョン 0.10 で追加.
- add_template_test(f,name=None)¶
Register a custom template test. Works exactly like the
template_test()
decorator.Changelog
バージョン 0.10 で追加.
- add_url_rule(rule,endpoint=None,view_func=None,provide_automatic_options=None,**options)¶
Register a rule for routing incoming requests and buildingURLs. The
route()
decorator is a shortcut to call thiswith theview_func
argument. These are equivalent:@app.route("/")defindex():...
defindex():...app.add_url_rule("/",view_func=index)
The endpoint name for the route defaults to the name of the viewfunction if the
endpoint
parameter isn't passed. An errorwill be raised if a function has already been registered for theendpoint.The
methods
parameter defaults to["GET"]
.HEAD
isalways added automatically, andOPTIONS
is addedautomatically by default.view_func
does not necessarily need to be passed, but if therule should participate in routing an endpoint name must beassociated with a view function at some point with theendpoint()
decorator.app.add_url_rule("/",endpoint="index")@app.endpoint("index")defindex():...
If
view_func
has arequired_methods
attribute, thosemethods are added to the passed and automatic methods. If ithas aprovide_automatic_methods
attribute, it is used as thedefault if the parameter is not passed.- パラメータ
rule (str) -- The URL rule string.
endpoint (Optional[str]) -- The endpoint name to associate with the ruleand view function. Used when routing and building URLs.Defaults to
view_func.__name__
.view_func (Optional[Union[Callable[[...],Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],WSGIApplication]],Callable[[...],Awaitable[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],WSGIApplication]]]]]) -- The view function to associate with theendpoint name.
provide_automatic_options (Optional[bool]) -- Add the
OPTIONS
method andrespond toOPTIONS
requests automatically.
- 戻り値の型
None
- after_request(f)¶
Register a function to run after each request to this object.
The function is called with the response object, and must returna response object. This allows the functions to modify orreplace the response before it is sent.
If a function raises an exception, any remaining
after_request
functions will not be called. Therefore, thisshould not be used for actions that must execute, such as toclose resources. Useteardown_request()
for that.- パラメータ
f (flask.scaffold.T_after_request) --
- 戻り値の型
flask.scaffold.T_after_request
- after_request_funcs:t.Dict[ft.AppOrBlueprintKey,t.List[ft.AfterRequestCallable]]¶
A data structure of functions to call at the end of eachrequest, in the format
{scope:[functions]}
. Thescope
key is the name of a blueprint the functions areactive for, orNone
for all requests.To register a function, use the
after_request()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- app_context()¶
Create an
AppContext
. Use as awith
block to push the context, which will makecurrent_app
point at this application.An application context is automatically pushed by
RequestContext.push()
when handling a request, and when running a CLI command. Usethis to manually create a context outside of these situations.withapp.app_context():init_db()
Seeアプリケーションのコンテキスト(The Application Context).
Changelog
バージョン 0.9 で追加.
- 戻り値の型
- async_to_sync(func)¶
Return a sync function that will run the coroutine function.
result=app.async_to_sync(func)(*args,**kwargs)
Override this method to change how the app converts async codeto be synchronously callable.
Changelog
バージョン 2.0 で追加.
- 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 named
instance
next to your main file orthe package.Changelog
バージョン 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.
バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Run setup code when creatingthe application instead.
Changelog
バージョン 0.8 で追加.
- パラメータ
f (flask.app.T_before_first_request) --
- 戻り値の型
flask.app.T_before_first_request
- before_first_request_funcs:t.List[ft.BeforeFirstRequestCallable]¶
A list of functions that will be called at the beginning of thefirst request to this instance. To register a function, use the
before_first_request()
decorator.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Run setup code whencreating the application instead.
Changelog
バージョン 0.8 で追加.
- before_request(f)¶
Register a function to run before each request.
For example, this can be used to open a database connection, orto load the logged in user from the session.
@app.before_requestdefload_user():if"user_id"insession:g.user=db.session.get(session["user_id"])
The function will be called without any arguments. If it returnsa non-
None
value, the value is handled as if it was thereturn value from the view, and further request handling isstopped.- パラメータ
f (flask.scaffold.T_before_request) --
- 戻り値の型
flask.scaffold.T_before_request
- before_request_funcs:t.Dict[ft.AppOrBlueprintKey,t.List[ft.BeforeRequestCallable]]¶
A data structure of functions to call at the beginning ofeach request, in the format
{scope:[functions]}
. Thescope
key is the name of a blueprint the functions areactive for, orNone
for all requests.To register a function, use the
before_request()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- blueprints:t.Dict[str,'Blueprint']¶
Maps registered blueprint names to blueprint objects. Thedict retains the order the blueprints were registered in.Blueprints can be registered multiple times, this dict doesnot track how often they were attached.
Changelog
バージョン 0.7 で追加.
- cli¶
The Click command group for registering CLI commands for thisobject. The commands are available from the
flask
commandonce the application has been discovered and blueprints havebeen registered.
- config¶
The configuration dictionary as
Config
. This behavesexactly like a regular dictionary but supports additional methodsto load a config from files.
- context_processor(f)¶
Registers a template context processor function.
- パラメータ
f (flask.scaffold.T_template_context_processor) --
- 戻り値の型
flask.scaffold.T_template_context_processor
- create_global_jinja_loader()¶
Creates the loader for the Jinja2 environment. Can be used tooverride just the loader and keeping the rest unchanged. It'sdiscouraged to override this function. Instead one should overridethe
jinja_loader()
function instead.The global loader dispatches between the loaders of the applicationand the individual blueprints.
Changelog
バージョン 0.7 で追加.
- 戻り値の型
flask.templating.DispatchingJinjaLoader
- create_jinja_environment()¶
Create the Jinja environment based on
jinja_options
and the various Jinja-related methods of the app. Changingjinja_options
after this will have no effect. Also addsFlask-related globals and filters to the environment.Changelog
バージョン 0.11 で変更:
Environment.auto_reload
set in accordance withTEMPLATES_AUTO_RELOAD
configuration option.バージョン 0.5 で追加.
- 戻り値の型
flask.templating.Environment
- 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
バージョン 1.0 で変更:
SERVER_NAME
no longer implicitly enables subdomainmatching. Usesubdomain_matching
instead.バージョン 0.9 で変更:This can now also be called without a request object when theURL adapter is created for the application context.
バージョン 0.6 で追加.
- パラメータ
request (Optional[flask.wrappers.Request]) --
- 戻り値の型
- propertydebug:bool¶
Whether debug mode is enabled. When using
flaskrun
to start thedevelopment server, an interactive debugger will be shown for unhandledexceptions, and the server will be reloaded when code changes. This maps to theDEBUG
config key. It may not behave as expected if set late.Do not enable debug mode when deploying in production.
Default:
False
- default_config={'APPLICATION_ROOT':'/','DEBUG':None,'ENV':None,'EXPLAIN_TEMPLATE_LOADING':False,'JSONIFY_MIMETYPE':None,'JSONIFY_PRETTYPRINT_REGULAR':None,'JSON_AS_ASCII':None,'JSON_SORT_KEYS':None,'MAX_CONTENT_LENGTH':None,'MAX_COOKIE_SIZE':4093,'PERMANENT_SESSION_LIFETIME':datetime.timedelta(days=31),'PREFERRED_URL_SCHEME':'http','PROPAGATE_EXCEPTIONS':None,'SECRET_KEY':None,'SEND_FILE_MAX_AGE_DEFAULT':None,'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.
- dispatch_request()¶
Does the request dispatching. Matches the URL and returns thereturn value of the view or error handler. This does not have tobe a response object. In order to convert the return value to aproper response object, call
make_response()
.Changelog
バージョン 0.7 で変更:This no longer does the exception handling, this code wasmoved to the new
full_dispatch_request()
.- 戻り値の型
Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]], WSGIApplication]
- do_teardown_appcontext(exc=<objectobject>)¶
Called right before the application context is popped.
When handling a request, the application context is poppedafter the request context. See
do_teardown_request()
.This calls all functions decorated with
teardown_appcontext()
. Then theappcontext_tearing_down
signal is sent.This is called by
AppContext.pop()
.Changelog
バージョン 0.9 で追加.
- パラメータ
exc (Optional[BaseException]) --
- 戻り値の型
None
- do_teardown_request(exc=<objectobject>)¶
Called after the request is dispatched and the response isreturned, right before the request context is popped.
This calls all functions decorated with
teardown_request()
, andBlueprint.teardown_request()
if a blueprint handled the request. Finally, therequest_tearing_down
signal is sent.This is called by
RequestContext.pop()
,which may be delayed during testing to maintain access toresources.- パラメータ
exc (Optional[BaseException]) -- An unhandled exception raised while dispatching therequest. Detected from the current exception information ifnot passed. Passed to each teardown function.
- 戻り値の型
None
Changelog
バージョン 0.9 で変更:Added the
exc
argument.
- endpoint(endpoint)¶
Decorate a view function to register it for the givenendpoint. Used if a rule is added without a
view_func
withadd_url_rule()
.app.add_url_rule("/ex",endpoint="example")@app.endpoint("example")defexample():...
- ensure_sync(func)¶
Ensure that the function is synchronous for WSGI workers.Plain
def
functions are returned as-is.asyncdef
functions are wrapped to run and wait for the response.Override this method to change how the app runs async views.
Changelog
バージョン 2.0 で追加.
- propertyenv:str¶
What environment the app is running in. This maps to the
ENV
configkey.Do not enable development when deploying in production.
Default:
'production'
バージョン 2.2 で非推奨:Will be removed in Flask 2.3.
- error_handler_spec:t.Dict[ft.AppOrBlueprintKey,t.Dict[t.Optional[int],t.Dict[t.Type[Exception],ft.ErrorHandlerCallable]]]¶
A data structure of registered error handlers, in the format
{scope:{code:{class:handler}}}
. Thescope
key isthe name of a blueprint the handlers are active for, orNone
for all requests. Thecode
key is the HTTPstatus code forHTTPException
, orNone
forother exceptions. The innermost dictionary maps exceptionclasses to handler functions.To register an error handler, use the
errorhandler()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- 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)defpage_not_found(error):return'This page does not exist',404
You can also register handlers for arbitrary exceptions:
@app.errorhandler(DatabaseError)defspecial_exception_handler(error):return'Database connection failed',500
Changelog
バージョン 0.7 で追加:Use
register_error_handler()
instead of modifyingerror_handler_spec
directly, for application wide errorhandlers.バージョン 0.7 で追加:One can now additionally also register custom exception typesthat do not necessarily have to be a subclass of the
HTTPException
class.
- extensions:dict¶
a place where extensions can store application specific state. Forexample this is where an extension could store database engines andsimilar things.
The key must match the name of the extension module. For example incase of a "Flask-Foo" extension inflask_foo, the key would be
'foo'
.Changelog
バージョン 0.7 で追加.
- full_dispatch_request()¶
Dispatches the request and on top of that performs requestpre and postprocessing as well as HTTP exception catching anderror handling.
Changelog
バージョン 0.7 で追加.
- get_send_file_max_age(filename)¶
Used by
send_file()
to determine themax_age
cachevalue for a given file path if it wasn't passed.By default, this returns
SEND_FILE_MAX_AGE_DEFAULT
fromthe configuration ofcurrent_app
. This defaultstoNone
, which tells the browser to use conditional requestsinstead of a timed cache, which is usually preferable.Changelog
バージョン 2.0 で変更:The default configuration is
None
instead of 12 hours.バージョン 0.9 で追加.
- propertygot_first_request:bool¶
This attribute is set to
True
if the application startedhandling the first request.Changelog
バージョン 0.8 で追加.
- handle_exception(e)¶
Handle an exception that did not have an error handlerassociated with it, or that was raised from an error handler.This always causes a 500
InternalServerError
.Always sends the
got_request_exception
signal.If
propagate_exceptions
isTrue
, such as in debugmode, the error will be re-raised so that the debugger candisplay it. Otherwise, the original exception is logged, andanInternalServerError
is returned.If an error handler is registered for
InternalServerError
or500
, it will be used. For consistency, the handler willalways receive theInternalServerError
. The originalunhandled exception is available ase.original_exception
.Changelog
バージョン 1.1.0 で変更:Always passes the
InternalServerError
instance to thehandler, settingoriginal_exception
to the unhandlederror.バージョン 1.1.0 で変更:
after_request
functions and other finalization is doneeven for the default 500 response when there is no handler.バージョン 0.3 で追加.
- パラメータ
e (Exception) --
- 戻り値の型
- handle_http_exception(e)¶
Handles an HTTP exception. By default this will invoke theregistered error handlers and fall back to returning theexception as response.
Changelog
バージョン 1.0.3 で変更:
RoutingException
, used internally for actions such as slash redirects during routing, is not passed to error handlers.バージョン 1.0 で変更:Exceptions are looked up by codeand by MRO, so
HTTPException
subclasses can be handled with a catch-allhandler for the baseHTTPException
.バージョン 0.3 で追加.
- パラメータ
- 戻り値の型
Union[werkzeug.exceptions.HTTPException,Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]], WSGIApplication]
- handle_url_build_error(error,endpoint,values)¶
Called by
url_for()
if aBuildError
was raised. If this returnsa value, it will be returned byurl_for
, otherwise the errorwill be re-raised.Each function in
url_build_error_handlers
is called witherror
,endpoint
andvalues
. If a function returnsNone
or raises aBuildError
, it is skipped. Otherwise,its return value is returned byurl_for
.
- handle_user_exception(e)¶
This method is called whenever an exception occurs thatshould be handled. A special case is
HTTPException
which is forwarded to thehandle_http_exception()
method. This function will eitherreturn a response value or reraise the exception with the sametraceback.Changelog
バージョン 1.0 で変更:Key errors raised from request data like
form
show thebad key in debug mode rather than a generic bad requestmessage.バージョン 0.7 で追加.
- パラメータ
e (Exception) --
- 戻り値の型
Union[werkzeug.exceptions.HTTPException,Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]], WSGIApplication]
- propertyhas_static_folder:bool¶
True
ifstatic_folder
is set.Changelog
バージョン 0.5 で追加.
- import_name¶
The name of the package or module that this object belongsto. Do not change 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
バージョン 0.7 で追加.
- instance_path¶
Holds the path to the instance folder.
Changelog
バージョン 0.8 で追加.
- iter_blueprints()¶
Iterates over all blueprints by the order they were registered.
Changelog
バージョン 0.11 で追加.
- 戻り値の型
- propertyjinja_env:flask.templating.Environment¶
The Jinja environment used to load templates.
The environment is created the first time this property isaccessed. Changing
jinja_options
after that will have noeffect.
- propertyjinja_loader:Optional[jinja2.loaders.FileSystemLoader]¶
The Jinja loader for this object's templates. By default thisis a class
jinja2.loaders.FileSystemLoader
totemplate_folder
if it is set.Changelog
バージョン 0.5 で追加.
- jinja_options:dict={}¶
Options that are passed to the Jinja environment in
create_jinja_environment()
. Changing these options afterthe environment is created (accessingjinja_env
) willhave no effect.Changelog
バージョン 1.1.0 で変更:This is a
dict
instead of anImmutableDict
to alloweasier configuration.
- json:JSONProvider¶
Provides access to JSON methods. Functions in
flask.json
will call methods on this provider when the application contextis active. Used for handling JSON requests and responses.An instance of
json_provider_class
. Can be customized bychanging that attribute on a subclass, or by assigning to thisattribute afterwards.The default,
DefaultJSONProvider
,uses Python's built-injson
library. A different providercan use a different JSON library.バージョン 2.2 で追加.
- propertyjson_decoder:Type[json.decoder.JSONDecoder]¶
The JSON decoder class to use. Defaults to
JSONDecoder
.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Customize
json_provider_class
instead.Changelog
バージョン 0.10 で追加.
- propertyjson_encoder:Type[json.encoder.JSONEncoder]¶
The JSON encoder class to use. Defaults to
JSONEncoder
.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Customize
json_provider_class
instead.Changelog
バージョン 0.10 で追加.
- log_exception(exc_info)¶
Logs an exception. This is called by
handle_exception()
if debugging is disabled and right before the handler is called.The default implementation logs the exception as error on thelogger
.Changelog
バージョン 0.8 で追加.
- パラメータ
exc_info (Union[Tuple[type,BaseException,types.TracebackType],Tuple[None,None,None]]) --
- 戻り値の型
None
- propertylogger:logging.Logger¶
A standard Python
Logger
for the app, withthe same name asname
.In debug mode, the logger's
level
willbe set toDEBUG
.If there are no handlers configured, a default handler will beadded. Seeログ処理(Logging) for more information.
Changelog
バージョン 1.1.0 で変更:The logger takes the same name as
name
rather thanhard-coding"flask.app"
.バージョン 1.0.0 で変更:Behavior was simplified. The logger is always named
"flask.app"
. The level is only set during configuration,it doesn't checkapp.debug
each time. Only one format isused, not different ones depending onapp.debug
. Nohandlers are removed, and a handler is only added if nohandlers are already configured.バージョン 0.3 で追加.
- make_aborter()¶
Create the object to assign to
aborter
. That objectis called byflask.abort()
to raise HTTP errors, and canbe called directly as well.By default, this creates an instance of
aborter_class
,which defaults towerkzeug.exceptions.Aborter
.バージョン 2.2 で追加.
- make_config(instance_relative=False)¶
Used to create the config attribute by the Flask constructor.Theinstance_relative parameter is passed in from the constructorof Flask (there namedinstance_relative_config) and indicates ifthe config should be relative to the instance path or the root pathof the application.
Changelog
バージョン 0.8 で追加.
- パラメータ
instance_relative (bool) --
- 戻り値の型
- make_default_options_response()¶
This method is called to create the default
OPTIONS
response.This can be changed through subclassing to change the defaultbehavior ofOPTIONS
responses.Changelog
バージョン 0.7 で追加.
- make_response(rv)¶
Convert the return value from a view function to an instance of
response_class
.- パラメータ
rv (Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],WSGIApplication]) --
the return value from the view function. The view functionmust return a response. Returning
None
, or the view endingwithout returning, is not allowed. The following types are allowedforview_rv
:str
A response object is created with the string encoded to UTF-8as the body.
bytes
A response object is created with the bytes as the body.
dict
A dictionary that will be jsonify'd before being returned.
list
A list that will be jsonify'd before being returned.
generator
oriterator
A generator that returns
str
orbytes
to bestreamed as the response.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.
- 戻り値の型
バージョン 2.2 で変更:A generator will be converted to a streaming response.A list will be converted to a JSON response.
Changelog
バージョン 1.1 で変更:A dict will be converted to a JSON response.
バージョン 0.9 で変更:Previously a tuple was interpreted as the arguments for theresponse object.
- make_shell_context()¶
Returns the shell context for an interactive shell for thisapplication. This runs all the registered shell contextprocessors.
Changelog
バージョン 0.11 で追加.
- 戻り値の型
- propertyname:str¶
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
バージョン 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.
- open_resource(resource,mode='rb')¶
Open a resource file relative to
root_path
forreading.For example, if the file
schema.sql
is next to the fileapp.py
where theFlask
app is defined, it can be openedwith:withapp.open_resource("schema.sql")asf:conn.executescript(f.read())
- permanent_session_lifetime¶
A
timedelta
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 the
PERMANENT_SESSION_LIFETIME
configuration key. Defaults totimedelta(days=31)
- preprocess_request()¶
Called before the request is dispatched. Calls
url_value_preprocessors
registered with the app and thecurrent blueprint (if any). Then callsbefore_request_funcs
registered with the app and the blueprint.If any
before_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.- 戻り値の型
Optional[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]], WSGIApplication]]
- 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 the
after_request()
decorated functions.Changelog
バージョン 0.5 で変更:As of Flask 0.5 the functions registered for after requestexecution are called in reverse order of registration.
- パラメータ
response (flask.wrappers.Response) -- a
response_class
object.- 戻り値
a new response object or the same, has to be aninstance of
response_class
.- 戻り値の型
- propertypropagate_exceptions:bool¶
Returns the value of the
PROPAGATE_EXCEPTIONS
configurationvalue in case it's set, otherwise a sensible default is returned.バージョン 2.2 で非推奨:Will be removed in Flask 2.3.
Changelog
バージョン 0.7 で追加.
- redirect(location,code=302)¶
Create a redirect response object.
This is called by
flask.redirect()
, and can be calleddirectly as well.- パラメータ
- 戻り値の型
バージョン 2.2 で追加:Moved from
flask.redirect
, which calls this method.
- register_blueprint(blueprint,**options)¶
Register a
Blueprint
on the application. Keywordarguments passed to this method will override the defaults set on theblueprint.Calls the blueprint's
register()
method afterrecording the blueprint in the application'sblueprints
.- パラメータ
blueprint (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 (Any) -- Additional keyword arguments are passed to
BlueprintSetupState
. They can beaccessed inrecord()
callbacks.
- 戻り値の型
None
Changelog
バージョン 2.0.1 で変更:The
name
option can be used to change the (pre-dotted)name the blueprint is registered with. This allows the sameblueprint to be registered multiple times with unique namesforurl_for
.バージョン 0.7 で追加.
- register_error_handler(code_or_exception,f)¶
Alternative error attach function to the
errorhandler()
decorator that is more straightforward to use for non decoratorusage.Changelog
バージョン 0.7 で追加.
- パラメータ
f (Callable[[Any],Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],WSGIApplication]]) --
- 戻り値の型
None
- request_context(environ)¶
Create a
RequestContext
representing aWSGI environment. Use awith
block to push the context,which will makerequest
point at this request.Seeリクエストのコンテキスト(The Request Context).
Typically you should not call this from your own code. A requestcontext is automatically pushed by the
wsgi_app()
whenhandling a request. Usetest_request_context()
to createan environment and context instead of this method.- パラメータ
environ (dict) -- a WSGI environment
- 戻り値の型
- root_path¶
Absolute path to the package on the filesystem. Used to lookup resources contained in the package.
- route(rule,**options)¶
Decorate a view function to register it with the given URLrule and options. Calls
add_url_rule()
, which has moredetails about the implementation.@app.route("/")defindex():return"Hello, World!"
The endpoint name for the route defaults to the name of the viewfunction if the
endpoint
parameter isn't passed.The
methods
parameter defaults to["GET"]
.HEAD
andOPTIONS
are added automatically.
- run(host=None,port=None,debug=None,load_dotenv=True,**options)¶
Runs the application on a local development server.
Do not use
run()
in a production setting. It is not intended tomeet security and performance requirements for a production server.Instead, see本番環境への展開(Deployment to Production) for WSGI server recommendations.If the
debug
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 pass
use_evalex=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 theflask command line script's
run
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 toinvoke
run()
withdebug=True
anduse_reloader=False
.Settinguse_debugger
toTrue
without being in debug modewon't catch any exceptions because there won't be any tocatch.- パラメータ
host (Optional[str]) -- 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 theSERVER_NAME
config variableif present.port (Optional[int]) -- the port of the webserver. Defaults to
5000
or theport defined in theSERVER_NAME
config variable if present.debug (Optional[bool]) -- if given, enable or disable debug mode. See
debug
.load_dotenv (bool) -- Load the nearest
.env
and.flaskenv
files to set environment variables. Will also change the workingdirectory to the directory containing the first file found.options (Any) -- the options to be forwarded to the underlying Werkzeugserver. See
werkzeug.serving.run_simple()
for moreinformation.
- 戻り値の型
None
Changelog
バージョン 1.0 で変更:If installed, python-dotenv will be used to load environmentvariables from
.env
and.flaskenv
files.The
FLASK_DEBUG
environment variable will overridedebug
.Threaded mode is enabled by default.
バージョン 0.10 で変更:The default port is now picked from the
SERVER_NAME
variable.
- secret_key¶
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 the
SECRET_KEY
configuration key. Defaults toNone
.
- select_jinja_autoescape(filename)¶
Returns
True
if autoescaping should be active for the giventemplate name. If no template name is given, returnsTrue.Changelog
バージョン 0.5 で追加.
- propertysend_file_max_age_default:Optional[datetime.timedelta]¶
The default value for
max_age
forsend_file()
. The defaultisNone
, which tells the browser to use conditional requests instead of atimed cache.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Use
app.config["SEND_FILE_MAX_AGE_DEFAULT"]
instead.Changelog
バージョン 2.0 で変更:Defaults to
None
instead of 12 hours.
- send_static_file(filename)¶
The view function used to serve files from
static_folder
. A route is automatically registered forthis view atstatic_url_path
ifstatic_folder
isset.Changelog
バージョン 0.5 で追加.
- propertysession_cookie_name:str¶
The name of the cookie set by the session interface.
バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Use
app.config["SESSION_COOKIE_NAME"]
instead.
- session_interface:flask.sessions.SessionInterface=<flask.sessions.SecureCookieSessionInterfaceobject>¶
the session interface to use. By default an instance of
SecureCookieSessionInterface
is used here.Changelog
バージョン 0.8 で追加.
- shell_context_processor(f)¶
Registers a shell context processor function.
Changelog
バージョン 0.11 で追加.
- パラメータ
f (flask.app.T_shell_context_processor) --
- 戻り値の型
flask.app.T_shell_context_processor
- shell_context_processors:t.List[ft.ShellContextProcessorCallable]¶
A list of shell context processor functions that should be runwhen a shell context is created.
Changelog
バージョン 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 returns
True
then the teardown handlers will not bepassed the error.Changelog
バージョン 0.10 で追加.
- パラメータ
error (Optional[BaseException]) --
- 戻り値の型
- propertystatic_folder:Optional[str]¶
The absolute path to the configured static folder.
None
if no static folder is set.
- propertystatic_url_path:Optional[str]¶
The URL prefix that the static route will be accessible from.
If it was not configured during init, it is derived from
static_folder
.
- teardown_appcontext(f)¶
Registers a function to be called when the applicationcontext is popped. The application context is typically poppedafter the request context for each request, at the end of CLIcommands, or after a manually pushed context ends.
withapp.app_context():...
When the
with
block exits (orctx.pop()
is called), theteardown functions are called just before the app context ismade inactive. Since a request context typically also manages anapplication context it would also be called when you pop arequest context.When a teardown function was called because of an unhandledexception it will be passed an error object. If an
errorhandler()
is registered, it will handle the exceptionand the teardown will not receive it.Teardown functions must avoid raising exceptions. If theyexecute code that might fail they must surround that code with a
try
/except
block and log any errors.The return values of teardown functions are ignored.
Changelog
バージョン 0.9 で追加.
- パラメータ
f (flask.app.T_teardown) --
- 戻り値の型
flask.app.T_teardown
- teardown_appcontext_funcs:t.List[ft.TeardownCallable]¶
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
バージョン 0.9 で追加.
- teardown_request(f)¶
Register a function to be called when the request context ispopped. Typically this happens at the end of each request, butcontexts may be pushed manually as well during testing.
withapp.test_request_context():...
When the
with
block exits (orctx.pop()
is called), theteardown functions are called just before the request context ismade inactive.When a teardown function was called because of an unhandledexception it will be passed an error object. If an
errorhandler()
is registered, it will handle the exceptionand the teardown will not receive it.Teardown functions must avoid raising exceptions. If theyexecute code that might fail they must surround that code with a
try
/except
block and log any errors.The return values of teardown functions are ignored.
- パラメータ
f (flask.scaffold.T_teardown) --
- 戻り値の型
flask.scaffold.T_teardown
- teardown_request_funcs:t.Dict[ft.AppOrBlueprintKey,t.List[ft.TeardownCallable]]¶
A data structure of functions to call at the end of eachrequest even if an exception is raised, in the format
{scope:[functions]}
. Thescope
key is the name of ablueprint the functions are active for, orNone
for allrequests.To register a function, use the
teardown_request()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- template_context_processors:t.Dict[ft.AppOrBlueprintKey,t.List[ft.TemplateContextProcessorCallable]]¶
A data structure of functions to call to pass extra contextvalues when rendering templates, in the format
{scope:[functions]}
. Thescope
key is the name of ablueprint the functions are active for, orNone
for allrequests.To register a function, use the
context_processor()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- 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.template_filter()defreverse(s):returns[::-1]
- template_folder¶
The path to the templates folder, relative to
root_path
, to add to the template loader.None
iftemplates 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.template_global()defdouble(n):return2*n
Changelog
バージョン 0.10 で追加.
- 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.template_test()defis_prime(n):ifn==2:returnTrueforiinrange(2,int(math.ceil(math.sqrt(n)))+1):ifn%i==0:returnFalsereturnTrue
Changelog
バージョン 0.10 で追加.
- propertytemplates_auto_reload:bool¶
Reload templates when they are changed. Used by
create_jinja_environment()
. It is enabled by default in debug mode.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Use
app.config["TEMPLATES_AUTO_RELOAD"]
instead.Changelog
バージョン 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.SeeCLI実行プログラムを使ったコマンドの実行.
Returns an instance of
test_cli_runner_class
, by defaultFlaskCliRunner
. The Flask app object ispassed as the first argument.Changelog
バージョン 1.0 で追加.
- パラメータ
kwargs (Any) --
- 戻り値の型
- test_cli_runner_class:Optional[Type[FlaskCliRunner]]=None¶
The
CliRunner
subclass, by defaultFlaskCliRunner
that is used bytest_cli_runner()
. Its__init__
method should take aFlask app object as the first argument.Changelog
バージョン 1.0 で追加.
- test_client(use_cookies=True,**kwargs)¶
Creates a test client for this application. For informationabout unit testing head over toFlaskアプリケーションのテスト.
Note that if you are testing for assertions or exceptions in yourapplication code, you must set
app.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=Trueclient=app.test_client()
The test client can be used in a
with
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:withapp.test_client()asc:rv=c.get('/?vodka=42')assertrequest.args['vodka']=='42'
Additionally, you may pass optional keyword arguments that will thenbe passed to the application's
test_client_class
constructor.For example:fromflask.testingimportFlaskClientclassCustomClient(FlaskClient):def__init__(self,*args,**kwargs):self._authentication=kwargs.pop("authentication")super(CustomClient,self).__init__(*args,**kwargs)app.test_client_class=CustomClientclient=app.test_client(authentication='Basic ....')
See
FlaskClient
for more information.Changelog
バージョン 0.11 で変更:Added**kwargs to support passing additional keyword arguments tothe constructor of
test_client_class
.バージョン 0.7 で追加:Theuse_cookies parameter was added as well as the abilityto override the client to be used by setting the
test_client_class
attribute.バージョン 0.4 で変更:added support for
with
block usage for the client.- パラメータ
- 戻り値の型
- test_client_class:Optional[Type[FlaskClient]]=None¶
The
test_client()
method creates an instance of this testclient class. Defaults toFlaskClient
.Changelog
バージョン 0.7 で追加.
- test_request_context(*args,**kwargs)¶
Create a
RequestContext
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リクエストのコンテキスト(The Request Context).
Use a
with
block to push the context, which will makerequest
point at the request for the createdenvironment.withtest_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's
EnvironBuilder
, with some defaults fromthe application. See the linked Werkzeug docs for most of theavailable arguments. Flask-specific behavior is listed here.- パラメータ
path -- URL path being requested.
base_url -- Base URL where the app is being served, which
path
is relative to. If not given, built fromPREFERRED_URL_SCHEME
,subdomain
,SERVER_NAME
, andAPPLICATION_ROOT
.subdomain -- Subdomain name to append to
SERVER_NAME
.url_scheme -- Scheme to use instead of
PREFERRED_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 as
data
. Also defaultscontent_type
toapplication/json
.args (Any) -- other positional arguments passed to
EnvironBuilder
.kwargs (Any) -- other keyword arguments passed to
EnvironBuilder
.
- 戻り値の型
- testing¶
The testing flag. Set this to
True
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 the
TESTING
configuration key. Defaults toFalse
.
- trap_http_exception(e)¶
Checks if an HTTP exception should be trapped or not. By defaultthis will return
False
for all exceptions except for a bad requestkey error ifTRAP_BAD_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 returns
True
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
バージョン 1.0 で変更:Bad request errors are not trapped by default in debug mode.
バージョン 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.
- パラメータ
context (dict) -- the context as a dictionary that is updated in placeto add extra variables.
- 戻り値の型
None
- url_build_error_handlers:t.List[t.Callable[[Exception,str,t.Dict[str,t.Any]],str]]¶
A list of functions that are called by
handle_url_build_error()
whenurl_for()
raises aBuildError
. Each function is calledwitherror
,endpoint
andvalues
. If a functionreturnsNone
or raises aBuildError
, it is skipped.Otherwise, its return value is returned byurl_for
.Changelog
バージョン 0.9 で追加.
- url_default_functions:t.Dict[ft.AppOrBlueprintKey,t.List[ft.URLDefaultCallable]]¶
A data structure of functions to call to modify the keywordarguments when generating URLs, in the format
{scope:[functions]}
. Thescope
key is the name of ablueprint the functions are active for, orNone
for allrequests.To register a function, use the
url_defaults()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- 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.
- パラメータ
f (flask.scaffold.T_url_defaults) --
- 戻り値の型
flask.scaffold.T_url_defaults
- url_for(endpoint,*,_anchor=None,_method=None,_scheme=None,_external=None,**values)¶
Generate a URL to the given endpoint with the given values.
This is called by
flask.url_for()
, and can be calleddirectly as well.Anendpoint is the name of a URL rule, usually added with
@app.route()
, and usually the same name as theview function. A route defined in aBlueprint
will prepend the blueprint's name separated by a.
to theendpoint.In some cases, such as email messages, you want URLs to includethe scheme and domain, like
https://example.com/hello
. Whennot in an active request, URLs will be external by default, butthis requires settingSERVER_NAME
so Flask knows whatdomain to use.APPLICATION_ROOT
andPREFERRED_URL_SCHEME
should also be configured asneeded. This config is only used when not in an active request.Functions can be decorated with
url_defaults()
to modifykeyword arguments before the URL is built.If building fails for some reason, such as an unknown endpointor incorrect values, the app's
handle_url_build_error()
method is called. If that returns a string, that is returned,otherwise aBuildError
is raised.- パラメータ
endpoint (str) -- The endpoint name associated with the URL togenerate. If this starts with a
.
, the current blueprintname (if any) will be used._anchor (Optional[str]) -- If given, append this as
#anchor
to the URL._method (Optional[str]) -- If given, generate the URL associated with thismethod for the endpoint.
_scheme (Optional[str]) -- If given, the URL will have this scheme if itis external.
_external (Optional[bool]) -- If given, prefer the URL to be internal(False) or require it to be external (True). External URLsinclude the scheme and domain. When not in an activerequest, URLs are external by default.
values (Any) -- Values to use for the variable parts of the URLrule. Unknown keys are appended as query string arguments,like
?a=b&c=d
.
- 戻り値の型
バージョン 2.2 で追加:Moved from
flask.url_for
, which calls this method.
- url_map¶
The
Map
for this instance. You can usethis to change the routing converters after the class was createdbut before any routes are connected. Example:fromwerkzeug.routingimportBaseConverterclassListConverter(BaseConverter):defto_python(self,value):returnvalue.split(',')defto_url(self,values):return','.join(super(ListConverter,self).to_url(value)forvalueinvalues)app=Flask(__name__)app.url_map.converters['list']=ListConverter
- url_value_preprocessor(f)¶
Register a URL value preprocessor function for all viewfunctions in the application. These functions will be called before the
before_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 in
g
rather than pass it toevery view.The function is passed the endpoint name and values dict. The returnvalue is ignored.
- パラメータ
f (flask.scaffold.T_url_value_preprocessor) --
- 戻り値の型
flask.scaffold.T_url_value_preprocessor
- url_value_preprocessors:t.Dict[ft.AppOrBlueprintKey,t.List[ft.URLValuePreprocessorCallable]]¶
A data structure of functions to call to modify the keywordarguments passed to the view function, in the format
{scope:[functions]}
. Thescope
key is the name of ablueprint the functions are active for, orNone
for allrequests.To register a function, use the
url_value_preprocessor()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- propertyuse_x_sendfile:bool¶
Enable this to use the
X-Sendfile
feature, assuming the server supportsit, fromsend_file()
.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Use
app.config["USE_X_SENDFILE"]
instead.
- view_functions:t.Dict[str,t.Callable]¶
A dictionary mapping endpoint names to view functions.
To register a view function, use the
route()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- wsgi_app(environ,start_response)¶
The actual WSGI application. This is not implemented in
__call__()
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.wsgi_app=MyMiddleware(app.wsgi_app)
Then you still have the original application object around andcan continue to call methods on it.
Changelog
バージョン 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コールバックとエラー.
Blueprint Objects¶
- classflask.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,cli_group=<objectobject>)¶
Represents a blueprint, a collection of routes and otherapp-related functions that can be registered on a real applicationlater.
A blueprint is an object that allows defining application functionswithout requiring an application object ahead of time. It uses thesame decorators as
Flask
, but defers the need for anapplication by recording them for later registration.Decorating a function with a blueprint creates a deferred functionthat is called with
BlueprintSetupState
when the blueprint is registered on an application.SeeBlueprintを使ったアプリケーションのモジュール化 for more information.
- パラメータ
name (str) -- The name of the blueprint. Will be prepended to eachendpoint name.
import_name (str) -- The name of the blueprint package, usually
__name__
. This helps locate theroot_path
for theblueprint.static_folder (Optional[Union[str,os.PathLike]]) -- A folder with static files that should beserved by the blueprint's static route. The path is relative tothe blueprint's root path. Blueprint static files are disabledby default.
static_url_path (Optional[str]) -- The url to serve static files from.Defaults to
static_folder
. If the blueprint does not haveaurl_prefix
, the app's static route will take precedence,and the blueprint's static files won't be accessible.template_folder (Optional[str]) -- A folder with templates that should be addedto the app's template search path. The path is relative to theblueprint's root path. Blueprint templates are disabled bydefault. Blueprint templates have a lower precedence than thosein the app's templates folder.
url_prefix (Optional[str]) -- A path to prepend to all of the blueprint's URLs,to make them distinct from the rest of the app's routes.
subdomain (Optional[str]) -- A subdomain that blueprint routes will match on bydefault.
url_defaults (Optional[dict]) -- A dict of default values that blueprint routeswill receive by default.
root_path (Optional[str]) -- By default, the blueprint will automatically setthis based on
import_name
. In certain situations thisautomatic detection can fail, so the path can be specifiedmanually instead.
Changelog
バージョン 1.1.0 で変更:Blueprints have a
cli
group to register nested CLI commands.Thecli_group
parameter controls the name of the group undertheflask
command.バージョン 0.7 で追加.
- add_app_template_filter(f,name=None)¶
Register a custom template filter, available application wide. Like
Flask.add_template_filter()
but for a blueprint. Works exactlylike theapp_template_filter()
decorator.
- add_app_template_global(f,name=None)¶
Register a custom template global, available application wide. Like
Flask.add_template_global()
but for a blueprint. Works exactlylike theapp_template_global()
decorator.Changelog
バージョン 0.10 で追加.
- add_app_template_test(f,name=None)¶
Register a custom template test, available application wide. Like
Flask.add_template_test()
but for a blueprint. Works exactlylike theapp_template_test()
decorator.Changelog
バージョン 0.10 で追加.
- add_url_rule(rule,endpoint=None,view_func=None,provide_automatic_options=None,**options)¶
Like
Flask.add_url_rule()
but for a blueprint. The endpoint fortheurl_for()
function is prefixed with the name of the blueprint.- パラメータ
rule (str) --
view_func (Optional[Union[Callable[[...],Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],WSGIApplication]],Callable[[...],Awaitable[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],WSGIApplication]]]]]) --
options (Any) --
- 戻り値の型
None
- after_app_request(f)¶
Like
Flask.after_request()
but for a blueprint. Such a functionis executed after each request, even if outside of the blueprint.- パラメータ
f (flask.blueprints.T_after_request) --
- 戻り値の型
flask.blueprints.T_after_request
- after_request(f)¶
Register a function to run after each request to this object.
The function is called with the response object, and must returna response object. This allows the functions to modify orreplace the response before it is sent.
If a function raises an exception, any remaining
after_request
functions will not be called. Therefore, thisshould not be used for actions that must execute, such as toclose resources. Useteardown_request()
for that.- パラメータ
f (flask.scaffold.T_after_request) --
- 戻り値の型
flask.scaffold.T_after_request
- after_request_funcs:Dict[Optional[str],List[Union[Callable[[flask.typing.ResponseClass],flask.typing.ResponseClass],Callable[[flask.typing.ResponseClass],Awaitable[flask.typing.ResponseClass]]]]]¶
A data structure of functions to call at the end of eachrequest, in the format
{scope:[functions]}
. Thescope
key is the name of a blueprint the functions areactive for, orNone
for all requests.To register a function, use the
after_request()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- app_context_processor(f)¶
Like
Flask.context_processor()
but for a blueprint. Such afunction is executed each request, even if outside of the blueprint.- パラメータ
f (flask.blueprints.T_template_context_processor) --
- 戻り値の型
flask.blueprints.T_template_context_processor
- app_errorhandler(code)¶
Like
Flask.errorhandler()
but for a blueprint. Thishandler is used for all requests, even if outside of the blueprint.
- app_template_filter(name=None)¶
Register a custom template filter, available application wide. Like
Flask.template_filter()
but for a blueprint.
- app_template_global(name=None)¶
Register a custom template global, available application wide. Like
Flask.template_global()
but for a blueprint.Changelog
バージョン 0.10 で追加.
- app_template_test(name=None)¶
Register a custom template test, available application wide. Like
Flask.template_test()
but for a blueprint.Changelog
バージョン 0.10 で追加.
- app_url_defaults(f)¶
Same as
url_defaults()
but application wide.- パラメータ
f (flask.blueprints.T_url_defaults) --
- 戻り値の型
flask.blueprints.T_url_defaults
- app_url_value_preprocessor(f)¶
Same as
url_value_preprocessor()
but application wide.- パラメータ
f (flask.blueprints.T_url_value_preprocessor) --
- 戻り値の型
flask.blueprints.T_url_value_preprocessor
- before_app_first_request(f)¶
Like
Flask.before_first_request()
. Such a function isexecuted before the first request to the application.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Run setup code when creatingthe application instead.
- パラメータ
f (flask.blueprints.T_before_first_request) --
- 戻り値の型
flask.blueprints.T_before_first_request
- before_app_request(f)¶
Like
Flask.before_request()
. Such a function is executedbefore each request, even if outside of a blueprint.- パラメータ
f (flask.blueprints.T_before_request) --
- 戻り値の型
flask.blueprints.T_before_request
- before_request(f)¶
Register a function to run before each request.
For example, this can be used to open a database connection, orto load the logged in user from the session.
@app.before_requestdefload_user():if"user_id"insession:g.user=db.session.get(session["user_id"])
The function will be called without any arguments. If it returnsa non-
None
value, the value is handled as if it was thereturn value from the view, and further request handling isstopped.- パラメータ
f (flask.scaffold.T_before_request) --
- 戻り値の型
flask.scaffold.T_before_request
- before_request_funcs:Dict[Optional[str],List[Union[Callable[[],Optional[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],WSGIApplication]]],Callable[[],Awaitable[Optional[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],WSGIApplication]]]]]]]¶
A data structure of functions to call at the beginning ofeach request, in the format
{scope:[functions]}
. Thescope
key is the name of a blueprint the functions areactive for, orNone
for all requests.To register a function, use the
before_request()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- cli¶
The Click command group for registering CLI commands for thisobject. The commands are available from the
flask
commandonce the application has been discovered and blueprints havebeen registered.
- context_processor(f)¶
Registers a template context processor function.
- パラメータ
f (flask.scaffold.T_template_context_processor) --
- 戻り値の型
flask.scaffold.T_template_context_processor
- endpoint(endpoint)¶
Decorate a view function to register it for the givenendpoint. Used if a rule is added without a
view_func
withadd_url_rule()
.app.add_url_rule("/ex",endpoint="example")@app.endpoint("example")defexample():...
- error_handler_spec:Dict[Optional[str],Dict[Optional[int],Dict[Type[Exception],Callable[[Any],Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],WSGIApplication]]]]]¶
A data structure of registered error handlers, in the format
{scope:{code:{class:handler}}}
. Thescope
key isthe name of a blueprint the handlers are active for, orNone
for all requests. Thecode
key is the HTTPstatus code forHTTPException
, orNone
forother exceptions. The innermost dictionary maps exceptionclasses to handler functions.To register an error handler, use the
errorhandler()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- 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)defpage_not_found(error):return'This page does not exist',404
You can also register handlers for arbitrary exceptions:
@app.errorhandler(DatabaseError)defspecial_exception_handler(error):return'Database connection failed',500
Changelog
バージョン 0.7 で追加:Use
register_error_handler()
instead of modifyingerror_handler_spec
directly, for application wide errorhandlers.バージョン 0.7 で追加:One can now additionally also register custom exception typesthat do not necessarily have to be a subclass of the
HTTPException
class.
- get_send_file_max_age(filename)¶
Used by
send_file()
to determine themax_age
cachevalue for a given file path if it wasn't passed.By default, this returns
SEND_FILE_MAX_AGE_DEFAULT
fromthe configuration ofcurrent_app
. This defaultstoNone
, which tells the browser to use conditional requestsinstead of a timed cache, which is usually preferable.Changelog
バージョン 2.0 で変更:The default configuration is
None
instead of 12 hours.バージョン 0.9 で追加.
- propertyhas_static_folder:bool¶
True
ifstatic_folder
is set.Changelog
バージョン 0.5 で追加.
- import_name¶
The name of the package or module that this object belongsto. Do not change this once it is set by the constructor.
- propertyjinja_loader:Optional[jinja2.loaders.FileSystemLoader]¶
The Jinja loader for this object's templates. By default thisis a class
jinja2.loaders.FileSystemLoader
totemplate_folder
if it is set.Changelog
バージョン 0.5 で追加.
- propertyjson_decoder:Optional[Type[json.decoder.JSONDecoder]]¶
Blueprint-local JSON decoder class to use. Set to
None
to use the app's.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Customize
json_provider_class
instead.Changelog
バージョン 0.10 で追加.
- propertyjson_encoder:Optional[Type[json.encoder.JSONEncoder]]¶
Blueprint-local JSON encoder class to use. Set to
None
to use the app's.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Customize
json_provider_class
instead.Changelog
バージョン 0.10 で追加.
- make_setup_state(app,options,first_registration=False)¶
Creates an instance of
BlueprintSetupState()
object that is later passed to the register callback functions.Subclasses can override this to return a subclass of the setup state.- パラメータ
- 戻り値の型
- open_resource(resource,mode='rb')¶
Open a resource file relative to
root_path
forreading.For example, if the file
schema.sql
is next to the fileapp.py
where theFlask
app is defined, it can be openedwith:withapp.open_resource("schema.sql")asf:conn.executescript(f.read())
- record(func)¶
Registers a function that is called when the blueprint isregistered on the application. This function is called with thestate as argument as returned by the
make_setup_state()
method.- パラメータ
func (Callable) --
- 戻り値の型
None
- record_once(func)¶
Works like
record()
but wraps the function in anotherfunction that will ensure the function is only called once. If theblueprint is registered a second time on the application, thefunction passed is not called.- パラメータ
func (Callable) --
- 戻り値の型
None
- register(app,options)¶
Called by
Flask.register_blueprint()
to register allviews and callbacks registered on the blueprint with theapplication. Creates aBlueprintSetupState
and callseachrecord()
callback with it.- パラメータ
app (Flask) -- The application this blueprint is being registeredwith.
options (dict) -- Keyword arguments forwarded from
register_blueprint()
.
- 戻り値の型
None
Changelog
バージョン 2.0.1 で変更:Nested blueprints are registered with their dotted name.This allows different blueprints with the same name to benested at different locations.
バージョン 2.0.1 で変更:The
name
option can be used to change the (pre-dotted)name the blueprint is registered with. This allows the sameblueprint to be registered multiple times with unique namesforurl_for
.バージョン 2.0.1 で変更:Registering the same blueprint with the same name multipletimes is deprecated and will become an error in Flask 2.1.
- register_blueprint(blueprint,**options)¶
Register a
Blueprint
on this blueprint. Keywordarguments passed to this method will override the defaults seton the blueprint.Changelog
バージョン 2.0.1 で変更:The
name
option can be used to change the (pre-dotted)name the blueprint is registered with. This allows the sameblueprint to be registered multiple times with unique namesforurl_for
.バージョン 2.0 で追加.
- パラメータ
blueprint (flask.blueprints.Blueprint) --
options (Any) --
- 戻り値の型
None
- register_error_handler(code_or_exception,f)¶
Alternative error attach function to the
errorhandler()
decorator that is more straightforward to use for non decoratorusage.Changelog
バージョン 0.7 で追加.
- パラメータ
f (Callable[[Any],Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str,...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str,...]]]]]],WSGIApplication]]) --
- 戻り値の型
None
- root_path¶
Absolute path to the package on the filesystem. Used to lookup resources contained in the package.
- route(rule,**options)¶
Decorate a view function to register it with the given URLrule and options. Calls
add_url_rule()
, which has moredetails about the implementation.@app.route("/")defindex():return"Hello, World!"
The endpoint name for the route defaults to the name of the viewfunction if the
endpoint
parameter isn't passed.The
methods
parameter defaults to["GET"]
.HEAD
andOPTIONS
are added automatically.
- send_static_file(filename)¶
The view function used to serve files from
static_folder
. A route is automatically registered forthis view atstatic_url_path
ifstatic_folder
isset.Changelog
バージョン 0.5 で追加.
- propertystatic_folder:Optional[str]¶
The absolute path to the configured static folder.
None
if no static folder is set.
- propertystatic_url_path:Optional[str]¶
The URL prefix that the static route will be accessible from.
If it was not configured during init, it is derived from
static_folder
.
- teardown_app_request(f)¶
Like
Flask.teardown_request()
but for a blueprint. Such afunction is executed when tearing down each request, even if outside ofthe blueprint.- パラメータ
f (flask.blueprints.T_teardown) --
- 戻り値の型
flask.blueprints.T_teardown
- teardown_request(f)¶
Register a function to be called when the request context ispopped. Typically this happens at the end of each request, butcontexts may be pushed manually as well during testing.
withapp.test_request_context():...
When the
with
block exits (orctx.pop()
is called), theteardown functions are called just before the request context ismade inactive.When a teardown function was called because of an unhandledexception it will be passed an error object. If an
errorhandler()
is registered, it will handle the exceptionand the teardown will not receive it.Teardown functions must avoid raising exceptions. If theyexecute code that might fail they must surround that code with a
try
/except
block and log any errors.The return values of teardown functions are ignored.
- パラメータ
f (flask.scaffold.T_teardown) --
- 戻り値の型
flask.scaffold.T_teardown
- teardown_request_funcs:Dict[Optional[str],List[Union[Callable[[Optional[BaseException]],None],Callable[[Optional[BaseException]],Awaitable[None]]]]]¶
A data structure of functions to call at the end of eachrequest even if an exception is raised, in the format
{scope:[functions]}
. Thescope
key is the name of ablueprint the functions are active for, orNone
for allrequests.To register a function, use the
teardown_request()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- template_context_processors:Dict[Optional[str],List[Callable[[],Dict[str,Any]]]]¶
A data structure of functions to call to pass extra contextvalues when rendering templates, in the format
{scope:[functions]}
. Thescope
key is the name of ablueprint the functions are active for, orNone
for allrequests.To register a function, use the
context_processor()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- template_folder¶
The path to the templates folder, relative to
root_path
, to add to the template loader.None
iftemplates should not be added.
- url_default_functions:Dict[Optional[str],List[Callable[[str,dict],None]]]¶
A data structure of functions to call to modify the keywordarguments when generating URLs, in the format
{scope:[functions]}
. Thescope
key is the name of ablueprint the functions are active for, orNone
for allrequests.To register a function, use the
url_defaults()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
- 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.
- パラメータ
f (flask.scaffold.T_url_defaults) --
- 戻り値の型
flask.scaffold.T_url_defaults
- url_value_preprocessor(f)¶
Register a URL value preprocessor function for all viewfunctions in the application. These functions will be called before the
before_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 in
g
rather than pass it toevery view.The function is passed the endpoint name and values dict. The returnvalue is ignored.
- パラメータ
f (flask.scaffold.T_url_value_preprocessor) --
- 戻り値の型
flask.scaffold.T_url_value_preprocessor
- url_value_preprocessors:Dict[Optional[str],List[Callable[[Optional[str],Optional[dict]],None]]]¶
A data structure of functions to call to modify the keywordarguments passed to the view function, in the format
{scope:[functions]}
. Thescope
key is the name of ablueprint the functions are active for, orNone
for allrequests.To register a function, use the
url_value_preprocessor()
decorator.This data structure is internal. It should not be modifieddirectly and its format may change at any time.
Incoming Request Data¶
- classflask.Request(environ,populate_request=True,shallow=False)¶
The request object used by default in Flask. Remembers thematched endpoint and view arguments.
It is what ends up as
request
. If you want to replacethe request object used you can subclass this and setrequest_class
to your subclass.The request object is a
Request
subclass andprovides all of the attributes Werkzeug defines plus a few Flaskspecific ones.- propertyaccept_charsets:werkzeug.datastructures.CharsetAccept¶
List of charsets this client supports as
CharsetAccept
object.
- propertyaccept_encodings:werkzeug.datastructures.Accept¶
List of encodings this client accepts. Encodings in a HTTP termare compression encodings such as gzip. For charsets have a look at
accept_charset
.
- propertyaccept_languages:werkzeug.datastructures.LanguageAccept¶
List of languages this client accepts as
LanguageAccept
object.
- propertyaccept_mimetypes:werkzeug.datastructures.MIMEAccept¶
List of mimetypes this client supports as
MIMEAccept
object.
- access_control_request_headers¶
Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set
access_control_allow_headers
on the response to indicate which headers are allowed.
- access_control_request_method¶
Sent with a preflight request to indicate which method will be used for the cross origin request. Set
access_control_allow_methods
on the response to indicate which methods are allowed.
- propertyaccess_route:List[str]¶
If a forwarded header exists this is a list of all ip addressesfrom the client ip to the last proxy server.
- classmethodapplication(f)¶
Decorate a function as responder that accepts the request asthe last argument. This works like the
responder()
decorator but the function is passed the request object as thelast argument and the request object will be closedautomatically:@Request.applicationdefmy_wsgi_app(request):returnResponse('Hello World!')
As of Werkzeug 0.14 HTTP exceptions are automatically caught andconverted to responses instead of failing.
- propertyargs:MultiDict[str,str]¶
The parsed URL parameters (the part in the URL after the questionmark).
By default an
ImmutableMultiDict
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.
- propertyauthorization:Optional[werkzeug.datastructures.Authorization]¶
TheAuthorization object in parsed form.
- propertyblueprint:Optional[str]¶
The registered name of the current blueprint.
This will be
None
if the endpoint is not part of ablueprint, or if URL matching failed or has not been performedyet.This does not necessarily match the name the blueprint wascreated with. It may have been nested, or registered with adifferent name.
- propertyblueprints:List[str]¶
The registered names of the current blueprint upwards throughparent blueprints.
This will be an empty list if there is no current blueprint, orif URL matching failed.
Changelog
バージョン 2.0.1 で追加.
- propertycache_control:werkzeug.datastructures.RequestCacheControl¶
A
RequestCacheControl
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
バージョン 0.9 で追加.
- 戻り値の型
None
- content_encoding¶
The Content-Encoding entity-header field is used as amodifier to the media-type. When present, its value indicateswhat additional content codings have been applied to theentity-body, and thus what decoding mechanisms must be appliedin order to obtain the media-type referenced by the Content-Typeheader field.
Changelog
バージョン 0.9 で追加.
- propertycontent_length:Optional[int]¶
The Content-Length entity-header field indicates the size of theentity-body in bytes or, in the case of the HEAD method, the size ofthe entity-body that would have been sent had the request been aGET.
- content_md5¶
The Content-MD5 entity-header field, as defined inRFC 1864, is an MD5 digest of the entity-body for the purpose ofproviding an end-to-end message integrity check (MIC) of theentity-body. (Note: a MIC is good for detecting accidentalmodification of the entity-body in transit, but is not proofagainst malicious attacks.)
Changelog
バージョン 0.9 で追加.
- content_type¶
The Content-Type entity-header field indicates the mediatype of the entity-body sent to the recipient or, in the case ofthe HEAD method, the media type that would have been sent hadthe request been a GET.
- propertycookies:ImmutableMultiDict[str,str]¶
A
dict
with the contents of all cookies transmitted withthe request.
- propertydata:bytes¶
Contains the incoming request data as string in case it came witha mimetype Werkzeug does not handle.
- date¶
The Date general-header field represents the date andtime at which the message was originated, having the samesemantics as orig-date in RFC 822.
Changelog
バージョン 2.0 で変更:The datetime object is timezone-aware.
- propertyendpoint:Optional[str]¶
The endpoint that matched the request URL.
This will be
None
if matching failed or has not beenperformed yet.This in combination with
view_args
can be used toreconstruct the same URL or a modified URL.
- environ:WSGIEnvironment¶
The WSGI environment containing HTTP headers and information fromthe WSGI server.
- propertyfiles:ImmutableMultiDict[str,FileStorage]¶
MultiDict
object containingall uploaded files. Each key infiles
is the name from the<inputtype="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 a
save()
function that canstore the file on the filesystem.Note that
files
will only contain data if the request method wasPOST, PUT or PATCH and the<form>
that posted to the request hadenctype="multipart/form-data"
. It will be empty otherwise.See the
MultiDict
/FileStorage
documentation formore details about the used data structure.
- propertyform:ImmutableMultiDict[str,str]¶
The form parameters. By default an
ImmutableMultiDict
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 the
files
attribute.Changelog
バージョン 0.9 で変更:Previous to Werkzeug 0.9 this would only contain form data for POSTand PUT requests.
- classmethodfrom_values(*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 the
EnvironBuilder
.Changelog
バージョン 0.5 で変更:This method now accepts the same arguments as
EnvironBuilder
. Because of this theenviron parameter is now calledenviron_overrides.- 戻り値
request object
- パラメータ
- 戻り値の型
- get_data(cache=True,as_text=False,parse_form_data=False)¶
This reads the buffered incoming data from the client into onebytes object. By default this is cached but that behavior can bechanged by settingcache toFalse.
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 functionsetparse_form_data toTrue. 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.
Ifas_text is set toTrue the return value will be a decodedstring.
Changelog
バージョン 0.9 で追加.
- get_json(force=False,silent=False,cache=True)¶
Parse
data
as JSON.If the mimetype does not indicate JSON(application/json, see
is_json
), or parsingfails,on_json_loading_failed()
is called andits return value is used as the return value. By default thisraises a 400 Bad Request error.- パラメータ
- 戻り値の型
Changelog
バージョン 2.1 で変更:Raise a 400 error if the content type is incorrect.
- headers¶
The headers received with the request.
- propertyhost:str¶
The host name the request was made to, including the port ifit's non-standard. Validated with
trusted_hosts
.
- propertyif_match:werkzeug.datastructures.ETags¶
An object containing all the etags in theIf-Match header.
- 戻り値の型
- propertyif_modified_since:Optional[datetime.datetime]¶
The parsedIf-Modified-Since header as a datetime object.
Changelog
バージョン 2.0 で変更:The datetime object is timezone-aware.
- propertyif_none_match:werkzeug.datastructures.ETags¶
An object containing all the etags in theIf-None-Match header.
- 戻り値の型
- propertyif_range:werkzeug.datastructures.IfRange¶
The parsed
If-Range
header.Changelog
バージョン 2.0 で変更:
IfRange.date
is timezone-aware.バージョン 0.7 で追加.
- propertyif_unmodified_since:Optional[datetime.datetime]¶
The parsedIf-Unmodified-Since header as a datetime object.
Changelog
バージョン 2.0 で変更:The datetime object is timezone-aware.
- input_stream¶
The WSGI input stream.
In general it's a bad idea to use this one because you caneasily read past the boundary. Use the
stream
instead.
- propertyis_json:bool¶
Check if the mimetype indicates JSON data, eitherapplication/json orapplication/*+json.
- is_multiprocess¶
boolean that isTrue if the application is served by aWSGI server that spawns multiple processes.
- is_multithread¶
boolean that isTrue if the application is served by amultithreaded WSGI server.
- is_run_once¶
boolean that isTrue if the application will beexecuted only once in a process lifetime. This is the case forCGI for example, but it's not guaranteed that the execution onlyhappens one time.
- propertyjson:Optional[Any]¶
The parsed JSON data if
mimetype
indicates JSON(application/json, seeis_json
).Calls
get_json()
with default arguments.If the request content type is not
application/json
, thiswill raise a 400 Bad Request error.Changelog
バージョン 2.1 で変更:Raise a 400 error if the content type is incorrect.
- make_form_data_parser()¶
Creates the form data parser. Instantiates the
form_data_parser_class
with some parameters.Changelog
バージョン 0.8 で追加.
- max_forwards¶
The Max-Forwards request-header field provides amechanism with the TRACE and OPTIONS methods to limit the numberof proxies or gateways that can forward the request to the nextinbound server.
- method¶
The method the request was made with, such as
GET
.
- propertymimetype:str¶
Like
content_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'
.
- propertymimetype_params:Dict[str,str]¶
The mimetype parameters as dict. For example if the contenttype is
text/html;charset=utf-8
the params would be{'charset':'utf-8'}
.
- on_json_loading_failed(e)¶
Called if
get_json()
fails and isn't silenced.If this method returns a value, it is used as the return valuefor
get_json()
. The default implementation raisesBadRequest
.- パラメータ
e (Optional[ValueError]) -- If parsing failed, this is the exception. It will be
None
if the content type wasn'tapplication/json
.- 戻り値の型
- origin¶
The host that the request originated from. Set
access_control_allow_origin
on the response to indicate which origins are allowed.
- path¶
The path part of the URL after
root_path
. This is thepath used for routing within the application.
- propertypragma:werkzeug.datastructures.HeaderSet¶
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 part of the URL after the "?". This is the raw value, use
args
for the parsed values.
- propertyrange:Optional[werkzeug.datastructures.Range]¶
The parsedRange header.
Changelog
バージョン 0.7 で追加.
- 戻り値の型
- referrer¶
The Referer[sic] request-header field allows the clientto specify, for the server's benefit, the address (URI) of theresource from which the Request-URI was obtained (the"referrer", although the header field is misspelled).
- remote_addr¶
The address of the client sending the request.
- remote_user¶
If the server supports user authentication, and thescript is protected, this attribute contains the username theuser has authenticated as.
- root_path¶
The prefix that the application is mounted under, without atrailing slash.
path
comes after this.
- propertyroot_url:str¶
The request URL scheme, host, and root path. This is the rootthat the application is accessed from.
- routing_exception:Optional[Exception]=None¶
If matching the URL failed, this is the exception that will beraised / was raised as part of the request handling. This isusually a
NotFound
exception orsomething similar.
- scheme¶
The URL scheme of the protocol the request used, such as
https
orwss
.
- server¶
The address of the server.
(host,port)
,(path,None)
for unix sockets, orNone
if not known.
- shallow:bool¶
Set when creating the request object. If
True
, reading fromthe request body will cause aRuntimeException
. Useful toprevent modifying the stream from middleware.
- propertystream:IO[bytes]¶
If the incoming form data was not encoded with a known mimetypethe data is stored unmodified in this stream for consumption. Mostof the time it is a better idea to use
data
which will giveyou that data as a string. The stream only returns the data once.Unlike
input_stream
this stream is properly guarded that youcan't accidentally read past the length of the input. Werkzeug willinternally always refer to this stream to read data which makes itpossible to wrap this object with a stream that does filtering.Changelog
バージョン 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.
- propertyurl_charset:str¶
The charset that is assumed for URLs. Defaults to the valueof
charset
.Changelog
バージョン 0.6 で追加.
- propertyurl_root:str¶
Alias for
root_url
. The URL with scheme, host, androot path. For example,https://example.com/app/
.
- url_rule:Optional[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
バージョン 0.6 で追加.
- propertyuser_agent:werkzeug.user_agent.UserAgent¶
The user agent. Use
user_agent.string
to get the headervalue. Setuser_agent_class
to a subclass ofUserAgent
to provide parsing forthe other properties or other extended data.Changelog
バージョン 2.0 で変更:The built in parser is deprecated and will be removed inWerkzeug 2.1. A
UserAgent
subclass must be set to parsedata from the string.
- propertyvalues:CombinedMultiDict[str,str]¶
A
werkzeug.datastructures.CombinedMultiDict
thatcombinesargs
andform
.For GET requests, only
args
are present, notform
.Changelog
バージョン 2.0 で変更:For GET requests, only
args
are present, notform
.
- flask.request¶
To access incoming request data, you can use the globalrequestobject. 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プロキシに関する注意事項(Notes On Proxies) for more information.
The request object is an instance of a
Request
.
Response Objects¶
- classflask.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 because
make_response()
will take care of that for you.If you want to replace the response object used you can subclass this andset
response_class
to your subclass.Changelog
バージョン 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.
バージョン 1.0 で変更:Added
max_cookie_size
.- パラメータ
- 戻り値の型
None
- accept_ranges¶
TheAccept-Ranges header. Even though the name wouldindicate that multiple values are supported, it must be onestring token only.
The values
'bytes'
and'none'
are common.Changelog
バージョン 0.7 で追加.
- propertyaccess_control_allow_credentials:bool¶
Whether credentials can be shared by the browser toJavaScript code. As part of the preflight request it indicateswhether credentials can be used on the cross origin request.
- access_control_allow_headers¶
Which headers can be sent with the cross origin request.
- access_control_allow_methods¶
Which methods can be used for the cross origin request.
- access_control_allow_origin¶
The origin or '*' for any origin that may make cross origin requests.
- access_control_expose_headers¶
Which headers can be shared by the browser to JavaScript code.
- access_control_max_age¶
The maximum age in seconds the access control settings can be cached for.
- add_etag(overwrite=False,weak=False)¶
Add an etag for the current response if there is none yet.
Changelog
バージョン 2.0 で変更:SHA-1 is used to generate the value. MD5 may not beavailable in some environments.
- age¶
The Age response-header field conveys the sender'sestimate of the amount of time since the response (or itsrevalidation) was generated at the origin server.
Age values are non-negative decimal integers, representing timein seconds.
- propertyallow:werkzeug.datastructures.HeaderSet¶
The Allow entity-header field lists the set of methodssupported by the resource identified by the Request-URI. Thepurpose of this field is strictly to inform the recipient ofvalid methods associated with the resource. An Allow headerfield MUST be present in a 405 (Method Not Allowed)response.
- propertycache_control:werkzeug.datastructures.ResponseCacheControl¶
The Cache-Control general-header field is used to specifydirectives that MUST be obeyed by all caching mechanisms along therequest/response chain.
- calculate_content_length()¶
Returns the content length if available orNone otherwise.
- call_on_close(func)¶
Adds a function to the internal list of functions that shouldbe called as part of closing down the response. Since 0.7 thisfunction also returns the function that was passed so that thiscan be used as a decorator.
Changelog
バージョン 0.6 で追加.
- close()¶
Close the wrapped response if possible. You can also use the objectin a with statement which will automatically close it.
Changelog
バージョン 0.9 で追加:Can now be used in a with statement.
- 戻り値の型
None
- content_encoding¶
The Content-Encoding entity-header field is used as amodifier to the media-type. When present, its value indicateswhat additional content codings have been applied to theentity-body, and thus what decoding mechanisms must be appliedin order to obtain the media-type referenced by the Content-Typeheader field.
- propertycontent_language:werkzeug.datastructures.HeaderSet¶
The Content-Language entity-header field describes thenatural language(s) of the intended audience for the enclosedentity. Note that this might not be equivalent to all thelanguages used within the entity-body.
- content_length¶
The Content-Length entity-header field indicates the sizeof the entity-body, in decimal number of OCTETs, sent to therecipient or, in the case of the HEAD method, the size of theentity-body that would have been sent had the request been aGET.
- content_location¶
The Content-Location entity-header field MAY be used tosupply the resource location for the entity enclosed in themessage when that entity is accessible from a location separatefrom the requested resource's URI.
- content_md5¶
The Content-MD5 entity-header field, as defined inRFC 1864, is an MD5 digest of the entity-body for the purpose ofproviding an end-to-end message integrity check (MIC) of theentity-body. (Note: a MIC is good for detecting accidentalmodification of the entity-body in transit, but is not proofagainst malicious attacks.)
- propertycontent_range:werkzeug.datastructures.ContentRange¶
The
Content-Range
header as aContentRange
object. Availableeven if the header is not set.Changelog
バージョン 0.7 で追加.
- propertycontent_security_policy:werkzeug.datastructures.ContentSecurityPolicy¶
The
Content-Security-Policy
header as aContentSecurityPolicy
object. Availableeven if the header is not set.The Content-Security-Policy header adds an additional layer ofsecurity to help detect and mitigate certain types of attacks.
- propertycontent_security_policy_report_only:werkzeug.datastructures.ContentSecurityPolicy¶
The
Content-Security-policy-report-only
header as aContentSecurityPolicy
object. Availableeven if the header is not set.The Content-Security-Policy-Report-Only header adds a csp policythat is not enforced but is reported thereby helping detectcertain types of attacks.
- content_type¶
The Content-Type entity-header field indicates the mediatype of the entity-body sent to the recipient or, in the case ofthe HEAD method, the media type that would have been sent hadthe request been a GET.
- cross_origin_embedder_policy¶
Prevents a document from loading any cross-origin resources that do notexplicitly grant the document permission. Values must be a member of the
werkzeug.http.COEP
enum.
- cross_origin_opener_policy¶
Allows control over sharing of browsing context group with cross-origindocuments. Values must be a member of the
werkzeug.http.COOP
enum.
- propertydata:Union[bytes,str]¶
A descriptor that calls
get_data()
andset_data()
.
- date¶
The Date general-header field represents the date andtime at which the message was originated, having the samesemantics as orig-date in RFC 822.
Changelog
バージョン 2.0 で変更:The datetime object is timezone-aware.
- delete_cookie(key,path='/',domain=None,secure=False,httponly=False,samesite=None)¶
Delete a cookie. Fails silently if key doesn't exist.
- パラメータ
key (str) -- the key (name) of the cookie to be deleted.
path (str) -- if the cookie that should be deleted was limited to apath, the path has to be defined here.
domain (Optional[str]) -- if the cookie that should be deleted was limited to adomain, that domain has to be defined here.
secure (bool) -- If
True
, the cookie will only be availablevia HTTPS.httponly (bool) -- Disallow JavaScript access to the cookie.
samesite (Optional[str]) -- Limit the scope of the cookie to only beattached to requests that are "same-site".
- 戻り値の型
None
- direct_passthrough¶
Pass the response body directly through as the WSGI iterable.This can be used when the body is a binary file or otheriterator of bytes, to skip some unnecessary checks. Use
send_file()
instead of setting thismanually.
- expires¶
The Expires entity-header field gives the date/time afterwhich the response is considered stale. A stale cache entry maynot normally be returned by a cache.
Changelog
バージョン 2.0 で変更:The datetime object is timezone-aware.
- classmethodforce_type(response,environ=None)¶
Enforce that the WSGI response is a response object of the currenttype. Werkzeug will use the
Response
internally in manysituations like the exceptions. If you callget_response()
on anexception you will get back a regularResponse
object, evenif you are using a custom subclass.This method can enforce a given response type, and it will alsoconvert arbitrary WSGI callables into response objects if an environis provided:
# convert a Werkzeug response object into an instance of the# MyResponseClass subclass.response=MyResponseClass.force_type(response)# convert any WSGI application into a response objectresponse=MyResponseClass.force_type(response,environ)
This is especially useful if you want to post-process responses inthe main dispatcher and use functionality provided by your subclass.
Keep in mind that this will modify response objects in place ifpossible!
- freeze()¶
Make the response object ready to be pickled. Does thefollowing:
Buffer the response into a list, ignoring
implicity_sequence_conversion
anddirect_passthrough
.Set the
Content-Length
header.Generate an
ETag
header if one is not already set.
Changelog
バージョン 2.1 で変更:Removed the
no_etag
parameter.バージョン 2.0 で変更:An
ETag
header is added, theno_etag
parameter isdeprecated and will be removed in Werkzeug 2.1.バージョン 0.6 で変更:The
Content-Length
header is set.- 戻り値の型
None
- classmethodfrom_app(app,environ,buffered=False)¶
Create a new response object from an application output. Thisworks best if you pass it an application that returns a generator allthe time. Sometimes applications may use thewrite() callablereturned by thestart_response function. This tries to resolve suchedge cases automatically. But if you don't get the expected outputyou should setbuffered toTrue which enforces buffering.
- get_app_iter(environ)¶
Returns the application iterator for the given environ. Dependingon the request method and the current status code the return valuemight be an empty response rather than the one from the response.
If the request method isHEAD or the status code is in a rangewhere the HTTP specification requires an empty response, an emptyiterable is returned.
Changelog
バージョン 0.6 で追加.
- get_data(as_text=False)¶
The string representation of the response body. Whenever you callthis property the response iterable is encoded and flattened. Thiscan lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting
implicit_sequence_conversion
toFalse.Ifas_text is set toTrue the return value will be a decodedstring.
Changelog
バージョン 0.9 で追加.
- get_etag()¶
Return a tuple in the form
(etag,is_weak)
. If there is noETag the return value is(None,None)
.
- get_json(force=False,silent=False)¶
Parse
data
as JSON. Useful during testing.If the mimetype does not indicate JSON(application/json, see
is_json
), thisreturnsNone
.Unlike
Request.get_json()
, the result is not cached.
- get_wsgi_headers(environ)¶
This is automatically called right before the response is startedand returns headers modified for the given environment. It returns acopy of the headers from the response with some modifications appliedif necessary.
For example the location header (if present) is joined with the rootURL of the environment. Also the content length is automatically setto zero here for certain status codes.
Changelog
バージョン 0.6 で変更:Previously that function was calledfix_headers and modifiedthe response object in place. Also since 0.6, IRIs in locationand content-location headers are handled properly.
Also starting with 0.6, Werkzeug will attempt to set the contentlength if it is able to figure it out on its own. This is thecase if all the strings in the response iterable are alreadyencoded and the iterable is buffered.
- パラメータ
environ (WSGIEnvironment) -- the WSGI environment of the request.
- 戻り値
returns a new
Headers
object.- 戻り値の型
- get_wsgi_response(environ)¶
Returns the final WSGI response as tuple. The first item inthe tuple is the application iterator, the second the status andthe third the list of headers. The response returned is createdspecially for the given environment. For example if the requestmethod in the WSGI environment is
'HEAD'
the response willbe empty and only the headers and status code will be present.Changelog
バージョン 0.6 で追加.
- propertyis_json:bool¶
Check if the mimetype indicates JSON data, eitherapplication/json orapplication/*+json.
- propertyis_sequence:bool¶
If the iterator is buffered, this property will beTrue. Aresponse object will consider an iterator to be buffered if theresponse attribute is a list or tuple.
Changelog
バージョン 0.6 で追加.
- propertyis_streamed:bool¶
If the response is streamed (the response is not an iterable witha length information) this property isTrue. In this case streamedmeans that there is no information about the number of iterations.This is usuallyTrue if a generator is passed to the response object.
This is useful for checking before applying some sort of postfiltering that should not take place for streamed responses.
- iter_encoded()¶
Iter the response encoded with the encoding of the response.If the response object is invoked as WSGI application the returnvalue of this method is used as application iterator unless
direct_passthrough
was activated.
- propertyjson:Optional[Any]¶
The parsed JSON data if
mimetype
indicates JSON(application/json, seeis_json
).Calls
get_json()
with default arguments.
- last_modified¶
The Last-Modified entity-header field indicates the dateand time at which the origin server believes the variant waslast modified.
Changelog
バージョン 2.0 で変更:The datetime object is timezone-aware.
- location¶
The Location response-header field is used to redirectthe recipient to a location other than the Request-URI forcompletion of the request or identification of a newresource.
- make_conditional(request_or_environ,accept_ranges=False,complete_length=None)¶
Make the response conditional to the request. This method worksbest if an etag was defined for the response already. Theadd_etagmethod can be used to do that. If called without etag just the dateheader is set.
This does nothing if the request method in the request or environ isanything but GET or HEAD.
For optimal performance when handling range requests, it's recommendedthat your response data object implementsseekable,seek andtellmethods as described by
io.IOBase
. Objects returned bywrap_file()
automatically implement those methods.It does not remove the body of the response because that's somethingthe
__call__()
function does for us automatically.Returns self so that you can do
returnresp.make_conditional(req)
but modifies the object in-place.- パラメータ
request_or_environ (Union[WSGIEnvironment,Request]) -- a request object or WSGI environment to beused to make the response conditionalagainst.
accept_ranges (Union[bool,str]) -- This parameter dictates the value ofAccept-Ranges header. If
False
(default),the header is not set. IfTrue
, it will be setto"bytes"
. IfNone
, it will be set to"none"
. If it's a string, it will use thisvalue.complete_length (Optional[int]) -- Will be used only in valid Range Requests.It will setContent-Range complete lengthvalue and computeContent-Length real value.This parameter is mandatory for successfulRange Requests completion.
- Raises
RequestedRangeNotSatisfiable
ifRange header could not be parsed or satisfied.- 戻り値の型
Changelog
バージョン 2.0 で変更:Range processing is skipped if length is 0 instead ofraising a 416 Range Not Satisfiable error.
- make_sequence()¶
Converts the response iterator in a list. By default this happensautomatically if required. Ifimplicit_sequence_conversion isdisabled, this method is not automatically called and some propertiesmight raise exceptions. This also encodes all the items.
Changelog
バージョン 0.6 で追加.
- 戻り値の型
None
- propertymax_cookie_size:int¶
Read-only view of the
MAX_COOKIE_SIZE
config key.See
max_cookie_size
inWerkzeug's docs.
- propertymimetype_params:Dict[str,str]¶
The mimetype parameters as dict. For example if thecontent type is
text/html;charset=utf-8
the params would be{'charset':'utf-8'}
.Changelog
バージョン 0.5 で追加.
- propertyretry_after:Optional[datetime.datetime]¶
The Retry-After response-header field can be used with a503 (Service Unavailable) response to indicate how long theservice is expected to be unavailable to the requesting client.
Time in seconds until expiration or date.
Changelog
バージョン 2.0 で変更:The datetime object is timezone-aware.
- set_cookie(key,value='',max_age=None,expires=None,path='/',domain=None,secure=False,httponly=False,samesite=None)¶
Sets a cookie.
A warning is raised if the size of the cookie header exceeds
max_cookie_size
, but the header will still be set.- パラメータ
key (str) -- the key (name) of the cookie to be set.
value (str) -- the value of the cookie.
max_age (Optional[Union[datetime.timedelta,int]]) -- should be a number of seconds, orNone (default) ifthe cookie should last only as long as the client'sbrowser session.
expires (Optional[Union[str,datetime.datetime,int,float]]) -- should be adatetime object or UNIX timestamp.
path (Optional[str]) -- limits the cookie to a given path, per default it willspan the whole domain.
domain (Optional[str]) -- if you want to set a cross-domain cookie. For example,
domain=".example.com"
will set a cookie that isreadable by the domainwww.example.com
,foo.example.com
etc. Otherwise, a cookie will onlybe readable by the domain that set it.secure (bool) -- If
True
, the cookie will only be availablevia HTTPS.httponly (bool) -- Disallow JavaScript access to the cookie.
samesite (Optional[str]) -- Limit the scope of the cookie to only beattached to requests that are "same-site".
- 戻り値の型
None
- set_data(value)¶
Sets a new string as response. The value must be a string orbytes. If a string is set it's encoded to the charset of theresponse (utf-8 by default).
Changelog
バージョン 0.9 で追加.
- set_etag(etag,weak=False)¶
Set the etag, and override the old one if there was one.
- propertystream:werkzeug.wrappers.response.ResponseStream¶
The response iterable as write-only stream.
- propertyvary:werkzeug.datastructures.HeaderSet¶
The Vary field value indicates the set of request-headerfields that fully determines, while the response is fresh,whether a cache is permitted to use the response to reply to asubsequent request without revalidation.
- propertywww_authenticate:werkzeug.datastructures.WWWAuthenticate¶
The
WWW-Authenticate
header in a parsed form.
Sessions¶
If you have setFlask.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 thesession
object:
- classflask.session¶
The session object works pretty much like an ordinary dict, with thedifference that it keeps track of modifications.
This is a proxy. Seeプロキシに関する注意事項(Notes On Proxies) for more information.
The following attributes are interesting:
- new¶
True
if the session is new,False
otherwise.
- modified¶
True
if the session object detected a modification. Be 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 yourselfsession.modified=True
- permanent¶
If set to
True
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
バージョン 0.8 で追加.
The session interface provides a simple way to replace the sessionimplementation that Flask is using.
- classflask.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 are
open_session()
andsave_session()
, the others haveuseful defaults which you don't need to change.The session object returned by the
open_session()
method has toprovide a dictionary like interface plus the properties and methodsfrom theSessionMixin
. We recommend just subclassing a dictand adding that mixin:classSession(dict,SessionMixin):pass
If
open_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 assign
flask.Flask.session_interface
:app=Flask(__name__)app.session_interface=MySessionInterface()
Multiple requests with the same session may be sent and handledconcurrently. When implementing a new session interface, considerwhether reads or writes to the backing store must be synchronized.There is no guarantee on the order in which the session for eachrequest is opened or saved, it will occur in the order that requestsbegin and end processing.
Changelog
バージョン 0.8 で追加.
- get_cookie_domain(app)¶
Returns the domain that should be set for the session cookie.
Uses
SESSION_COOKIE_DOMAIN
if it is configured, 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.
- get_cookie_httponly(app)¶
Returns True if the session cookie should be httponly. Thiscurrently just returns the value of the
SESSION_COOKIE_HTTPONLY
config var.
- get_cookie_name(app)¶
The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``.
- get_cookie_path(app)¶
Returns the path for which the cookie should be valid. Thedefault implementation uses the value from the
SESSION_COOKIE_PATH
config var if it's set, and falls back toAPPLICATION_ROOT
oruses/
if it'sNone
.
- get_cookie_samesite(app)¶
Return
'Strict'
or'Lax'
if the cookie should use theSameSite
attribute. This currently just returns the value oftheSESSION_COOKIE_SAMESITE
setting.
- get_cookie_secure(app)¶
Returns True if the cookie should be secure. This currentlyjust returns the value of the
SESSION_COOKIE_SECURE
setting.
- get_expiration_time(app,session)¶
A helper method that returns an expiration date for the sessionor
None
if the session is linked to the browser session. Thedefault implementation returns now + the permanent sessionlifetime configured on the application.- パラメータ
app (Flask) --
session (flask.sessions.SessionMixin) --
- 戻り値の型
- is_null_session(obj)¶
Checks if a given object is a null session. Null sessions arenot asked to be saved.
This checks if the object is an instance of
null_session_class
by default.
- make_null_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 of
null_session_class
by default.- パラメータ
app (Flask) --
- 戻り値の型
- null_session_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.:py:class:`flask.sessions.NullSession`の別名です。
- open_session(app,request)¶
This is called at the beginning of each request, afterpushing the request context, before matching the URL.
This must return an object which implements a dictionary-likeinterface as well as the
SessionMixin
interface.This will return
None
to indicate that loading failed insome way that is not immediately an error. The requestcontext will fall back to usingmake_null_session()
in this case.- パラメータ
- 戻り値の型
- pickle_based=False¶
A flag that indicates if the session interface is pickle based.This can be used by Flask extensions to make a decision in regardsto how to deal with the session object.
Changelog
バージョン 0.10 で追加.
- save_session(app,session,response)¶
This is called at the end of each request, after generatinga response, before removing the request context. It is skippedif
is_null_session()
returnsTrue
.- パラメータ
app (Flask) --
session (flask.sessions.SessionMixin) --
response (Response) --
- 戻り値の型
None
- should_set_cookie(app,session)¶
Used by session backends to determine if a
Set-Cookie
headershould be set for this session cookie for this response. If the sessionhas been modified, the cookie is set. If the session is permanent andtheSESSION_REFRESH_EACH_REQUEST
config is true, the cookie isalways set.This check is usually skipped if the session was deleted.
Changelog
バージョン 0.11 で追加.
- パラメータ
app (Flask) --
session (flask.sessions.SessionMixin) --
- 戻り値の型
- classflask.sessions.SecureCookieSessionInterface¶
The default session interface that stores sessions in signed cookiesthrough the
itsdangerous
module.- staticdigest_method()¶
the hash function to use for the signature. The default is sha1
- key_derivation='hmac'¶
the name of the itsdangerous supported key derivation. The defaultis hmac.
- open_session(app,request)¶
This is called at the beginning of each request, afterpushing the request context, before matching the URL.
This must return an object which implements a dictionary-likeinterface as well as the
SessionMixin
interface.This will return
None
to indicate that loading failed insome way that is not immediately an error. The requestcontext will fall back to usingmake_null_session()
in this case.- パラメータ
- 戻り値の型
- salt='cookie-session'¶
the salt that should be applied on top of the secret key for thesigning of cookie based sessions.
- save_session(app,session,response)¶
This is called at the end of each request, after generatinga response, before removing the request context. It is skippedif
is_null_session()
returnsTrue
.- パラメータ
app (Flask) --
session (flask.sessions.SessionMixin) --
response (Response) --
- 戻り値の型
None
- serializer=<flask.json.tag.TaggedJSONSerializerobject>¶
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.
- classflask.sessions.SecureCookieSession(initial=None)¶
Base class for sessions based on signed cookies.
This session backend will set the
modified
andaccessed
attributes. It cannot reliably track whether asession is new (vs. empty), sonew
remains hard coded toFalse
.- パラメータ
initial (Any) --
- 戻り値の型
None
- accessed=False¶
header, which allows caching proxies to cache different pages fordifferent users.
- get(key,default=None)¶
Return the value for key if key is in the dictionary, else default.
- modified=False¶
When data is changed, this is set to
True
. Only the sessiondictionary itself is tracked; if the session contains mutabledata (for example a nested dict) then this must be set toTrue
manually when modifying that data. The session cookiewill only be written to the response if this isTrue
.
- classflask.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.
- パラメータ
initial (Any) --
- 戻り値の型
None
- pop(k[,d])→v,removespecifiedkeyandreturnthecorrespondingvalue.¶
If key is not found, d is returned if given, otherwise KeyError is raised
- popitem()→(k,v),removeandreturnsome(key,value)pairasa¶
2-tuple; but raise KeyError if D is empty.
- setdefault(*args,**kwargs)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E,]**F)→None. UpdateDfromdict/iterableEandF.¶
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = vIn either case, this is followed by: for k in F: D[k] = F[k]
- classflask.sessions.SessionMixin¶
Expands a basic dictionary with session attributes.
- accessed=True¶
Some implementations can detect when session data is read orwritten and set this when that happens. The mixin default is hardcoded to
True
.
- modified=True¶
Some implementations can detect changes to the session and setthis when that happens. The mixin default is hard coded to
True
.
Notice
ThePERMANENT_SESSION_LIFETIME
config can be an integer ortimedelta
.Thepermanent_session_lifetime
attribute is always atimedelta
.
Test Client¶
- classflask.testing.FlaskClient(*args,**kwargs)¶
Works like a regular Werkzeug test client but has knowledge aboutFlask's contexts to defer the cleanup of the request context untilthe end of a
with
block. For general information about how touse this class refer towerkzeug.test.Client
.Changelog
バージョン 0.12 で変更:app.test_client() includes preset default environment, which can beset after instantiation of theapp.test_client() object inclient.environ_base.
Basic usage is outlined in theFlaskアプリケーションのテスト chapter.
- open(*args,buffered=False,follow_redirects=False,**kwargs)¶
Generate an environ dict from the given arguments, make arequest to the application using it, and return the response.
- パラメータ
args (Any) -- Passed to
EnvironBuilder
to create theenviron for the request. If a single arg is passed, it canbe an existingEnvironBuilder
or an environ dict.buffered (bool) -- Convert the iterator returned by the app intoa list. If the iterator has a
close()
method, it iscalled automatically.follow_redirects (bool) -- Make additional requests to follow HTTPredirects until a non-redirect status is returned.
TestResponse.history
lists the intermediateresponses.kwargs (Any) --
- 戻り値の型
TestResponse
Changelog
バージョン 2.1 で変更:Removed the
as_tuple
parameter.バージョン 2.0 で変更:
as_tuple
is deprecated and will be removed in Werkzeug2.1. UseTestResponse.request
andrequest.environ
instead.バージョン 2.0 で変更:The request input stream is closed when calling
response.close()
. Input streams for redirects areautomatically closed.バージョン 0.5 で変更:If a dict is provided as file in the dict for the
data
parameter the content type has to be calledcontent_type
instead ofmimetype
. This change was made forconsistency withwerkzeug.FileWrapper
.バージョン 0.5 で変更:Added the
follow_redirects
parameter.
- session_transaction(*args,**kwargs)¶
When used in combination with a
with
statement this opens asession transaction. This can be used to modify the session thatthe test client uses. Once thewith
block is left the session isstored back.withclient.session_transaction()assession: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 as
test_request_context()
which are directlypassed through.- パラメータ
- 戻り値の型
Generator[flask.sessions.SessionMixin, None, None]
Test CLI Runner¶
- classflask.testing.FlaskCliRunner(app,**kwargs)¶
A
CliRunner
for testing a Flask app'sCLI commands. Typically created usingtest_cli_runner()
. SeeCLI実行プログラムを使ったコマンドの実行.- invoke(cli=None,args=None,**kwargs)¶
Invokes a CLI command in an isolated environment. See
CliRunner.invoke
forfull method documentation. SeeCLI実行プログラムを使ったコマンドの実行 for examples.If the
obj
argument is not given, passes an instance ofScriptInfo
that knows how to load the Flaskapp being tested.
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 forrequest
andsession
.
- flask.g¶
A namespace object that can store data during anapplication context. This is an instance of
Flask.app_ctx_globals_class
, which defaults toctx._AppCtxGlobals
.This is a good place to store resources during a request. Forexample, a
before_request
function could load a user object froma session id, then setg.user
to be used in the view function.This is a proxy. Seeプロキシに関する注意事項(Notes On Proxies) for more information.
Changelog
バージョン 0.10 で変更:Bound to the application context instead of the request context.
- classflask.ctx._AppCtxGlobals¶
A plain object. Used as a namespace for storing data during anapplication context.
Creating an app context automatically creates this object, which ismade available as the
g
proxy.- 'key'ing
Check whether an attribute is present.
Changelog
バージョン 0.10 で追加.
- iter(g)
Return an iterator over the attribute names.
Changelog
バージョン 0.10 で追加.
- get(name,default=None)¶
Get an attribute by name, or a default value. Like
dict.get()
.- パラメータ
- 戻り値の型
Changelog
バージョン 0.10 で追加.
- pop(name,default=<objectobject>)¶
Get and remove an attribute by name. Like
dict.pop()
.- パラメータ
- 戻り値の型
Changelog
バージョン 0.11 で追加.
Useful Functions and Classes¶
- flask.current_app¶
A proxy to the application handling the current request. This isuseful to access the application without needing to import it, or ifit can't be imported, such as when using the application factorypattern or in blueprints and extensions.
This is only available when anapplication context is pushed. This happensautomatically during requests and CLI commands. It can be controlledmanually with
app_context()
.This is a proxy. Seeプロキシに関する注意事項(Notes On Proxies) for more information.
- flask.has_request_context()¶
If you have code that wants to test if a request context is there ornot this function can be used. For instance, you may want to take advantageof request information if the request object is available, but failsilently if it is unavailable.
classUser(db.Model):def__init__(self,username,remote_addr=None):self.username=usernameifremote_addrisNoneandhas_request_context():remote_addr=request.remote_addrself.remote_addr=remote_addr
Alternatively you can also just test any of the context bound objects(such as
request
org
) for truthness:classUser(db.Model):def__init__(self,username,remote_addr=None):self.username=usernameifremote_addrisNoneandrequest:remote_addr=request.remote_addrself.remote_addr=remote_addr
Changelog
バージョン 0.7 で追加.
- 戻り値の型
- 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. The current session is alsoincluded in the copied request context.
Example:
importgeventfromflaskimportcopy_current_request_context@app.route('/')defindex():@copy_current_request_contextdefdo_some_work():# do some work here, it can access flask.request or# flask.session like you would otherwise in the view function....gevent.spawn(do_some_work)return'Regular response'
Changelog
バージョン 0.10 で追加.
- flask.has_app_context()¶
Works like
has_request_context()
but for the applicationcontext. You can also just do a boolean check on thecurrent_app
object instead.Changelog
バージョン 0.9 で追加.
- 戻り値の型
- flask.url_for(endpoint,*,_anchor=None,_method=None,_scheme=None,_external=None,**values)¶
Generate a URL to the given endpoint with the given values.
This requires an active request or application context, and calls
current_app.url_for()
. See that methodfor full documentation.- パラメータ
endpoint (str) -- The endpoint name associated with the URL togenerate. If this starts with a
.
, the current blueprintname (if any) will be used._anchor (Optional[str]) -- If given, append this as
#anchor
to the URL._method (Optional[str]) -- If given, generate the URL associated with thismethod for the endpoint.
_scheme (Optional[str]) -- If given, the URL will have this scheme if it isexternal.
_external (Optional[bool]) -- If given, prefer the URL to be internal (False) orrequire it to be external (True). External URLs include thescheme and domain. When not in an active request, URLs areexternal by default.
values (Any) -- Values to use for the variable parts of the URL rule.Unknown keys are appended as query string arguments, like
?a=b&c=d
.
- 戻り値の型
バージョン 2.2 で変更:Calls
current_app.url_for
, allowing an app to override thebehavior.Changelog
バージョン 0.10 で変更:The
_scheme
parameter was added.バージョン 0.9 で変更:The
_anchor
and_method
parameters were added.バージョン 0.9 で変更:Calls
app.handle_url_build_error
on build errors.
- flask.abort(code,*args,**kwargs)¶
Raise an
HTTPException
for the givenstatus code.If
current_app
is available, it will call itsaborter
object, otherwise it will usewerkzeug.exceptions.abort()
.- パラメータ
- 戻り値の型
te.NoReturn
バージョン 2.2 で追加:Calls
current_app.aborter
if available instead of alwaysusing Werkzeug's defaultabort
.
- flask.redirect(location,code=302,Response=None)¶
Create a redirect response object.
If
current_app
is available, it will use itsredirect()
method, otherwise it will usewerkzeug.utils.redirect()
.- パラメータ
- 戻り値の型
BaseResponse
バージョン 2.2 で追加:Calls
current_app.redirect
if available instead of alwaysusing Werkzeug's defaultredirect
.
- flask.make_response(*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:
defindex():returnrender_template('index.html',foo=42)
You can now do something like this:
defindex():response=make_response(render_template('index.html',foo=42))response.headers['X-Parachutes']='parachutes are cool'returnresponse
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
バージョン 0.6 で追加.
- 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('/')defindex():@after_this_requestdefadd_header(response):response.headers['X-Foo']='Parachute'returnresponsereturn'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
バージョン 0.9 で追加.
- パラメータ
f (Union[Callable[[flask.typing.ResponseClass],flask.typing.ResponseClass],Callable[[flask.typing.ResponseClass],Awaitable[flask.typing.ResponseClass]]]) --
- 戻り値の型
Union[Callable[[flask.typing.ResponseClass], flask.typing.ResponseClass],Callable[[flask.typing.ResponseClass],Awaitable[flask.typing.ResponseClass]]]
- flask.send_file(path_or_file,mimetype=None,as_attachment=False,download_name=None,conditional=True,etag=True,last_modified=None,max_age=None)¶
Send the contents of a file to the client.
The first argument can be a file path or a file-like object. Pathsare preferred in most cases because Werkzeug can manage the file andget extra information from the path. Passing a file-like objectrequires that the file is opened in binary mode, and is mostlyuseful when building a file in memory with
io.BytesIO
.Never pass file paths provided by a user. The path is assumed to betrusted, so a user could craft a path to access a file you didn'tintend. Use
send_from_directory()
to safely serveuser-requested paths from within a directory.If the WSGI server sets a
file_wrapper
inenviron
, it isused, otherwise Werkzeug's built-in wrapper is used. Alternatively,if the HTTP server supportsX-Sendfile
, configuring Flask withUSE_X_SENDFILE=True
will tell the server to send the givenpath, which is much more efficient than reading it in Python.- パラメータ
path_or_file (Union[os.PathLike,str,BinaryIO]) -- The path to the file to send, relative to thecurrent working directory if a relative path is given.Alternatively, a file-like object opened in binary mode. Makesure the file pointer is seeked to the start of the data.
mimetype (Optional[str]) -- The MIME type to send for the file. If notprovided, it will try to detect it from the file name.
as_attachment (bool) -- Indicate to a browser that it should offer tosave the file instead of displaying it.
download_name (Optional[str]) -- The default name browsers will use when savingthe file. Defaults to the passed file name.
conditional (bool) -- Enable conditional and range responses based onrequest headers. Requires passing a file path and
environ
.etag (Union[bool,str]) -- Calculate an ETag for the file, which requires passinga file path. Can also be a string to use instead.
last_modified (Optional[Union[datetime.datetime,int,float]]) -- The last modified time to send for the file,in seconds. If not provided, it will try to detect it from thefile path.
max_age (Optional[Union[int,Callable[[Optional[str]],Optional[int]]]]) -- How long the client should cache the file, inseconds. If set,
Cache-Control
will bepublic
, otherwiseit will beno-cache
to prefer conditional caching.
- 戻り値の型
Changelog
バージョン 2.0 で変更:
download_name
replaces theattachment_filename
parameter. Ifas_attachment=False
, it is passed withContent-Disposition:inline
instead.バージョン 2.0 で変更:
max_age
replaces thecache_timeout
parameter.conditional
is enabled andmax_age
is not set bydefault.バージョン 2.0 で変更:
etag
replaces theadd_etags
parameter. It can be astring to use instead of generating one.バージョン 2.0 で変更:Passing a file-like object that inherits from
TextIOBase
will raise aValueError
ratherthan sending an empty file.バージョン 2.0 で追加:Moved the implementation to Werkzeug. This is now a wrapper topass some Flask-specific arguments.
バージョン 1.1 で変更:
filename
may be aPathLike
object.バージョン 1.1 で変更:Passing a
BytesIO
object supports range requests.バージョン 1.0.3 で変更:Filenames are encoded with ASCII instead of Latin-1 for broadercompatibility with WSGI servers.
バージョン 1.0 で変更:UTF-8 filenames as specified inRFC 2231 are supported.
バージョン 0.12 で変更:The filename is no longer automatically inferred from fileobjects. If you want to use automatic MIME and etag support,pass a filename via
filename_or_fp
orattachment_filename
.バージョン 0.12 で変更:
attachment_filename
is preferred overfilename
for MIMEdetection.バージョン 0.9 で変更:
cache_timeout
defaults toFlask.get_send_file_max_age()
.バージョン 0.7 で変更:MIME guessing and etag support for file-like objects wasdeprecated because it was unreliable. Pass a filename if you areable to, otherwise attach an etag yourself.
バージョン 0.5 で変更:The
add_etags
,cache_timeout
andconditional
parameters were added. The default behavior is to add etags.バージョン 0.2 で追加.
- flask.send_from_directory(directory,path,**kwargs)¶
Send a file from within a directory using
send_file()
.@app.route("/uploads/<path:name>")defdownload_file(name):returnsend_from_directory(app.config['UPLOAD_FOLDER'],name,as_attachment=True)
This is a secure way to serve files from a folder, such as staticfiles or uploads. Uses
safe_join()
toensure the path coming from the client is not maliciously crafted topoint outside the specified directory.If the final path does not point to an existing regular file,raises a 404
NotFound
error.- パラメータ
directory (Union[os.PathLike,str]) -- The directory that
path
must be located under,relative to the current application's root path.path (Union[os.PathLike,str]) -- The path to the file to send, relative to
directory
.kwargs (Any) -- Arguments to pass to
send_file()
.
- 戻り値の型
Changelog
バージョン 2.0 で変更:
path
replaces thefilename
parameter.バージョン 2.0 で追加:Moved the implementation to Werkzeug. This is now a wrapper topass some Flask-specific arguments.
バージョン 0.5 で追加.
- flask.escape()¶
Replace the characters
&
,<
,>
,'
, and"
in the string with HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML.If the object has an
__html__
method, it is called and the return value is assumed to already be safe for HTML.- パラメータ
s -- An object to be converted to a string and escaped.
- 戻り値
A
Markup
string with the escaped text.
- classflask.Markup(base='',encoding=None,errors='strict')¶
A string that is ready to be safely inserted into an HTML or XMLdocument, either because it was escaped or because it was markedsafe.
Passing an object to the constructor converts it to text and wrapsit to mark it safe without escaping. To escape the text, use the
escape()
class method instead.>>>Markup("Hello, <em>World</em>!")Markup('Hello, <em>World</em>!')>>>Markup(42)Markup('42')>>>Markup.escape("Hello, <em>World</em>!")Markup('Hello <em>World</em>!')
This implements the
__html__()
interface that some frameworksuse. Passing an object that implements__html__()
will wrap theoutput of that method, marking it safe.>>>classFoo:...def__html__(self):...return'<a href="/foo">foo</a>'...>>>Markup(Foo())Markup('<a href="/foo">foo</a>')
This is a subclass of
str
. It has the same methods, butescapes their arguments and returns aMarkup
instance.>>>Markup("<em>%s</em>")%("foo & bar",)Markup('<em>foo & bar</em>')>>>Markup("<em>Hello</em> ")+"<foo>"Markup('<em>Hello</em> <foo>')
- classmethodescape(s)¶
Escape a string. Calls
escape()
and ensures that forsubclasses the correct type is returned.- パラメータ
s (Any) --
- 戻り値の型
- striptags()¶
unescape()
the markup, remove tags, and normalizewhitespace to single spaces.>>>Markup("Main » <em>About</em>").striptags()'Main » About'
- 戻り値の型
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 call
get_flashed_messages()
.Changelog
バージョン 0.3 で変更:category parameter added.
- パラメータ
- 戻り値の型
None
- flask.get_flashed_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 whenwith_categories is set to
True
, the return value willbe a list of tuples in the form(category,message)
instead.Filter the flashed messages to one or more categories by providing thosecategories incategory_filter. This allows rendering categories inseparate html blocks. Thewith_categories andcategory_filterarguments are distinct:
with_categories controls whether categories are returned with messagetext (
True
gives a tuple, whereFalse
gives just the message text).category_filter filters the messages down to only those matching theprovided categories.
Seeメッセージのフラッシュ表示(Message Flashing) for examples.
Changelog
バージョン 0.9 で変更:category_filter parameter added.
バージョン 0.3 で変更:with_categories parameter added.
JSON Support¶
Flask uses Python's built-injson
module for handling JSON bydefault. The JSON implementation can be changed by assigning a differentprovider toflask.Flask.json_provider_class
orflask.Flask.json
. The functions provided byflask.json
willuse methods onapp.json
if an app context is active.
Jinja's|tojson
filter is configured to use the app's JSON provider.The filter marks the output with|safe
. Use it to render data insideHTML<script>
tags.
<script>constnames={{names|tosjon}};renderChart(names,{{axis_data|tojson}});</script>
- flask.json.jsonify(*args,**kwargs)¶
Serialize the given arguments as JSON, and return a
Response
object with theapplication/json
mimetype. A dict or list returned from a view will be converted to aJSON response automatically without needing to call this.This requires an active request or application context, and calls
app.json.response()
.In debug mode, the output is formatted with indentation to make iteasier to read. This may also be controlled by the provider.
Either positional or keyword arguments can be given, not both.If no arguments are given,
None
is serialized.- パラメータ
args (t.Any) -- A single value to serialize, or multiple values totreat as a list to serialize.
kwargs (t.Any) -- Treat as a dict to serialize.
- 戻り値の型
バージョン 2.2 で変更:Calls
current_app.json.response
, allowing an app to overridethe behavior.Changelog
バージョン 2.0.2 で変更:
decimal.Decimal
is supported by converting to a string.バージョン 0.11 で変更:Added support for serializing top-level arrays. This was asecurity risk in ancient browsers. SeeJSONのセキュリティ.
バージョン 0.2 で追加.
- flask.json.dumps(obj,*,app=None,**kwargs)¶
Serialize data as JSON.
If
current_app
is available, it will use itsapp.json.dumps()
method, otherwise it will usejson.dumps()
.- パラメータ
obj (t.Any) -- The data to serialize.
kwargs (t.Any) -- Arguments passed to the
dumps
implementation.app (Flask |None) --
- 戻り値の型
バージョン 2.2 で変更:Calls
current_app.json.dumps
, allowing an app to overridethe behavior.バージョン 2.2 で変更:The
app
parameter will be removed in Flask 2.3.Changelog
バージョン 2.0.2 で変更:
decimal.Decimal
is supported by converting to a string.バージョン 2.0 で変更:
encoding
will be removed in Flask 2.1.バージョン 1.0.3 で変更:
app
can be passed directly, rather than requiring an appcontext for configuration.
- flask.json.dump(obj,fp,*,app=None,**kwargs)¶
Serialize data as JSON and write to a file.
If
current_app
is available, it will use itsapp.json.dump()
method, otherwise it will usejson.dump()
.- パラメータ
- 戻り値の型
None
バージョン 2.2 で変更:Calls
current_app.json.dump
, allowing an app to overridethe behavior.バージョン 2.2 で変更:The
app
parameter will be removed in Flask 2.3.Changelog
バージョン 2.0 で変更:Writing to a binary file, and the
encoding
argument, will beremoved in Flask 2.1.
- flask.json.loads(s,*,app=None,**kwargs)¶
Deserialize data as JSON.
If
current_app
is available, it will use itsapp.json.loads()
method, otherwise it will usejson.loads()
.- パラメータ
- 戻り値の型
t.Any
バージョン 2.2 で変更:Calls
current_app.json.loads
, allowing an app to overridethe behavior.バージョン 2.2 で変更:The
app
parameter will be removed in Flask 2.3.Changelog
バージョン 2.0 で変更:
encoding
will be removed in Flask 2.1. The data must be astring or UTF-8 bytes.バージョン 1.0.3 で変更:
app
can be passed directly, rather than requiring an appcontext for configuration.
- flask.json.load(fp,*,app=None,**kwargs)¶
Deserialize data as JSON read from a file.
If
current_app
is available, it will use itsapp.json.load()
method, otherwise it will usejson.load()
.- パラメータ
fp (t.IO[t.AnyStr]) -- A file opened for reading text or UTF-8 bytes.
kwargs (t.Any) -- Arguments passed to the
load
implementation.app (Flask |None) --
- 戻り値の型
t.Any
バージョン 2.2 で変更:Calls
current_app.json.load
, allowing an app to overridethe behavior.バージョン 2.2 で変更:The
app
parameter will be removed in Flask 2.3.Changelog
バージョン 2.0 で変更:
encoding
will be removed in Flask 2.1. The file must be textmode, or binary mode with UTF-8 bytes.
- classflask.json.provider.JSONProvider(app)¶
A standard set of JSON operations for an application. Subclassesof this can be used to customize JSON behavior or use differentJSON libraries.
To implement a provider for a specific library, subclass this baseclass and implement at least
dumps()
andloads()
. Allother methods have default implementations.To use a different provider, either subclass
Flask
and setjson_provider_class
to a provider class, or setapp.json
to an instance of the class.- パラメータ
app (Flask) -- An application instance. This will be stored as a
weakref.proxy
on the_app
attribute.- 戻り値の型
None
バージョン 2.2 で追加.
- dumps(obj,**kwargs)¶
Serialize data as JSON.
- dump(obj,fp,**kwargs)¶
Serialize data as JSON and write to a file.
- loads(s,**kwargs)¶
Deserialize data as JSON.
- load(fp,**kwargs)¶
Deserialize data as JSON read from a file.
- response(*args,**kwargs)¶
Serialize the given arguments as JSON, and return a
Response
object with theapplication/json
mimetype.The
jsonify()
function calls this method forthe current application.Either positional or keyword arguments can be given, not both.If no arguments are given,
None
is serialized.- パラメータ
args (t.Any) -- A single value to serialize, or multiple values totreat as a list to serialize.
kwargs (t.Any) -- Treat as a dict to serialize.
- 戻り値の型
- classflask.json.provider.DefaultJSONProvider(app)¶
Provide JSON operations using Python's built-in
json
library. Serializes the following additional data types:datetime.datetime
anddatetime.date
areserialized toRFC 822 strings. This is the same as the HTTPdate format.uuid.UUID
is serialized to a string.dataclasses.dataclass
is passed todataclasses.asdict()
.Markup
(or any object with a__html__
method) will call the__html__
method to get a string.
- パラメータ
app (Flask) --
- 戻り値の型
None
- staticdefault(o)¶
Apply this function to any object that
json.dumps()
doesnot know how to serialize. It should return a valid JSON type orraise aTypeError
.
- ensure_ascii=True¶
Replace non-ASCII characters with escape sequences. This may bemore compatible with some clients, but can be disabled for betterperformance and size.
- sort_keys=True¶
Sort the keys in any serialized dicts. This may be useful forsome caching situations, but can be disabled for better performance.When enabled, keys must all be strings, they are not convertedbefore sorting.
- compact:bool|None=None¶
If
True
, orNone
out of debug mode, theresponse()
output will not add indentation, newlines, or spaces. IfFalse
,orNone
in debug mode, it will use a non-compact representation.
- mimetype='application/json'¶
The mimetype set in
response()
.
- dumps(obj,**kwargs)¶
Serialize data as JSON to a string.
Keyword arguments are passed to
json.dumps()
. Sets someparameter defaults from thedefault
,ensure_ascii
, andsort_keys
attributes.- パラメータ
obj (Any) -- The data to serialize.
kwargs (Any) -- Passed to
json.dumps()
.
- 戻り値の型
- loads(s,**kwargs)¶
Deserialize data as JSON from a string or bytes.
- パラメータ
kwargs (t.Any) -- Passed to
json.loads()
.
- 戻り値の型
t.Any
- response(*args,**kwargs)¶
Serialize the given arguments as JSON, and return a
Response
object with it. The response mimetypewill be "application/json" and can be changed withmimetype
.If
compact
isFalse
or debug mode is enabled, theoutput will be formatted to be easier to read.Either positional or keyword arguments can be given, not both.If no arguments are given,
None
is serialized.- パラメータ
args (t.Any) -- A single value to serialize, or multiple values totreat as a list to serialize.
kwargs (t.Any) -- Treat as a dict to serialize.
- 戻り値の型
- classflask.json.JSONEncoder(**kwargs)¶
The default JSON encoder. Handles extra types compared to thebuilt-in
json.JSONEncoder
.datetime.datetime
anddatetime.date
areserialized toRFC 822 strings. This is the same as the HTTPdate format.decimal.Decimal
is serialized to a string.uuid.UUID
is serialized to a string.dataclasses.dataclass
is passed todataclasses.asdict()
.Markup
(or any object with a__html__
method) will call the__html__
method to get a string.
Assign a subclass of this to
flask.Flask.json_encoder
orflask.Blueprint.json_encoder
to override the default.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Use
app.json
instead.- 戻り値の型
None
- default(o)¶
Convert
o
to a JSON serializable type. Seejson.JSONEncoder.default()
. Python does not supportoverriding how basic types likestr
orlist
areserialized, they are handled before this method.
- classflask.json.JSONDecoder(**kwargs)¶
The default JSON decoder.
This does not change any behavior from the built-in
json.JSONDecoder
.Assign a subclass of this to
flask.Flask.json_decoder
orflask.Blueprint.json_decoder
to override the default.バージョン 2.2 で非推奨:Will be removed in Flask 2.3. Use
app.json
instead.- 戻り値の型
None
Tagged JSON¶
A compact representation for lossless serialization of non-standard JSONtypes.SecureCookieSessionInterface
uses thisto serialize the session data, but it may be useful in other places. Itcan be extended to support other types.
- classflask.json.tag.TaggedJSONSerializer¶
Serializer that uses a tag system to compactly represent objects thatare not JSON types. Passed as the intermediate serializer to
itsdangerous.Serializer
.The following extra types are supported:
- 戻り値の型
None
- default_tags=[<class'flask.json.tag.TagDict'>,<class'flask.json.tag.PassDict'>,<class'flask.json.tag.TagTuple'>,<class'flask.json.tag.PassList'>,<class'flask.json.tag.TagBytes'>,<class'flask.json.tag.TagMarkup'>,<class'flask.json.tag.TagUUID'>,<class'flask.json.tag.TagDateTime'>]¶
Tag classes to bind when creating the serializer. Other tags can beadded later using
register()
.
- 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.
- パラメータ
tag_class (Type[flask.json.tag.JSONTag]) -- tag class to register. Will be instantiated with thisserializer instance.
force (bool) -- overwrite an existing tag. If false (default), a
KeyError
is raised.index (Optional[int]) -- index to insert the new tag in the tag order. Useful whenthe new tag is a special case of an existing tag. If
None
(default), the tag is appended to the end of the order.
- 例外
KeyError -- if the tag key is already registered and
force
isnot true.- 戻り値の型
None
- tag(value)¶
Convert a value to a tagged representation if necessary.
- classflask.json.tag.JSONTag(serializer)¶
Base class for defining type tags for
TaggedJSONSerializer
.- パラメータ
serializer (TaggedJSONSerializer) --
- 戻り値の型
None
- key:Optional[str]=None¶
The tag to mark the serialized object with. If
None
, this tag isonly used as an intermediate step during tagging.
- tag(value)¶
Convert the value to a valid JSON type and add the tag structurearound it.
- to_json(value)¶
Convert the Python object to an object that is a valid JSON type.The tag will be added later.
Let's see an example that adds support forOrderedDict
. Dicts don't have an order in JSON, soto handle this we will dump the items as a list of[key,value]
pairs. SubclassJSONTag
and give it the new key'od'
toidentify the type. The session serializer processes dicts first, soinsert the new tag at the front of the order sinceOrderedDict
mustbe processed beforedict
.
fromflask.json.tagimportJSONTagclassTagOrderedDict(JSONTag):__slots__=('serializer',)key=' od'defcheck(self,value):returnisinstance(value,OrderedDict)defto_json(self,value):return[[k,self.serializer.tag(v)]fork,viniteritems(value)]defto_python(self,value):returnOrderedDict(value)app.session_interface.serializer.register(TagOrderedDict,index=0)
Template Rendering¶
- flask.render_template(template_name_or_list,**context)¶
Render a template by name with the given context.
- パラメータ
template_name_or_list (Union[str,jinja2.environment.Template,List[Union[str,jinja2.environment.Template]]]) -- The name of the template to render. Ifa list is given, the first name to exist will be rendered.
context (Any) -- The variables to make available in the template.
- 戻り値の型
- flask.render_template_string(source,**context)¶
Render a template from the given source string with the givencontext.
- flask.stream_template(template_name_or_list,**context)¶
Render a template by name with the given context as a stream.This returns an iterator of strings, which can be used as astreaming response from a view.
- パラメータ
template_name_or_list (Union[str,jinja2.environment.Template,List[Union[str,jinja2.environment.Template]]]) -- The name of the template to render. Ifa list is given, the first name to exist will be rendered.
context (Any) -- The variables to make available in the template.
- 戻り値の型
バージョン 2.2 で追加.
- flask.stream_template_string(source,**context)¶
Render a template from the given source string with the givencontext as a stream. This returns an iterator of strings, which canbe used as a streaming response from a view.
- パラメータ
- 戻り値の型
バージョン 2.2 で追加.
- flask.get_template_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 named
_cider.html
with the following contents:{%macrohello(name)%}Hello{{name}}!{%endmacro%}
You can access this from Python code like this:
hello=get_template_attribute('_cider.html','hello')returnhello('World')
Changelog
バージョン 0.2 で追加.
Configuration¶
- classflask.Config(root_path,defaults=None)¶
Works exactly like a dict but provides ways to fill it from filesor special dictionaries. There are two common patterns to populate theconfig.
Either you can fill the config from a config file:
app.config.from_pyfile('yourconfig.cfg')
Or alternatively you can define the configuration options in themodule that calls
from_object()
or provide an import path toa module that should be loaded. It is also possible to tell it touse the same module and with that provide the configuration valuesjust before the call:DEBUG=TrueSECRET_KEY='development key'app.config.from_object(__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:
exportYOURAPPLICATION_SETTINGS='/path/to/config/file'
On windows useset instead.
- パラメータ
- 戻り値の型
None
- from_envvar(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.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
- from_file(filename,load,silent=False)¶
Update the values in the config from a file that is loadedusing the
load
parameter. The loaded data is passed to thefrom_mapping()
method.importjsonapp.config.from_file("config.json",load=json.load)importtomlapp.config.from_file("config.toml",load=toml.load)
- パラメータ
filename (str) -- The path to the data file. This can be anabsolute path or relative to the config root path.
load (
Callable[[Reader],Mapping]
whereReader
implements aread
method.) -- A callable that takes a file handle and returns amapping of loaded data from the file.silent (bool) -- Ignore the file if it doesn't exist.
- 戻り値
True
if the file was loaded successfully.- 戻り値の型
Changelog
バージョン 2.0 で追加.
- from_mapping(mapping=None,**kwargs)¶
Updates the config like
update()
ignoring items with non-upperkeys.:return: Always returnsTrue
.Changelog
バージョン 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')fromyourapplicationimportdefault_configapp.config.from_object(default_config)
Nothing is done to the object before loading. If the object is aclass and has
@property
attributes, it needs to beinstantiated before being passed to this method.You should not use this function to load the actual configuration butrather configuration defaults. The actual config should be loadedwith
from_pyfile()
and ideally from a location not within thepackage because the package might be installed system wide.See開発環境 / 本番環境 for an example of class-based configurationusing
from_object()
.
- from_prefixed_env(prefix='FLASK',*,loads=<functionloads>)¶
Load any environment variables that start with
FLASK_
,dropping the prefix from the env key for the config key. Valuesare passed through a loading function to attempt to convert themto more specific types than strings.Keys are loaded in
sorted()
order.The default loading function attempts to parse values as anyvalid JSON type, including dicts and lists.
Specific items in nested dicts can be set by separating thekeys with double underscores (
__
). If an intermediate keydoesn't exist, it will be initialized to an empty dict.- パラメータ
prefix (str) -- Load env vars that start with this prefix,separated with an underscore (
_
).loads (Callable[[str],Any]) -- Pass each string value to this function and usethe returned value as the config value. If any error israised it is ignored and the value remains a string. Thedefault is
json.loads()
.
- 戻り値の型
Changelog
バージョン 2.1 で追加.
- from_pyfile(filename,silent=False)¶
Updates the values in the config from a Python file. This functionbehaves as if the file was imported as module with the
from_object()
function.- パラメータ
- 戻り値
True
if the file was loaded successfully.- 戻り値の型
Changelog
バージョン 0.7 で追加:silent parameter.
- get_namespace(namespace,lowercase=True,trim_namespace=True)¶
Returns a dictionary containing a subset of configuration optionsthat match the specified namespace/prefix. Example usage:
app.config['IMAGE_STORE_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 dictionaryimage_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.
- パラメータ
- 戻り値の型
Changelog
バージョン 0.11 で追加.
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:
fromflaskimportstream_with_context,request,Response@app.route('/stream')defstreamed_response():@stream_with_contextdefgenerate():yield'Hello 'yieldrequest.args['name']yield'!'returnResponse(generate())
Alternatively it can also be used around a specific generator:
fromflaskimportstream_with_context,request,Response@app.route('/stream')defstreamed_response():defgenerate():yield'Hello 'yieldrequest.args['name']yield'!'returnResponse(stream_with_context(generate()))
Changelog
バージョン 0.9 で追加.
Useful Internals¶
- classflask.ctx.RequestContext(app,environ,request=None,session=None)¶
The request context contains per-request information. The Flaskapp creates and pushes it at the beginning of the request, then popsit at the end of the request. It will create the URL adapter andrequest object for the WSGI environment provided.
Do not attempt to use this class directly, instead use
test_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 therequest. When using the interactive debugger, the context will berestored so
request
is still accessible. Similarly, the testclient can preserve the context after the request ends. However,teardown functions may already have closed some resources such asdatabase connections.- パラメータ
- 戻り値の型
None
- 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
バージョン 1.1 で変更:The current session object is used instead of reloading the originaldata. This preventsflask.session pointing to an out-of-date object.
バージョン 0.10 で追加.
- match_request()¶
Can be overridden by a subclass to hook into the matchingof the request.
- 戻り値の型
None
- pop(exc=<objectobject>)¶
Pops the request context and unbinds it by doing that. This willalso trigger the execution of functions registered by the
teardown_request()
decorator.Changelog
バージョン 0.9 で変更:Added theexc argument.
- パラメータ
exc (Optional[BaseException]) --
- 戻り値の型
None
- flask.globals.request_ctx¶
The current
RequestContext
. If a request contextis not active, accessing attributes on this proxy will raise aRuntimeError
.This is an internal object that is essential to how Flask handlesrequests. Accessing this should not be needed in most cases. Mostlikely you want
request
andsession
instead.
- classflask.ctx.AppContext(app)¶
The app context contains application-specific information. An appcontext is created and pushed at the beginning of each request ifone is not already active. An app context is also pushed whenrunning CLI commands.
- パラメータ
app (Flask) --
- 戻り値の型
None
- pop(exc=<objectobject>)¶
Pops the app context.
- パラメータ
exc (Optional[BaseException]) --
- 戻り値の型
None
- push()¶
Binds the app context to the current context.
- 戻り値の型
None
- flask.globals.app_ctx¶
The current
AppContext
. If an app context is notactive, accessing attributes on this proxy will raise aRuntimeError
.This is an internal object that is essential to how Flask handlesrequests. Accessing this should not be needed in most cases. Mostlikely you want
current_app
andg
instead.
- classflask.blueprints.BlueprintSetupState(blueprint,app,options,first_registration)¶
Temporary holder object for registering a blueprint with theapplication. An instance of this class is created by the
make_setup_state()
method and later passedto all register callback functions.- add_url_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¶
a reference to the current application
- blueprint¶
a reference to the blueprint that created this setup state.
- first_registration¶
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¶
a dictionary with all options that were passed to the
register_blueprint()
method.
- subdomain¶
The subdomain that the blueprint should be active for,
None
otherwise.
- url_defaults¶
A dictionary with URL defaults that is added to each and everyURL that was defined with the blueprint.
- url_prefix¶
The prefix that should be used for all URLs defined on theblueprint.
Signals¶
Changelog
バージョン 0.6 で追加.
- signals.signals_available¶
True
if the signaling system is available. This is the casewhenblinker 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 astemplateand the context as dictionary (namedcontext).
Example subscriber:
deflog_template_renders(sender,template,context,**extra):sender.logger.debug('Rendering template "%s" with context%s',template.nameor'string template',context)fromflaskimporttemplate_renderedtemplate_rendered.connect(log_template_renders,app)
- flask.before_render_template
This signal is sent before template rendering process. Thesignal is invoked with the instance of the template astemplateand the context as dictionary (namedcontext).
Example subscriber:
deflog_template_renders(sender,template,context,**extra):sender.logger.debug('Rendering template "%s" with context%s',template.nameor'string template',context)fromflaskimportbefore_render_templatebefore_render_template.connect(log_template_renders,app)
- flask.request_started¶
This signal is sent when the request context is set up, beforeany request processing happens. Because the request context is alreadybound, the subscriber can access the request with the standard globalproxies such as
request
.Example subscriber:
deflog_request(sender,**extra):sender.logger.debug('Request context is set up')fromflaskimportrequest_startedrequest_started.connect(log_request,app)
- flask.request_finished¶
This signal is sent right before the response is sent to the client.It is passed the response to be sent namedresponse.
Example subscriber:
deflog_response(sender,response,**extra):sender.logger.debug('Request context is about to close down. ''Response:%s',response)fromflaskimportrequest_finishedrequest_finished.connect(log_response,app)
- flask.got_request_exception¶
This signal is sent when an unhandled exception happens duringrequest processing, including when debugging. The exception ispassed to the subscriber as
exception
.This signal is not sent for
HTTPException
, or other exceptions thathave error handlers registered, unless the exception was raised froman error handler.This example shows how to do some extra logging if a theoretical
SecurityException
was raised:fromflaskimportgot_request_exceptiondeflog_security_exception(sender,exception,**extra):ifnotisinstance(exception,SecurityException):returnsecurity_logger.exception(f"SecurityException at{request.url!r}",exc_info=exception,)got_request_exception.connect(log_security_exception,app)
- flask.request_tearing_down¶
This signal is sent when the request is tearing down. This is alwayscalled, even if an exception is caused. Currently functions listeningto this signal are called after the regular teardown handlers, but thisis not something you can rely on.
Example subscriber:
defclose_db_connection(sender,**extra):session.close()fromflaskimportrequest_tearing_downrequest_tearing_down.connect(close_db_connection,app)
As of Flask 0.9, this will also be passed anexc keyword argumentthat has a reference to the exception that caused the teardown ifthere was one.
- flask.appcontext_tearing_down¶
This signal is sent when the app context is tearing down. This is alwayscalled, even if an exception is caused. Currently functions listeningto this signal are called after the regular teardown handlers, but thisis not something you can rely on.
Example subscriber:
defclose_db_connection(sender,**extra):session.close()fromflaskimportappcontext_tearing_downappcontext_tearing_down.connect(close_db_connection,app)
This will also be passed anexc keyword argument that has a referenceto the exception that caused the teardown if there was one.
- flask.appcontext_pushed¶
This signal is sent when an application context is pushed. The senderis the application. This is usually useful for unittests in order totemporarily hook in information. For instance it can be used toset a resource early onto theg object.
Example usage:
fromcontextlibimportcontextmanagerfromflaskimportappcontext_pushed@contextmanagerdefuser_set(app,user):defhandler(sender,**kwargs):g.user=userwithappcontext_pushed.connected_to(handler,app):yield
And in the testcode:
deftest_user_me(self):withuser_set(app,'john'):c=app.test_client()resp=c.get('/users/me')assertresp.data=='username=john'
Changelog
バージョン 0.10 で追加.
- flask.appcontext_popped¶
This signal is sent when an application context is popped. The senderis the application. This usually falls in line with the
appcontext_tearing_down
signal.Changelog
バージョン 0.10 で追加.
- flask.message_flashed¶
This signal is sent when the application is flashing a message. Themessages is sent asmessage keyword argument and the category ascategory.
Example subscriber:
recorded=[]defrecord(sender,message,category,**extra):recorded.append((message,category))fromflaskimportmessage_flashedmessage_flashed.connect(record,app)
Changelog
バージョン 0.10 で追加.
- classsignals.Namespace¶
An alias for
blinker.base.Namespace
if blinker is available,otherwise a dummy class that creates fake signals. This class isavailable for Flask extensions that want to provide the same fallbacksystem as Flask itself.- signal(name,doc=None)¶
Creates a new signal for this namespace if blinker is available,otherwise returns a fake signal that has a send method that willdo nothing but will fail with a
RuntimeError
for all otheroperations, including connecting.
Class-Based Views¶
Changelog
バージョン 0.7 で追加.
- classflask.views.View¶
Subclass this class and override
dispatch_request()
tocreate a generic class-based view. Callas_view()
to create aview function that creates an instance of the class with the givenarguments and calls itsdispatch_request
method with any URLvariables.Seeクラスに基づいたビュー(Class-based Views) for a detailed guide.
classHello(View):init_every_request=Falsedefdispatch_request(self,name):returnf"Hello,{name}!"app.add_url_rule("/hello/<name>",view_func=Hello.as_view("hello"))
Set
methods
on the class to change what methods the viewaccepts.Set
decorators
on the class to apply a list of decorators tothe generated view function. Decorators applied to the class itselfwill not be applied to the generated view function!Set
init_every_request
toFalse
for efficiency, unlessyou need to store request-global data onself
.- classmethodas_view(name,*class_args,**class_kwargs)¶
Convert the class into a view function that can be registeredfor a route.
By default, the generated view will create a new instance of theview class for every request and call its
dispatch_request()
method. If the view class setsinit_every_request
toFalse
, the same instance willbe used for every request.The arguments passed to this method are forwarded to the viewclass
__init__
method.バージョン 2.2 で変更:Added the
init_every_request
class attribute.- パラメータ
- 戻り値の型
Union[Callable[[...],Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]], WSGIApplication]],Callable[[...],Awaitable[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]], WSGIApplication]]]]
- decorators:ClassVar[List[Callable]]=[]¶
A list of decorators to apply, in order, to the generated viewfunction. Remember that
@decorator
syntax is applied bottomto top, so the first decorator in the list would be the bottomdecorator.Changelog
バージョン 0.8 で追加.
- dispatch_request()¶
The actual view function behavior. Subclasses must overridethis and return a valid response. Any variables from the URLrule are passed as keyword arguments.
- 戻り値の型
Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]], WSGIApplication]
- init_every_request:ClassVar[bool]=True¶
Create a new instance of this view class for every request bydefault. If a view subclass sets this to
False
, the sameinstance is used for every request.A single instance is more efficient, especially if complex setupis done during init. However, storing data on
self
is nolonger safe across requests, andg
should be usedinstead.バージョン 2.2 で追加.
- classflask.views.MethodView¶
Dispatches request methods to the corresponding instance methods.For example, if you implement a
get
method, it will be used tohandleGET
requests.This can be useful for defining a REST API.
methods
is automatically set based on the methods defined onthe class.Seeクラスに基づいたビュー(Class-based Views) for a detailed guide.
classCounterAPI(MethodView):defget(self):returnstr(session.get("counter",0))defpost(self):session["counter"]=session.get("counter",0)+1returnredirect(url_for("counter"))app.add_url_rule("/counter",view_func=CounterAPI.as_view("counter"))
- dispatch_request(**kwargs)¶
The actual view function behavior. Subclasses must overridethis and return a valid response. Any variables from the URLrule are passed as keyword arguments.
- パラメータ
kwargs (Any) --
- 戻り値の型
Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int],Tuple[Union[Response,str,bytes,List[Any],Mapping[str,Any],Iterator[str],Iterator[bytes]],int,Union[Headers,Mapping[str,Union[str,List[str],Tuple[str, ...]]],Sequence[Tuple[str,Union[str,List[str],Tuple[str, ...]]]]]], WSGIApplication]
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 | likeint 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 usingflask.Flask.url_map
.
Here are some examples:
@app.route('/')defindex():pass@app.route('/<username>')defshow_user(username):pass@app.route('/post/<int:post_id>')defshow_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>')defshow_users(page):pass
This specifies that/users/
will be the URL for page one and/users/page/N
will be the URL for pageN
.
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 handlesGET
andPOST
requests, make sure the default route only handlesGET
, as redirectscan't preserve form data.
@app.route('/region/',defaults={'id':1})@app.route('/region/<int:id>',methods=['GET','POST'])defregion(id):pass
Here are the parameters thatroute()
andadd_url_rule()
accept. The only difference is thatwith the route parameter the view function is defined with the decoratorinstead of theview_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 |
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 |
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 toadd_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 amethodsattribute 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 theOPTIONS
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:
defindex():ifrequest.method=='OPTIONS':# custom options handling here...return'Hello World!'index.provide_automatic_options=Falseindex.methods=['GET','OPTIONS']app.add_url_rule('/',index)
Changelog
バージョン 0.8 で追加:Theprovide_automatic_options functionality was added.
Command Line Interface¶
- classflask.cli.FlaskGroup(add_default_commands=True,create_app=None,add_version_option=True,load_dotenv=True,set_debug_flag=True,**extra)¶
Special subclass of the
AppGroup
group that supportsloading more commands from the configured Flask app. Normally adeveloper does not have to interface with this class but there aresome very advanced use cases for which it makes sense to create aninstance of this. see独自のスクリプト.- パラメータ
add_default_commands (bool) -- if this is True then the default run andshell commands will be added.
add_version_option (bool) -- adds the
--version
option.create_app (t.Callable[...,Flask]|None) -- an optional callback that is passed the script info andreturns the loaded app.
load_dotenv (bool) -- Load the nearest
.env
and.flaskenv
files to set environment variables. Will also change the workingdirectory to the directory containing the first file found.set_debug_flag (bool) -- Set the app's debug flag.
extra (t.Any) --
- 戻り値の型
None
バージョン 2.2 で変更:Added the
-A/--app
,--debug/--no-debug
,-e/--env-file
options.バージョン 2.2 で変更:An app context is pushed when running
app.cli
commands, so@with_appcontext
is no longer required for those commands.Changelog
バージョン 1.0 で変更:If installed, python-dotenv will be used to load environment variablesfrom
.env
and.flaskenv
files.- get_command(ctx,name)¶
Given a context and a command name, this returns a
Command
object if it exists or returnsNone.
- list_commands(ctx)¶
Returns a list of subcommand names in the order they shouldappear.
- make_context(info_name,args,parent=None,**extra)¶
This function when given an info name and arguments will kickoff the parsing and create a new
Context
. It does notinvoke the actual command callback though.To quickly customize the context class used without overridingthis method, set the
context_class
attribute.- パラメータ
info_name (str |None) -- the info name for this invocation. Generally thisis the most descriptive name for the script orcommand. For the toplevel script it's usuallythe name of the script, for commands below it it'sthe name of the command.
args (list[str]) -- the arguments to parse as list of strings.
parent (click.Context |None) -- the parent context if available.
extra (t.Any) -- extra keyword arguments forwarded to the contextconstructor.
- 戻り値の型
バージョン 8.0 で変更:Added the
context_class
attribute.
- parse_args(ctx,args)¶
Given a context and a list of arguments this creates the parserand parses the arguments, then modifies the context as necessary.This is automatically invoked by
make_context()
.- パラメータ
ctx (click.Context) --
- 戻り値の型
- classflask.cli.AppGroup(name=None,commands=None,**attrs)¶
This works similar to a regular click
Group
but itchanges the behavior of thecommand()
decorator so that itautomatically wraps the functions inwith_appcontext()
.Not to be confused with
FlaskGroup
.- パラメータ
commands (Optional[Union[Dict[str,click.core.Command],Sequence[click.core.Command]]]) --
attrs (Any) --
- 戻り値の型
None
- command(*args,**kwargs)¶
This works exactly like the method of the same name on a regular
click.Group
but it wraps callbacks inwith_appcontext()
unless it's disabled by passingwith_appcontext=False
.
- group(*args,**kwargs)¶
This works exactly like the method of the same name on a regular
click.Group
but it defaults the group class toAppGroup
.
- classflask.cli.ScriptInfo(app_import_path=None,create_app=None,set_debug_flag=True)¶
Helper object to deal with Flask applications. This is usually notnecessary to interface with as it's used internally in the dispatchingto click. In future versions of Flask this object will most likely playa bigger role. Typically it's created automatically by the
FlaskGroup
but you can also manually create it and pass itonwards as click object.- パラメータ
- 戻り値の型
None
- app_import_path¶
Optionally the import path for the Flask application.
- create_app¶
Optionally a function that is passed the script info to createthe instance of the application.
- data:t.Dict[t.Any,t.Any]¶
A dictionary with arbitrary data that can be associated withthis script info.
- 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.
This is a no-op ifpython-dotenv is not installed.
- パラメータ
path (str |os.PathLike |None) -- Load the file at this location instead of searching.
- 戻り値
True
if a file was loaded.- 戻り値の型
Changelog
バージョン 2.0 で変更:The current directory is not changed to the location of theloaded file.
バージョン 2.0 で変更:When loading the env files, set the default encoding to UTF-8.
バージョン 1.1.0 で変更:Returns
False
when python-dotenv is not installed, or whenthe given path isn't a file.バージョン 1.0 で追加.
- flask.cli.with_appcontext(f)¶
Wraps a callback so that it's guaranteed to be executed with thescript's application context.
Custom commands (and their options) registered under
app.cli
orblueprint.cli
will always have an app context available, thisdecorator is not required in that case.バージョン 2.2 で変更:The app context is active for subcommands as well as thedecorated callback. The app context is always available to
app.cli
command and parameter callbacks.
- flask.cli.pass_script_info(f)¶
Marks a function so that an instance of
ScriptInfo
is passedas first argument to the click callback.- パラメータ
f (click.decorators.F) --
- 戻り値の型
click.decorators.F
- flask.cli.run_command=<Commandrun>¶
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 with the '--debug'option.
- flask.cli.shell_command=<Commandshell>¶
Run an interactive Python shell in the context of a givenFlask application. The application will populate the defaultnamespace of this shell according to its configuration.
This is useful for executing small snippets of management codewithout having to manually configure the application.