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 (str | None) – 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 (str | os.PathLike[str] | None) – The folder with static files that is served at static_url_path. Relative to the application root_path or an absolute path. Defaults to 'static'.
  • static_host (str | None) – the host to use when adding the static route. Defaults to None. Required when using host_matching=True with a static_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 (str | os.PathLike[str] | None) – 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 (str | None) – 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 True relative filenames for loading the config are assumed to be relative to the instance path instead of the application root.
  • root_path (str | None) – 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.

Changelog

New in version 2.2: Moved from flask.abort, which calls this object. - aborter_class

alias of Aborter - add_template_filter(f, name=None)

Register a custom template filter. Works exactly like the template_filter() decorator.

  • Parameters:

    • name (str | None) – 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 (str | None) – 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 (str | None) – 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. ...

  1. app.add_url_rule("/", view_func=index) ```

See URL Route Registrations.

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")

  1. @app.endpoint("index")
  2. def index():
  3. ... ```

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 (str | None) – The endpoint name to associate with the rule and view function. Used when routing and building URLs. Defaults to view_func.__name__.
    • view_func (ft.RouteCallable | None) – The view function to associate with the endpoint name.
    • provide_automatic_options (bool | None) – Add the OPTIONS method and respond to OPTIONS requests automatically.
    • options (t.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.

This is available on both app and blueprint objects. When used on an app, this executes after every request. When used on a blueprint, this executes after every request that the blueprint handles. To register with a blueprint and execute after every request, use Blueprint.after_app_request().

  • Parameters:

    f (T_after_request) –

    Return type:

    T_after_request - after_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]]

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()

See The Application Context.

Changelog

New in version 0.9.

alias of _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_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.

