Skip to main content

Flask

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

AttributeTypeDescription
default_configImmutableDict = ImmutableDict({...})A dictionary containing the default configuration values for the application, including session settings, server names, and limits.
request_classtype[[Request](../wrappers/request.md?sid=src_flask_wrappers_request)] = RequestThe class that is used for request objects.
response_classtype[[Response](../wrappers/response.md?sid=src_flask_wrappers_response)] = ResponseThe 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

NameTypeDescription
import_namestrThe name of the application package.
static_url_path`strNone` = None
static_folder`stros.PathLike[str]
static_host`strNone` = None
host_matchingbool = FalseSet url_map.host_matching attribute.
subdomain_matchingbool = FalseConsider the subdomain relative to SERVER_NAME when matching routes.
template_folder`stros.PathLike[str]
instance_path`strNone` = None
instance_relative_configbool = FalseIf True, relative filenames for loading config are assumed to be relative to the instance path.
root_path`strNone` = 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

NameTypeDescription
filename`strNone`

Returns

TypeDescription
`intNone`

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

NameTypeDescription
filenamestrThe name of the file within the static folder to be served

Returns

TypeDescription
[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

NameTypeDescription
resourcestrPath to the resource relative to the application root path
modestr = rbThe file mode to use; only reading modes like 'r' or 'rb' are supported
encoding`strNone` = null

Returns

TypeDescription
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

NameTypeDescription
resourcestrPath to the resource relative to the application's instance folder
modestr = rbThe file mode to use for opening the resource
encoding`strNone` = utf-8

Returns

TypeDescription
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

TypeDescription
[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

NameTypeDescription
request`RequestNone`

Returns

TypeDescription
`MapAdapterNone`

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

NameTypeDescription
request[Request](../wrappers/request.md?sid=src_flask_wrappers_request)The current request object containing the routing exception to be processed

Returns

TypeDescription
t.NoReturnThis 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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context used to resolve request and blueprint information
contextdict[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

TypeDescription
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

NameTypeDescription
host`strNone` = null
port`intNone` = null
debug`boolNone` = null
load_dotenvbool = TrueWhether to load environment variables from .env and .flaskenv files
**optionst.AnyAdditional 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

NameTypeDescription
use_cookiesbool = TrueWhether the test client should handle cookies across multiple requests
**kwargst.AnyAdditional arguments passed to the test client class constructor

Returns

TypeDescription
[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

NameTypeDescription
**kwargst.AnyAdditional arguments passed to the CLI runner class constructor

Returns

TypeDescription
[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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context
eHTTPExceptionThe HTTP exception that needs to be handled

Returns

TypeDescription
`HTTPExceptionft.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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context
eExceptionThe exception that was raised during request processing

Returns

TypeDescription
`HTTPExceptionft.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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context
eExceptionThe unhandled exception to be logged and processed

Returns

TypeDescription
[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

NameTypeDescription
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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context containing the request to dispatch

Returns

TypeDescription
ft.ResponseReturnValueThe 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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context

Returns

TypeDescription
[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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context
rv`ft.ResponseReturnValueHTTPException`
from_error_handlerbool = FalseWhether this finalization is occurring after an error handler was invoked

Returns

TypeDescription
[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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context

Returns

TypeDescription
[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

NameTypeDescription
funct.Callable[..., t.Any]The function to be ensured as synchronous

Returns

TypeDescription
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

NameTypeDescription
funct.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]The coroutine function to convert

Returns

TypeDescription
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

NameTypeDescription
endpointstrThe endpoint name associated with the URL to generate
_anchor`strNone` = null
_method`strNone` = null
_scheme`strNone` = null
_external`boolNone` = null
**valuest.AnyVariable parts of the URL rule and query string arguments

Returns

TypeDescription
strThe 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

NameTypeDescription
rvft.ResponseReturnValueThe return value from the view function to be converted

Returns

TypeDescription
[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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context

Returns

TypeDescription
`ft.ResponseReturnValueNone`

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

NameTypeDescription
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

TypeDescription
[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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context
exc`BaseExceptionNone` = 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

NameTypeDescription
ctx[AppContext](../ctx/appcontext.md?sid=src_flask_ctx_appcontext)The current application context
exc`BaseExceptionNone` = 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

TypeDescription
[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

NameTypeDescription
environWSGIEnvironmentA WSGI environment dictionary

Returns

TypeDescription
[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

NameTypeDescription
*argst.AnyPositional arguments passed to the EnvironBuilder
**kwargst.AnyKeyword arguments passed to the EnvironBuilder to configure the request

Returns

TypeDescription
[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

NameTypeDescription
environWSGIEnvironmentThe WSGI environment dictionary
start_responseStartResponseThe WSGI start_response callable

Returns

TypeDescription
cabc.Iterable[bytes]An iterable of bytes representing the response body