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**[str]) – 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 (Optional**[str]) – 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 (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 True relative 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.
  • 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]**, str]) –

    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[[Any]**, 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 (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[Callable**]) – The view function to associate with the endpoint name.
    • provide_automatic_options (Optional**[bool]) – Add the OPTIONS method and respond to OPTIONS requests 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 (Callable[[Response]**, Response]) –

    Return type

    Callable[[Response], Response] - after_request_funcs: t.Dict[AppOrBlueprintKey, t.List[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()

See The Application Context.

Changelog

New in version 0.9.

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.

New in version 2.0.

  • Parameters

    func (Callable[[…]**, Coroutine**]) –

    Return type

    Callable[[…], Any] - auto_find_instance_path()

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.

Changelog

New in version 0.8.

  • Parameters

    f (Callable[[], None]) –

    Return type

    Callable[[], None] - before_first_request_funcs: t.List[BeforeRequestCallable]

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.

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 (Callable[[], None]) –

    Return type

    Callable[[], None] - before_request_funcs: t.Dict[AppOrBlueprintKey, t.List[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 (Callable[[], Dict**[str, Any]]) –

    Return type

    Callable[[], Dict[str, Any]] - 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.

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. This is enabled when env is 'development' and is overridden by the FLASK_DEBUG environment variable. It may not behave as expected if set in code.

Do not enable debug mode when deploying in production.

Default: True if env is 'development', or False otherwise. - default_config = {‘APPLICATION_ROOT’: ‘/‘, ‘DEBUG’: None, ‘ENV’: None, ‘EXPLAIN_TEMPLATE_LOADING’: False, ‘JSONIFY_MIMETYPE’: ‘application/json’, ‘JSONIFY_PRETTYPRINT_REGULAR’: False, ‘JSON_AS_ASCII’: True, ‘JSON_SORT_KEYS’: True, ‘MAX_CONTENT_LENGTH’: None, ‘MAX_COOKIE_SIZE’: 4093, ‘PERMANENT_SESSION_LIFETIME’: datetime.timedelta(days=31), ‘PREFERRED_URL_SCHEME’: ‘http’, ‘PRESERVE_CONTEXT_ON_EXCEPTION’: None, ‘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"].

New in version 2.0.

  • Parameters

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

    Return type

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

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 (Optional**[BaseException]) –

    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 (Optional**[BaseException]) – 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 - 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.

New in version 2.0.

  • Parameters

    func (Callable) –

    Return type

    Callable - env

What environment the app is running in. Flask and extensions may enable behaviors based on the environment, such as enabling debug mode. This maps to the ENV config key. This is set by the FLASK_ENV environment variable and may not behave as expected if set in code.

Do not enable development when deploying in production.

Default: 'production' - error_handler_spec: t.Dict[AppOrBlueprintKey, t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ErrorHandlerCallable]]]

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

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.

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.

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

New in version 2.0.

  • Parameters

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

    Return type

    Callable - 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.

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

Changelog

New in version 0.9.

  • Parameters

    filename (Optional**[str]) –

    Return type

    Optional[int] - property got_first_request: bool

This attribute is set to True if the application started handling the first request.

Changelog

New in version 0.8. - 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 HTTPExcpetion subclasses can be handled with a catch-all handler for the base HTTPException.

New in version 0.3.

Handle BuildError on url_for().

  • Parameters

    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.

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