This is available on both app and blueprint objects. When used on an app, this executes before every request. When used on a blueprint, this executes before every request that the blueprint handles. To register with a blueprint and execute before every request, use Blueprint.before_app_request().

  • Parameters:

    f (T_before_request) –

    Return type:

    T_before_request - before_request_funcs: dict[ft.AppOrBlueprintKey, 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: 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: click.Group

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 Config - context_processor(f)

Registers a template context processor function. These functions run before rendering a template. The keys of the returned dict are added as variables available in the template.

This is available on both app and blueprint objects. When used on an app, this is called for every rendered template. When used on a blueprint, this is called for templates rendered from the blueprint’s views. To register with a blueprint and affect every template, use Blueprint.app_context_processor().

  • Parameters:

    f (T_template_context_processor) –

    Return type:

    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:

    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:

    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.

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 - delete(rule, **options)

Shortcut for route() with methods=["DELETE"].

Changelog

New in version 2.0.

  • Parameters:

    • rule (str) –
    • options (Any) –

    Return type:

    Callable[[T_route], 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:

    ft.ResponseReturnValue - do_teardown_appcontext(exc=<object object>)

Called right before the application context is popped.

When handling a request, the application context is popped after the request context. See do_teardown_request().

This calls all functions decorated with teardown_appcontext(). Then the appcontext_tearing_down signal is sent.

This is called by AppContext.pop().

Changelog

New in version 0.9.

  • Parameters:

    exc (BaseException | None) –

    Return type:

    None - do_teardown_request(exc=<object object>)

Called after the request is dispatched and the response is returned, right before the request context is popped.

This calls all functions decorated with teardown_request(), and Blueprint.teardown_request() if a blueprint handled the request. Finally, the request_tearing_down signal is sent.

This is called by RequestContext.pop(), which may be delayed during testing to maintain access to resources.

  • Parameters:

    exc (BaseException | None) – An unhandled exception raised while dispatching the request. Detected from the current exception information if not passed. Passed to each teardown function.

    Return type:

    None

Changelog

Changed in version 0.9: Added the exc argument. - endpoint(endpoint)

Decorate a view function to register it for the given endpoint. Used if a rule is added without a view_func with add_url_rule().

``` 1. app.add_url_rule("/ex", endpoint="example")

  1. @app.endpoint("example")
  2. def example():
  3. ... ```

  4. Parameters:

    endpoint (str) – The endpoint name to associate with the view function.

    Return type:

    Callable[[F], F] - ensure_sync(func)

Ensure that the function is synchronous for WSGI workers. Plain def functions are returned as-is. async def functions are wrapped to run and wait for the response.

Override this method to change how the app runs async views.

Changelog

New in version 2.0.

A data structure of registered error handlers, in the format {scope: {code: {class: handler}}}. The scope key is the name of a blueprint the handlers are active for, or None for all requests. The code key is the HTTP status code for HTTPException, or None for other exceptions. The innermost dictionary maps exception classes to handler functions.

To register an error handler, use the errorhandler() decorator.

This data structure is internal. It should not be modified directly 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 an error code. Example:

1. @app.errorhandler(404) 2. def page_not_found(error): 3. return 'This page does not exist', 404

You can also register handlers for arbitrary exceptions:

1. @app.errorhandler(DatabaseError) 2. def special_exception_handler(error): 3. return 'Database connection failed', 500

This is available on both app and blueprint objects. When used on an app, this can handle errors from every request. When used on a blueprint, this can handle errors from requests that the blueprint handles. To register with a blueprint and affect every request, use Blueprint.app_errorhandler().

Changelog

New in version 0.7: Use register_error_handler() instead of modifying error_handler_spec directly, for application wide error handlers.

New in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the HTTPException class.

  • Parameters:

    code_or_exception (type[Exception] | int) – the code as integer for the handler, or an arbitrary exception

    Return type:

    Callable[[T_error_handler], T_error_handler] - extensions: dict[str, t.Any]

a place where extensions can store application specific state. For example this is where an extension could store database engines and similar things.

The key must match the name of the extension module. For example in case of a “Flask-Foo” extension in flask_foo, the key would be 'foo'.

Changelog

New in version 0.7. - full_dispatch_request()

Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling.

Changelog

New in version 0.7.

  • Return type:

    Response - get(rule, **options)

Shortcut for route() with methods=["GET"].

Changelog

New in version 2.0.

  • Parameters:

    • rule (str) –
    • options (Any) –

    Return type:

    Callable[[T_route], T_route] - get_send_file_max_age(filename)

Used by send_file() to determine the max_age cache value for a given file path if it wasn’t passed.

By default, this returns SEND_FILE_MAX_AGE_DEFAULT from the configuration of current_app. This defaults to None, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable.

Note this is a duplicate of the same method in the Flask class.

Changelog

Changed in version 2.0: The default configuration is None instead of 12 hours.

New in version 0.9.

  • Parameters:

    filename (str | None) –

    Return type:

    int | None - handle_exception(e)

Handle an exception that did not have an error handler associated 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 is True, such as in debug mode, the error will be re-raised so that the debugger can display it. Otherwise, the original exception is logged, and an InternalServerError is returned.

If an error handler is registered for InternalServerError or 500, it will be used. For consistency, the handler will always receive the InternalServerError. The original unhandled exception is available as e.original_exception.

Changelog

Changed in version 1.1.0: Always passes the InternalServerError instance to the handler, setting original_exception to the unhandled error.

Changed in version 1.1.0: after_request functions and other finalization is done even for the default 500 response when there is no handler.

New in version 0.3.

Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.

Changelog

Changed in version 1.0.3: RoutingException, used internally for actions such as slash redirects during routing, is not passed to error handlers.

Changed in version 1.0: Exceptions are looked up by code and by MRO, so HTTPException subclasses can be handled with a catch-all handler for the base HTTPException.

New in version 0.3.

  • Parameters:

    e (HTTPException) –

    Return type:

    HTTPException | ft.ResponseReturnValue - handle_url_build_error(error, endpoint, values)

Called by url_for() if a BuildError was raised. If this returns a value, it will be returned by url_for, otherwise the error will be re-raised.

Each function in url_build_error_handlers is called with error, endpoint and values. If a function returns None or raises a BuildError, it is skipped. Otherwise, its return value is returned by url_for.

  • Parameters:

    • error (BuildError) – The active BuildError being handled.
    • endpoint (str) – The endpoint being built.
    • values (dict[str, Any]) – The keyword arguments passed to url_for.

    Return type:

    str - handle_user_exception(e)

This method is called whenever an exception occurs that should be handled. A special case is HTTPException which is forwarded to the handle_http_exception() method. This function will either return a response value or reraise the exception with the same traceback.

Changelog

Changed in version 1.0: Key errors raised from request data like form show the bad key in debug mode rather than a generic bad request message.

New in version 0.7.

  • Parameters:

    e (Exception) –

    Return type:

    HTTPException | ft.ResponseReturnValue - property has_static_folder: bool

True if static_folder is set.

Changelog

New in version 0.5. - import_name

The name of the package or module that this object belongs to. 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 into the values dictionary passed. This is used internally and automatically called on URL building.

Changelog

New in version 0.7.

  • Parameters:

    Return type:

    None - instance_path

Holds the path to the instance folder.

Changelog

New in version 0.8. - iter_blueprints()

Iterates over all blueprints by the order they were registered.

Changelog

New in version 0.11.

  • Return type:

    t.ValuesView[Blueprint] - property jinja_env: Environment

The Jinja environment used to load templates.

The environment is created the first time this property is accessed. Changing jinja_options after that will have no effect. - jinja_environment

alias of Environment - property jinja_loader: BaseLoader | None

The Jinja loader for this object’s templates. By default this is a class jinja2.loaders.FileSystemLoader to template_folder if it is set.

Changelog

New in version 0.5. - jinja_options: dict[str, t.Any] = {}

Options that are passed to the Jinja environment in create_jinja_environment(). Changing these options after the environment is created (accessing jinja_env) will have no effect.

Changelog

Changed in version 1.1.0: This is a dict instead of an ImmutableDict to allow easier configuration. - json: JSONProvider

Provides access to JSON methods. Functions in flask.json will call methods on this provider when the application context is active. Used for handling JSON requests and responses.

An instance of json_provider_class. Can be customized by changing that attribute on a subclass, or by assigning to this attribute afterwards.

The default, DefaultJSONProvider, uses Python’s built-in json library. A different provider can use a different JSON library.

Changelog

New in version 2.2. - json_provider_class

alias of DefaultJSONProvider - 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 the logger.

Changelog

New in version 0.8.

A standard Python Logger for the app, with the same name as name.

In debug mode, the logger’s level will be set to DEBUG.

If there are no handlers configured, a default handler will be added. See Logging for more information.

Changelog

Changed in version 1.1.0: The logger takes the same name as name rather than hard-coding "flask.app".

Changed in version 1.0.0: Behavior was simplified. The logger is always named "flask.app". The level is only set during configuration, it doesn’t check app.debug each time. Only one format is used, not different ones depending on app.debug. No handlers are removed, and a handler is only added if no handlers are already configured.

New in version 0.3. - make_aborter()

Create the object to assign to aborter. That object is called by flask.abort() to raise HTTP errors, and can be called directly as well.

By default, this creates an instance of aborter_class, which defaults to werkzeug.exceptions.Aborter.

Changelog

New in version 2.2.

  • Return type:

    Aborter - make_config(instance_relative=False)

Used to create the config attribute by the Flask constructor. The instance_relative parameter is passed in from the constructor of Flask (there named instance_relative_config) and indicates if the config should be relative to the instance path or the root path of the application.

Changelog

New in version 0.8.

  • Parameters:

    instance_relative (bool) –

    Return type:

    Config - make_default_options_response()

This method is called to create the default OPTIONS response. This can be changed through subclassing to change the default behavior of OPTIONS responses.

Changelog

New in version 0.7.

  • Return type:

    Response - make_response(rv)

Convert the return value from a view function to an instance of response_class.

  • Parameters:

    rv (ft.ResponseReturnValue) –

    the return value from the view function. The view function must return a response. Returning None, or the view ending without returning, is not allowed. The following types are allowed for view_rv:

    str

    A response object is created with the string encoded to UTF-8 as 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 or iterator

    A generator that returns str or bytes to be streamed as the response.

    tuple

    Either (body, status, headers), (body, status), or (body, headers), where body is any of the other types allowed here, status is a string or an integer, and headers is a dictionary or a list of (key, value) tuples. If body is a response_class instance, status overwrites the exiting value and headers are extended.

    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 is used to create a response object.

    Return type:

    Response

Changelog

Changed in version 2.2: A generator will be converted to a streaming response. A list will be converted to a JSON response.

Changed in version 1.1: A dict will be converted to a JSON response.

Changed in version 0.9: Previously a tuple was interpreted as the arguments for the response object. - make_shell_context()

Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors.

Changelog

New in version 0.11.

The name of the application. This is

(本文超出单文档体积上限,已截断)