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.
Attributes
| Attribute | Type | Description |
|---|
| default_config | ImmutableDict = ImmutableDict({...}) | A dictionary containing the default configuration values for the application, including session settings, server names, and limits. |
| request_class | type[[Request](../wrappers/request.md?sid=src_flask_wrappers_request)] = Request | The class that is used for request objects. |
| response_class | type[[Response](../wrappers/response.md?sid=src_flask_wrappers_response)] = Response | The class that is used for response objects. |
| session_interface | [SessionInterface](../sessions/sessioninterface.md?sid=src_flask_sessions_sessioninterface) = SecureCookieSessionInterface() | The session interface to use. |
Constructor
Signature
def Flask(
import_name: str,
static_url_path: str | None = None,
static_folder: str | os.PathLike[str]| None = "static",
static_host: str | None = None,
host_matching: bool = False,
subdomain_matching: bool = False,
template_folder: str | os.PathLike[str]| None = "templates",
instance_path: str | None = None,
instance_relative_config: bool = False,
root_path: str | None = None
) - > null
Parameters
| Name | Type | Description |
|---|
| import_name | str | The name of the application package. |
| static_url_path | `str | None` = None |
| static_folder | `str | os.PathLike[str] |
| static_host | `str | None` = None |
| host_matching | bool = False | Set url_map.host_matching attribute. |
| subdomain_matching | bool = False | Consider the subdomain relative to SERVER_NAME when matching routes. |
| template_folder | `str | os.PathLike[str] |
| instance_path | `str | None` = None |
| instance_relative_config | bool = False | If True, relative filenames for loading config are assumed to be relative to the instance path. |
| root_path | `str | None` = None |
Methods
get_send_file_max_age()
@classmethod
def get_send_file_max_age(
filename: str | None
) - > int | None
Used by :func:send_file to determine the max_age cache value for a given file path if it wasn't passed.
Parameters
| Name | Type | Description |
|---|
| filename | `str | None` |
Returns
send_static_file()
@classmethod
def send_static_file(
filename: str
) - > [Response](../wrappers/response.md?sid=src_flask_wrappers_response)
The view function used to serve files from :attr:static_folder. A route is automatically registered for this view at :attr:static_url_path if :attr:static_folder is set.
Parameters
| Name | Type | Description |
|---|
| filename | str | The name of the file within the static folder to be served |
Returns
| Type | Description |
|---|
[Response](../wrappers/response.md?sid=src_flask_wrappers_response) | A response object containing the requested static file |
open_resource()
@classmethod
def open_resource(
resource: str,
mode: str = rb,
encoding: str | None = null
) - > t.IO[t.AnyStr]
Open a resource file relative to :attr:root_path for reading.
Parameters
| Name | Type | Description |
|---|
| resource | str | Path to the resource relative to the application root path |
| mode | str = rb | The file mode to use; only reading modes like 'r' or 'rb' are supported |
| encoding | `str | None` = null |
Returns
| Type | Description |
|---|
t.IO[t.AnyStr] | A file-like object for the requested resource |
open_instance_resource()
@classmethod
def open_instance_resource(
resource: str,
mode: str = rb,
encoding: str | None = utf-8
) - > t.IO[t.AnyStr]
Open a resource file relative to the application's instance folder :attr:instance_path. Unlike :meth:open_resource, files in the instance folder can be opened for writing.
Parameters
| Name | Type | Description |
|---|
| resource | str | Path to the resource relative to the application's instance folder |
| mode | str = rb | The file mode to use for opening the resource |
| encoding | `str | None` = utf-8 |
Returns
| Type | Description |
|---|
t.IO[t.AnyStr] | A file-like object for the requested instance resource |
create_jinja_environment()
@classmethod
def create_jinja_environment() - > [Environment](../templating/environment.md?sid=src_flask_templating_environment)
Create the Jinja environment based on :attr:jinja_options and the various Jinja-related methods of the app. Changing :attr:jinja_options after this will have no effect. Also adds Flask-related globals and filters to the environment.
Returns
| Type | Description |
|---|
[Environment](../templating/environment.md?sid=src_flask_templating_environment) | The configured Jinja2 environment for template rendering |
create_url_adapter()
@classmethod
def create_url_adapter(
request: Request | None
) - > MapAdapter | None
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.
Parameters
| Name | Type | Description |
|---|
| request | `Request | None` |
Returns
| Type | Description |
|---|
| `MapAdapter | None` |
raise_routing_exception()
@classmethod
def raise_routing_exception(
request: [Request](../wrappers/request.md?sid=src_flask_wrappers_request)
) - > t.NoReturn
Intercept routing exceptions and possibly do something else.
Parameters
| Name | Type | Description |
|---|
| request | [Request](../wrappers/request.md?sid=src_flask_wrappers_request) | The current request object containing the routing exception to be processed |
Returns
| Type | Description |
|---|
t.NoReturn | This method always raises an exception |
update_template_context()
@classmethod
def update_template_context(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext),
context: dict[str, t.Any]
)
Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context used to resolve request and blueprint information |
| context | dict[str, t.Any] | The dictionary of template variables to be updated in place |
make_shell_context()
@classmethod
def make_shell_context() - > dict[str, t.Any]
Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors.
Returns
| Type | Description |
|---|
dict[str, t.Any] | A dictionary containing the variables available in the interactive shell |
run()
@classmethod
def run(
host: str | None = null,
port: int | None = null,
debug: bool | None = null,
load_dotenv: bool = True,
**options: t.Any
)
Runs the application on a local development server. Do not use run() in a production setting.
Parameters
| Name | Type | Description |
|---|
| host | `str | None` = null |
| port | `int | None` = null |
| debug | `bool | None` = null |
| load_dotenv | bool = True | Whether to load environment variables from .env and .flaskenv files |
| **options | t.Any | Additional options forwarded to the underlying Werkzeug server |
test_client()
@classmethod
def test_client(
use_cookies: bool = True,
**kwargs: t.Any
) - > [FlaskClient](../testing/flaskclient.md?sid=src_flask_testing_flaskclient)
Creates a test client for this application. For information about unit testing head over to :doc:/testing.
Parameters
| Name | Type | Description |
|---|
| use_cookies | bool = True | Whether the test client should handle cookies across multiple requests |
| **kwargs | t.Any | Additional arguments passed to the test client class constructor |
Returns
| Type | Description |
|---|
[FlaskClient](../testing/flaskclient.md?sid=src_flask_testing_flaskclient) | A client configured to simulate requests to the application for testing |
test_cli_runner()
@classmethod
def test_cli_runner(
**kwargs: t.Any
) - > [FlaskCliRunner](../testing/flaskclirunner.md?sid=src_flask_testing_flaskclirunner)
Create a CLI runner for testing CLI commands. See :ref:testing-cli.
Parameters
| Name | Type | Description |
|---|
| **kwargs | t.Any | Additional arguments passed to the CLI runner class constructor |
Returns
| Type | Description |
|---|
[FlaskCliRunner](../testing/flaskclirunner.md?sid=src_flask_testing_flaskclirunner) | A runner instance used to invoke and test Click-based CLI commands |
handle_http_exception()
@classmethod
def handle_http_exception(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext),
e: HTTPException
) - > HTTPException | ft.ResponseReturnValue
Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context |
| e | HTTPException | The HTTP exception that needs to be handled |
Returns
| Type | Description |
|---|
| `HTTPException | ft.ResponseReturnValue` |
handle_user_exception()
@classmethod
def handle_user_exception(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext),
e: Exception
) - > HTTPException | ft.ResponseReturnValue
This method is called whenever an exception occurs that should be handled. A special case is :class:~werkzeug .exceptions.HTTPException which is forwarded to the :meth:handle_http_exception method.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context |
| e | Exception | The exception that was raised during request processing |
Returns
| Type | Description |
|---|
| `HTTPException | ft.ResponseReturnValue` |
handle_exception()
@classmethod
def handle_exception(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext),
e: Exception
) - > [Response](../wrappers/response.md?sid=src_flask_wrappers_response)
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.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context |
| e | Exception | The unhandled exception to be logged and processed |
Returns
| Type | Description |
|---|
[Response](../wrappers/response.md?sid=src_flask_wrappers_response) | A 500 Internal Server Error response |
log_exception()
@classmethod
def log_exception(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext),
exc_info: tuple[type, BaseException, TracebackType]| tuple[None, None, None]
)
Logs an exception. This is called by :meth:handle_exception if debugging is disabled and right before the handler is called.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context containing request details |
| exc_info | `tuple[type, BaseException, TracebackType] | tuple[None, None, None]` |
dispatch_request()
@classmethod
def dispatch_request(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)
) - > ft.ResponseReturnValue
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.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context containing the request to dispatch |
Returns
| Type | Description |
|---|
ft.ResponseReturnValue | The return value from the matched view function |
full_dispatch_request()
@classmethod
def full_dispatch_request(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)
) - > [Response](../wrappers/response.md?sid=src_flask_wrappers_response)
Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context |
Returns
| Type | Description |
|---|
[Response](../wrappers/response.md?sid=src_flask_wrappers_response) | The final response object after processing and dispatching |
finalize_request()
@classmethod
def finalize_request(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext),
rv: ft.ResponseReturnValue | HTTPException,
from_error_handler: bool = False
) - > [Response](../wrappers/response.md?sid=src_flask_wrappers_response)
Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context |
| rv | `ft.ResponseReturnValue | HTTPException` |
| from_error_handler | bool = False | Whether this finalization is occurring after an error handler was invoked |
Returns
| Type | Description |
|---|
[Response](../wrappers/response.md?sid=src_flask_wrappers_response) | The finalized response object |
make_default_options_response()
@classmethod
def make_default_options_response(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)
) - > [Response](../wrappers/response.md?sid=src_flask_wrappers_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.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context |
Returns
| Type | Description |
|---|
[Response](../wrappers/response.md?sid=src_flask_wrappers_response) | A response object with the 'Allow' header set to the supported HTTP methods |
ensure_sync()
@classmethod
def ensure_sync(
func: t.Callable[..., t.Any]
) - > t.Callable[..., t.Any]
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.
Parameters
| Name | Type | Description |
|---|
| func | t.Callable[..., t.Any] | The function to be ensured as synchronous |
Returns
| Type | Description |
|---|
t.Callable[..., t.Any] | A synchronous version of the provided function |
async_to_sync()
@classmethod
def async_to_sync(
func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]
) - > t.Callable[..., t.Any]
Return a sync function that will run the coroutine function.
Parameters
| Name | Type | Description |
|---|
| func | t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]] | The coroutine function to convert |
Returns
| Type | Description |
|---|
t.Callable[..., t.Any] | A synchronous wrapper around the coroutine function |
url_for()
@classmethod
def url_for(
endpoint: str,
_anchor: str | None = null,
_method: str | None = null,
_scheme: str | None = null,
_external: bool | None = null,
**values: t.Any
) - > str
Generate a URL to the given endpoint with the given values. This is called by :func:flask.url_for, and can be called directly as well.
Parameters
| Name | Type | Description |
|---|
| endpoint | str | The endpoint name associated with the URL to generate |
| _anchor | `str | None` = null |
| _method | `str | None` = null |
| _scheme | `str | None` = null |
| _external | `bool | None` = null |
| **values | t.Any | Variable parts of the URL rule and query string arguments |
Returns
| Type | Description |
|---|
str | The generated URL string |
make_response()
@classmethod
def make_response(
rv: ft.ResponseReturnValue
) - > [Response](../wrappers/response.md?sid=src_flask_wrappers_response)
Convert the return value from a view function to an instance of :attr:response_class.
Parameters
| Name | Type | Description |
|---|
| rv | ft.ResponseReturnValue | The return value from the view function to be converted |
Returns
| Type | Description |
|---|
[Response](../wrappers/response.md?sid=src_flask_wrappers_response) | A response object derived from the view's return value |
preprocess_request()
@classmethod
def preprocess_request(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)
) - > ft.ResponseReturnValue | None
Called before the request is dispatched. Calls :attr:url_value_preprocessors registered with the app and the current blueprint (if any). Then calls :attr:before_request_funcs registered with the app and the blueprint.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context |
Returns
| Type | Description |
|---|
| `ft.ResponseReturnValue | None` |
process_response()
@classmethod
def process_response(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext),
response: [Response](../wrappers/response.md?sid=src_flask_wrappers_response)
) - > [Response](../wrappers/response.md?sid=src_flask_wrappers_response)
Can be overridden in order to modify the response object before it's sent to the WSGI server. By default this will call all the :meth:after_request decorated functions.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context |
| response | [Response](../wrappers/response.md?sid=src_flask_wrappers_response) | The response object to be modified |
Returns
| Type | Description |
|---|
[Response](../wrappers/response.md?sid=src_flask_wrappers_response) | The processed response object |
do_teardown_request()
@classmethod
def do_teardown_request(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext),
exc: BaseException | None = null
)
Called after the request is dispatched and the response is finalized, right before the request context is popped. Called by :meth:.AppContext.pop.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context |
| exc | `BaseException | None` = null |
do_teardown_appcontext()
@classmethod
def do_teardown_appcontext(
ctx: [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext),
exc: BaseException | None = null
)
Called right before the application context is popped. Called by :meth:.AppContext.pop.
Parameters
| Name | Type | Description |
|---|
| ctx | [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | The current application context |
| exc | `BaseException | None` = null |
app_context()
@classmethod
def app_context() - > [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)
Create an :class:.AppContext. When the context is pushed, :data:.current_app and :data:.g become available.
Returns
| Type | Description |
|---|
[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | A new application context instance |
request_context()
@classmethod
def request_context(
environ: WSGIEnvironment
) - > [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)
Create an :class:.AppContext with request information representing the given WSGI environment. A context is automatically pushed when handling each request.
Parameters
| Name | Type | Description |
|---|
| environ | WSGIEnvironment | A WSGI environment dictionary |
Returns
| Type | Description |
|---|
[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | An application context bound to the provided WSGI environment |
test_request_context()
@classmethod
def test_request_context(
*args: t.Any,
**kwargs: t.Any
) - > [AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)
Create an :class:.AppContext with request information created from the given arguments. When the context is pushed, :data:.request, :data:.session, :data:g:, and :data:.current_app` become available.
Parameters
| Name | Type | Description |
|---|
| *args | t.Any | Positional arguments passed to the EnvironBuilder |
| **kwargs | t.Any | Keyword arguments passed to the EnvironBuilder to configure the request |
Returns
| Type | Description |
|---|
[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext) | An application context suitable for testing request-dependent code |
wsgi_app()
@classmethod
def wsgi_app(
environ: WSGIEnvironment,
start_response: StartResponse
) - > cabc.Iterable[bytes]
The actual WSGI application. This is not implemented in :meth:__call__ so that middlewares can be applied without losing a reference to the app object.
Parameters
| Name | Type | Description |
|---|
| environ | WSGIEnvironment | The WSGI environment dictionary |
| start_response | StartResponse | The WSGI start_response callable |
Returns
| Type | Description |
|---|
cabc.Iterable[bytes] | An iterable of bytes representing the response body |