API
This part of the documentation covers all the interfaces of Flask. For parts where Flask depends on external libraries, we document the most important right here and provide links to the canonical documentation.
Application Object
class flask.Flask(import_name, static_url_path=None, static_folder=’static’, static_host=None, host_matching=False, subdomain_matching=False, template_folder=’templates’, instance_path=None, instance_relative_config=False, root_path=None)
The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more.
The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an __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 or in the __init__.py file of your package like this:
1. from flask import Flask
2. app = Flask(__name__)
About the First Parameter
The idea of the first parameter is to give Flask an idea of what belongs to your application. This name is used to find resources on the filesystem, can be used by extensions to improve debugging information and a lot more.
So it’s important what you provide there. If you are using a single module, __name__ is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package there.
For example if your application is defined in yourapplication/app.py you should create it with one of the two versions below:
1. app = Flask('yourapplication')
2. app = Flask(__name__.split('.')[0])
Why is that? The application will work even with __name__, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application. For example the Flask-SQLAlchemy extension will look for the code in your application that triggered an SQL query in debug mode. If the import name is not properly set up, that debugging information is lost. (For example it would only pick up SQL queries in yourapplication.app and not yourapplication.views.frontend)
Changelog
New in version 1.0: The host_matching and static_host parameters were added.
New in version 1.0: The subdomain_matching parameter was added. Subdomain matching needs to be enabled manually now. Setting SERVER_NAME does not implicitly enable it.
New in version 0.11: The root_path parameter was added.
New in version 0.8: The instance_path and instance_relative_config parameters were added.
New in version 0.7: The static_url_path, static_folder, and template_folder parameters were added.
-
Parameters
-
import_name (str) – the name of the application package
- static_url_path (Optional[str]) – can be used to specify a different path for the static files on the web. Defaults to the name of the static_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_pathor 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=Truewith astatic_folderconfigured. - host_matching (bool) – set
url_map.host_matchingattribute. 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 should be used by the application. Defaults to
'templates'folder in the root path of the application. - instance_path (Optional[str]) – An alternative instance path for the application. By default the folder
'instance'next to the package or module is assumed to be the instance path. - instance_relative_config (bool) – if set to
Truerelative filenames for loading the config are assumed to be relative to the instance path instead of 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 detected automatically, such as for namespace packages.
- aborter
An instance of aborter_class created by make_aborter(). This is called by flask.abort() to raise HTTP errors, and can be called directly as well.
New in version 2.2: Moved from flask.abort, which calls this object.
- aborter_class
alias of werkzeug.exceptions.Aborter - add_template_filter(f, name=None)
Register a custom template filter. Works exactly like the template_filter() decorator.
-
Parameters
- name (Optional[str]) – the optional name of the filter, otherwise the function name will be used.
- f (Callable[[…], Any]) –
Return type
None - add_template_global(f, name=None)
Register a custom template global function. Works exactly like the template_global() decorator.
Changelog
New in version 0.10.
-
Parameters
- name (Optional[str]) – the optional name of the global function, otherwise the function name will be used.
- f (Callable[[…], Any]) –
Return type
None - add_template_test(f, name=None)
Register a custom template test. Works exactly like the template_test() decorator.
Changelog
New in version 0.10.
-
Parameters
- name (Optional[str]) – the optional name of the test, otherwise the function name will be used.
- f (Callable[[…], bool]) –
Return type
None - add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, ***options*)
Register a rule for routing incoming requests and building URLs. The route() decorator is a shortcut to call this with the view_func argument. These are equivalent:
1. @app.route("/")
2. def index():
3. ...
``` 1. def index(): 2. ...
- app.add_url_rule("/", view_func=index) ```
The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn’t passed. An error will be raised if a function has already been registered for the endpoint.
The methods parameter defaults to ["GET"]. HEAD is always added automatically, and OPTIONS is added automatically by default.
view_func does not necessarily need to be passed, but if the rule should participate in routing an endpoint name must be associated with a view function at some point with the endpoint() decorator.
``` 1. app.add_url_rule("/", endpoint="index")
- @app.endpoint("index")
- def index():
- ... ```
If view_func has a required_methods attribute, those methods are added to the passed and automatic methods. If it has a provide_automatic_methods attribute, it is used as the default if the parameter is not passed.
-
Parameters
- rule (str) – The URL rule string.
- endpoint (Optional[str]) – The endpoint name to associate with the rule and 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 the endpoint name.
- provide_automatic_options (Optional[bool]) – Add the
OPTIONSmethod and respond toOPTIONSrequests automatically. - options (Any) – Extra options passed to the Rule object.
Return type
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 return a response object. This allows the functions to modify or replace the response before it is sent.
If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request() for that.
-
Parameters
f (flask.scaffold.T_after_request) –
Return type
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 each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the after_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time. - app_context()
Create an AppContext. Use as a with block to push the context, which will make current_app point at this application.
An application context is automatically pushed by RequestContext.push() when handling a request, and when running a CLI command. Use this to manually create a context outside of these situations.
1. with app.app_context():
2. init_db()
Changelog
New in version 0.9.
-
Return type
flask.ctx.AppContext - app_ctx_globals_class
alias of flask.ctx._AppCtxGlobals - async_to_sync(func)
Return a sync function that will run the coroutine function.
1. result = app.async_to_sync(func)(*args, **kwargs)
Override this method to change how the app converts async code to be synchronously callable.
Changelog
New in version 2.0.
Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named instance next to your main file or the package.
Changelog
New in version 0.8.
-
Return type
str - before_first_request(f)
Registers a function to be run before the first request to this instance of the application.
The function will be called without any arguments and its return value is ignored.
Deprecated since version 2.2: Will be removed in Flask 2.3. Run setup code when creating the application instead.
Changelog
New in version 0.8.
-
Parameters
f (flask.app.T_before_first_request) –
Return type
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 the first request to this instance. To register a function, use the before_first_request() decorator.
Deprecated since version 2.2: Will be removed in Flask 2.3. Run setup code when creating the application instead.
Changelog
New in version 0.8. - before_request(f)
Register a function to run before each request.
For example, this can be used to open a database connection, or to load the logged in user from the session.
1. @app.before_request
2. def load_user():
3. if "user_id" in session:
4. g.user = db.session.get(session["user_id"])
The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped.
-
Parameters
f (flask.scaffold.T_before_request) –
Return type
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 of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the before_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time. - blueprints: t.Dict[str, ‘Blueprint’]
Maps registered blueprint names to blueprint objects. The dict retains the order the blueprints were registered in. Blueprints can be registered multiple times, this dict does not track how often they were attached.
Changelog
New in version 0.7. - cli
The Click command group for registering CLI commands for this object. The commands are available from the flask command once the application has been discovered and blueprints have been registered.
- config
The configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files. - config_class
alias of flask.config.Config - context_processor(f)
Registers a template context processor function.
-
Parameters
f (flask.scaffold.T_template_context_processor) –
Return type
flask.scaffold.T_template_context_processor - create_global_jinja_loader()
Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It’s discouraged to override this function. Instead one should override the jinja_loader() function instead.
The global loader dispatches between the loaders of the application and the individual blueprints.
Changelog
New in version 0.7.
-
Return type
flask.templating.DispatchingJinjaLoader - create_jinja_environment()
Create the Jinja environment based on jinja_options and the various Jinja-related methods of the app. Changing jinja_options after this will have no effect. Also adds Flask-related globals and filters to the environment.
Changelog
Changed in version 0.11: Environment.auto_reload set in accordance with TEMPLATES_AUTO_RELOAD configuration option.
New in version 0.5.
-
Return type
flask.templating.Environment - create_url_adapter(request)
Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly.
Changelog
Changed in version 1.0: SERVER_NAME no longer implicitly enables subdomain matching. Use subdomain_matching instead.
Changed in version 0.9: This can now also be called without a request object when the URL adapter is created for the application context.
New in version 0.6.
-
Parameters
request (Optional[flask.wrappers.Request]) –
Return type
Optional[werkzeug.routing.map.MapAdapter] - property debug: bool
Whether debug mode is enabled. When using flask run to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. This maps to the DEBUG 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. - delete(rule, ***options*)
Shortcut for route() with methods=["DELETE"].
Changelog
New in version 2.0.
-
Parameters
Return type
Callable[[flask.scaffold.T_route], flask.scaffold.T_route] - dispatch_request()
Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call make_response().
Changelog
Changed in version 0.7: This no longer does the exception handling, this code was moved to the new full_dispatch_request().
-
Return type
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](#flask.Respon
(本文超出单文档体积上限,已截断)
