flask package

Subpackages

Submodules

flask.app module

class flask.app.Flask(import_name: str, static_url_path: str | None = None, static_folder: str | PathLike[str] | None = 'static', static_host: str | None = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: str | PathLike[str] | None = 'templates', instance_path: str | None = None, instance_relative_config: bool = False, root_path: str | None = None)

Bases: App

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:

from flask import Flask
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:

app = Flask('yourapplication')
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)

Added in version 0.7: The static_url_path, static_folder, and template_folder parameters were added.

Added in version 0.8: The instance_path and instance_relative_config parameters were added.

Added in version 0.11: The root_path parameter was added.

Added in version 1.0: The host_matching and static_host parameters were added.

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

Parameters:
  • import_name – the name of the application package

  • static_url_path – 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 – 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 – 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 – set url_map.host_matching attribute. Defaults to False.

  • subdomain_matching – consider the subdomain relative to SERVER_NAME when matching routes. Defaults to False.

  • template_folder – 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 – 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 – 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 – 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.

app_context() AppContext

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.

with app.app_context():
    init_db()

See /appcontext.

Added in version 0.9.

async_to_sync(func: Callable[[...], Coroutine[Any, Any, Any]]) Callable[[...], Any]

Return a sync function that will run the coroutine function.

result = app.async_to_sync(func)(*args, **kwargs)

Override this method to change how the app converts async code to be synchronously callable.

Added in version 2.0.

cli: 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.

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

Changed in version 0.11: Environment.auto_reload set in accordance with TEMPLATES_AUTO_RELOAD configuration option.

Added in version 0.5.

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.

Changed in version 3.1: If SERVER_NAME is set, it does not restrict requests to only that domain, for both subdomain_matching and host_matching.

Changed in version 1.0: SERVER_NAME no longer implicitly enables subdomain matching. Use subdomain_matching instead.

Changed in version 0.9: This can be called outside a request when the URL adapter is created for an application context.

Added in version 0.6.

default_config: dict[str, t.Any] = {'APPLICATION_ROOT': '/', 'DEBUG': None, 'EXPLAIN_TEMPLATE_LOADING': False, 'MAX_CONTENT_LENGTH': None, 'MAX_COOKIE_SIZE': 4093, 'MAX_FORM_MEMORY_SIZE': 500000, 'MAX_FORM_PARTS': 1000, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'PREFERRED_URL_SCHEME': 'http', 'PROPAGATE_EXCEPTIONS': None, 'PROVIDE_AUTOMATIC_OPTIONS': True, 'SECRET_KEY': None, 'SECRET_KEY_FALLBACKS': None, 'SEND_FILE_MAX_AGE_DEFAULT': None, 'SERVER_NAME': None, 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_PARTITIONED': False, '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, 'TRUSTED_HOSTS': None, 'USE_X_SENDFILE': False}
dispatch_request() 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. In order to convert the return value to a proper response object, call make_response().

Changed in version 0.7: This no longer does the exception handling, this code was moved to the new full_dispatch_request().

do_teardown_appcontext(exc: BaseException | None = <object object>) None

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

Added in version 0.9.

do_teardown_request(exc: BaseException | None = <object object>) None

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 – An unhandled exception raised while dispatching the request. Detected from the current exception information if not passed. Passed to each teardown function.

Changed in version 0.9: Added the exc argument.

ensure_sync(func: Callable[[...], Any]) Callable[[...], 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.

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

Added in version 2.0.

finalize_request(rv: ft.ResponseReturnValue | HTTPException, from_error_handler: bool = False) Response

Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions. This is invoked for both normal request dispatching as well as error handlers.

Because this means that it might be called as a result of a failure a special safe mode is available which can be enabled with the from_error_handler flag. If enabled, failures in response processing will be logged and otherwise ignored.

Internal:

full_dispatch_request() Response

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

Added in version 0.7.

get_send_file_max_age(filename: str | None) int | None

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.

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

Added in version 0.9.

handle_exception(e: Exception) 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.

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.

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.

Added in version 0.3.

handle_http_exception(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.

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.

Added in version 0.3.

handle_user_exception(e: Exception) HTTPException | ft.ResponseReturnValue

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.

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.

Added in version 0.7.

log_exception(exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None]) None

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.

Added in version 0.8.

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

Added in version 0.7.

make_response(rv: ft.ResponseReturnValue) Response

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

Parameters:

rv

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.

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() dict[str, Any]

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

Added in version 0.11.

open_instance_resource(resource: str, mode: str = 'rb', encoding: str | None = 'utf-8') IO

Open a resource file relative to the application’s instance folder instance_path. Unlike open_resource(), files in the instance folder can be opened for writing.

Parameters:
  • resource – Path to the resource relative to instance_path.

  • mode – Open the file in this mode.

  • encoding – Open the file with this encoding when opening in text mode. This is ignored when opening in binary mode.

Changed in version 3.1: Added the encoding parameter.

open_resource(resource: str, mode: str = 'rb', encoding: str | None = None) IO

Open a resource file relative to root_path for reading.

For example, if the file schema.sql is next to the file app.py where the Flask app is defined, it can be opened with:

with app.open_resource("schema.sql") as f:
    conn.executescript(f.read())
Parameters:
  • resource – Path to the resource relative to root_path.

  • mode – Open the file in this mode. Only reading is supported, valid values are "r" (or "rt") and "rb".

  • encoding – Open the file with this encoding when opening in text mode. This is ignored when opening in binary mode.

Changed in version 3.1: Added the encoding parameter.

preprocess_request() ft.ResponseReturnValue | None

Called before the request is dispatched. Calls url_value_preprocessors registered with the app and the current blueprint (if any). Then calls before_request_funcs registered with the app and the blueprint.

If any before_request() handler 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.

process_response(response: Response) 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 after_request() decorated functions.

Changed in version 0.5: As of Flask 0.5 the functions registered for after request execution are called in reverse order of registration.

Parameters:

response – a response_class object.

Returns:

a new response object or the same, has to be an instance of response_class.

request_class

The class that is used for request objects. See Request for more information.

alias of Request

request_context(environ: WSGIEnvironment) RequestContext

Create a RequestContext representing a WSGI environment. Use a with block to push the context, which will make request point at this request.

See /reqcontext.

Typically you should not call this from your own code. A request context is automatically pushed by the wsgi_app() when handling a request. Use test_request_context() to create an environment and context instead of this method.

Parameters:

environ – a WSGI environment

response_class

The class that is used for response objects. See Response for more information.

alias of Response

run(host: str | None = None, port: int | None = None, debug: bool | None = None, load_dotenv: bool = True, **options: Any) None

Runs the application on a local development server.

Do not use run() in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see /deploying/index for WSGI server recommendations.

If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened.

If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass use_evalex=False as parameter. This will keep the debugger’s traceback screen active, but disable code execution.

It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the flask command line script’s run support.

Keep in Mind

Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke run() with debug=True and use_reloader=False. Setting use_debugger to True without being in debug mode won’t catch any exceptions because there won’t be any to catch.

Parameters:
  • host – the hostname to listen on. Set this to '0.0.0.0' to have the server available externally as well. Defaults to '127.0.0.1' or the host in the SERVER_NAME config variable if present.

  • port – the port of the webserver. Defaults to 5000 or the port defined in the SERVER_NAME config variable if present.

  • debug – if given, enable or disable debug mode. See debug.

  • load_dotenv – Load the nearest .env and .flaskenv files to set environment variables. Will also change the working directory to the directory containing the first file found.

  • options – the options to be forwarded to the underlying Werkzeug server. See werkzeug.serving.run_simple() for more information.

Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from .env and .flaskenv files.

The FLASK_DEBUG environment variable will override debug.

Threaded mode is enabled by default.

Changed in version 0.10: The default port is now picked from the SERVER_NAME variable.

send_static_file(filename: str) Response

The view function used to serve files from static_folder. A route is automatically registered for this view at static_url_path if static_folder is set.

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

Added in version 0.5.

session_interface: SessionInterface = <flask.sessions.SecureCookieSessionInterface object>

the session interface to use. By default an instance of SecureCookieSessionInterface is used here.

Added in version 0.8.

test_cli_runner(**kwargs: t.Any) FlaskCliRunner

Create a CLI runner for testing CLI commands. See testing-cli.

Returns an instance of test_cli_runner_class, by default FlaskCliRunner. The Flask app object is passed as the first argument.

Added in version 1.0.

test_client(use_cookies: bool = True, **kwargs: t.Any) FlaskClient

Creates a test client for this application. For information about unit testing head over to /testing.

Note that if you are testing for assertions or exceptions in your application code, you must set app.testing = True in order for the exceptions to propagate to the test client. Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client. See the testing attribute. For example:

app.testing = True
client = app.test_client()

The test client can be used in a with block to defer the closing down of the context until the end of the with block. This is useful if you want to access the context locals for testing:

with app.test_client() as c:
    rv = c.get('/?vodka=42')
    assert request.args['vodka'] == '42'

Additionally, you may pass optional keyword arguments that will then be passed to the application’s test_client_class constructor. For example:

from flask.testing import FlaskClient

class CustomClient(FlaskClient):
    def __init__(self, *args, **kwargs):
        self._authentication = kwargs.pop("authentication")
        super(CustomClient,self).__init__( *args, **kwargs)

app.test_client_class = CustomClient
client = app.test_client(authentication='Basic ....')

See FlaskClient for more information.

Changed in version 0.4: added support for with block usage for the client.

Added in version 0.7: The use_cookies parameter was added as well as the ability to override the client to be used by setting the test_client_class attribute.

Changed in version 0.11: Added **kwargs to support passing additional keyword arguments to the constructor of test_client_class.

test_request_context(*args: Any, **kwargs: Any) RequestContext

Create a RequestContext for a WSGI environment created from the given values. This is mostly useful during testing, where you may want to run a function that uses request data without dispatching a full request.

See /reqcontext.

Use a with block to push the context, which will make request point at the request for the created environment.

with app.test_request_context(...):
    generate_report()

When using the shell, it may be easier to push and pop the context manually to avoid indentation.

ctx = app.test_request_context(...)
ctx.push()
...
ctx.pop()

Takes the same arguments as Werkzeug’s EnvironBuilder, with some defaults from the application. See the linked Werkzeug docs for most of the available arguments. Flask-specific behavior is listed here.

Parameters:
  • path – URL path being requested.

  • base_url – Base URL where the app is being served, which path is relative to. If not given, built from PREFERRED_URL_SCHEME, subdomain, SERVER_NAME, and APPLICATION_ROOT.

  • subdomain – Subdomain name to append to SERVER_NAME.

  • url_scheme – Scheme to use instead of PREFERRED_URL_SCHEME.

  • data – The request body, either as a string or a dict of form keys and values.

  • json – If given, this is serialized as JSON and passed as data. Also defaults content_type to application/json.

  • args – other positional arguments passed to EnvironBuilder.

  • kwargs – other keyword arguments passed to EnvironBuilder.

update_template_context(context: dict[str, Any]) None

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. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key.

Parameters:

context – the context as a dictionary that is updated in place to add extra variables.

url_for(endpoint: str, *, _anchor: str | None = None, _method: str | None = None, _scheme: str | None = None, _external: bool | None = None, **values: Any) str

Generate a URL to the given endpoint with the given values.

This is called by flask.url_for(), and can be called directly as well.

An endpoint is the name of a URL rule, usually added with @app.route(), and usually the same name as the view function. A route defined in a Blueprint will prepend the blueprint’s name separated by a . to the endpoint.

In some cases, such as email messages, you want URLs to include the scheme and domain, like https://example.com/hello. When not in an active request, URLs will be external by default, but this requires setting SERVER_NAME so Flask knows what domain to use. APPLICATION_ROOT and PREFERRED_URL_SCHEME should also be configured as needed. This config is only used when not in an active request.

Functions can be decorated with url_defaults() to modify keyword arguments before the URL is built.

If building fails for some reason, such as an unknown endpoint or incorrect values, the app’s handle_url_build_error() method is called. If that returns a string, that is returned, otherwise a BuildError is raised.

Parameters:
  • endpoint – The endpoint name associated with the URL to generate. If this starts with a ., the current blueprint name (if any) will be used.

  • _anchor – If given, append this as #anchor to the URL.

  • _method – If given, generate the URL associated with this method for the endpoint.

  • _scheme – If given, the URL will have this scheme if it is external.

  • _external – If given, prefer the URL to be internal (False) or require it to be external (True). External URLs include the scheme and domain. When not in an active request, URLs are external by default.

  • values – Values to use for the variable parts of the URL rule. Unknown keys are appended as query string arguments, like ?a=b&c=d.

Added in version 2.2: Moved from flask.url_for, which calls this method.

wsgi_app(environ: WSGIEnvironment, start_response: StartResponse) cabc.Iterable[bytes]

The actual WSGI application. This is not implemented in __call__() so that middlewares can be applied without losing a reference to the app object. Instead of doing this:

app = MyMiddleware(app)

It’s a better idea to do this instead:

app.wsgi_app = MyMiddleware(app.wsgi_app)

Then you still have the original application object around and can continue to call methods on it.

Changed in version 0.7: Teardown events for the request and app contexts are called even if an unhandled error occurs. Other events may not be called depending on when an error occurs during dispatch. See callbacks-and-errors.

Parameters:
  • environ – A WSGI environment.

  • start_response – A callable accepting a status code, a list of headers, and an optional exception context to start the response.

flask.blueprints module

class flask.blueprints.Blueprint(name: str, import_name: str, static_folder: str | ~os.PathLike[str] | None = None, static_url_path: str | None = None, template_folder: str | ~os.PathLike[str] | None = None, url_prefix: str | None = None, subdomain: str | None = None, url_defaults: dict[str, ~typing.Any] | None = None, root_path: str | None = None, cli_group: str | None = <object object>)

Bases: Blueprint

cli: 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.

get_send_file_max_age(filename: str | None) int | None

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.

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

Added in version 0.9.

open_resource(resource: str, mode: str = 'rb', encoding: str | None = 'utf-8') IO

Open a resource file relative to root_path for reading. The blueprint-relative equivalent of the app’s open_resource() method.

Parameters:
  • resource – Path to the resource relative to root_path.

  • mode – Open the file in this mode. Only reading is supported, valid values are "r" (or "rt") and "rb".

  • encoding – Open the file with this encoding when opening in text mode. This is ignored when opening in binary mode.

Changed in version 3.1: Added the encoding parameter.

send_static_file(filename: str) Response

The view function used to serve files from static_folder. A route is automatically registered for this view at static_url_path if static_folder is set.

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

Added in version 0.5.

flask.cli module

class flask.cli.AppGroup(name: str | None = None, commands: MutableMapping[str, Command] | Sequence[Command] | None = None, **attrs: Any)

Bases: Group

This works similar to a regular click Group but it changes the behavior of the command() decorator so that it automatically wraps the functions in with_appcontext().

Not to be confused with FlaskGroup.

command(*args: Any, **kwargs: Any) Callable[[Callable[[...], Any]], Command]

This works exactly like the method of the same name on a regular click.Group but it wraps callbacks in with_appcontext() unless it’s disabled by passing with_appcontext=False.

group(*args: Any, **kwargs: Any) Callable[[Callable[[...], Any]], Group]

This works exactly like the method of the same name on a regular click.Group but it defaults the group class to AppGroup.

class flask.cli.CertParamType

Bases: ParamType

Click option type for the --cert option. Allows either an existing file, the string 'adhoc', or an import for a SSLContext object.

convert(value: Any, param: Parameter | None, ctx: Context | None) Any

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value – The value to convert.

  • param – The parameter that is using this type to convert its value. May be None.

  • ctx – The current context that arrived at this value. May be None.

name: str = 'path'

the descriptive name of this type

class flask.cli.FlaskGroup(add_default_commands: bool = True, create_app: t.Callable[..., Flask] | None = None, add_version_option: bool = True, load_dotenv: bool = True, set_debug_flag: bool = True, **extra: t.Any)

Bases: AppGroup

Special subclass of the AppGroup group that supports loading more commands from the configured Flask app. Normally a developer does not have to interface with this class but there are some very advanced use cases for which it makes sense to create an instance of this. see custom-scripts.

Parameters:
  • add_default_commands – if this is True then the default run and shell commands will be added.

  • add_version_option – adds the --version option.

  • create_app – an optional callback that is passed the script info and returns the loaded app.

  • load_dotenv – Load the nearest .env and .flaskenv files to set environment variables. Will also change the working directory to the directory containing the first file found.

  • set_debug_flag – Set the app’s debug flag.

Changed in version 3.1: -e path takes precedence over default .env and .flaskenv files.

Changed in version 2.2: Added the -A/--app, --debug/--no-debug, -e/--env-file options.

Changed in version 2.2: An app context is pushed when running app.cli commands, so @with_appcontext is no longer required for those commands.

Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from .env and .flaskenv files.

get_command(ctx: Context, name: str) Command | None

Given a context and a command name, this returns a Command object if it exists or returns None.

list_commands(ctx: Context) list[str]

Returns a list of subcommand names in the order they should appear.

make_context(info_name: str | None, args: list[str], parent: Context | None = None, **extra: Any) Context

This function when given an info name and arguments will kick off the parsing and create a new Context. It does not invoke the actual command callback though.

To quickly customize the context class used without overriding this method, set the context_class attribute.

Parameters:
  • info_name – the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it’s usually the name of the script, for commands below it’s the name of the command.

  • args – the arguments to parse as list of strings.

  • parent – the parent context if available.

  • extra – extra keyword arguments forwarded to the context constructor.

Changed in version 8.0: Added the context_class attribute.

parse_args(ctx: Context, args: list[str]) list[str]

Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by make_context().

exception flask.cli.NoAppException(message: str, ctx: Context | None = None)

Bases: UsageError

Raised if an application cannot be found or loaded.

class flask.cli.ScriptInfo(app_import_path: str | None = None, create_app: t.Callable[..., Flask] | None = None, set_debug_flag: bool = True, load_dotenv_defaults: bool = True)

Bases: object

Helper object to deal with Flask applications. This is usually not necessary to interface with as it’s used internally in the dispatching to click. In future versions of Flask this object will most likely play a bigger role. Typically it’s created automatically by the FlaskGroup but you can also manually create it and pass it onwards as click object.

Changed in version 3.1: Added the load_dotenv_defaults parameter and attribute.

app_import_path

Optionally the import path for the Flask application.

create_app

Optionally a function that is passed the script info to create the instance of the application.

data: dict[t.Any, t.Any]

A dictionary with arbitrary data that can be associated with this script info.

load_app() Flask

Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned.

load_dotenv_defaults

Whether default .flaskenv and .env files should be loaded.

ScriptInfo doesn’t load anything, this is for reference when doing the load elsewhere during processing.

Added in version 3.1.

class flask.cli.SeparatedPathType(exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: Type[Any] | None = None, executable: bool = False)

Bases: Path

Click option type that accepts a list of values separated by the OS’s path separator (:, ; on Windows). Each value is validated as a click.Path type.

convert(value: Any, param: Parameter | None, ctx: Context | None) Any

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value – The value to convert.

  • param – The parameter that is using this type to convert its value. May be None.

  • ctx – The current context that arrived at this value. May be None.

flask.cli.find_app_by_string(module: ModuleType, app_name: str) Flask

Check if the given string is a variable name or a function. Call a function to get the app instance, or return the variable directly.

flask.cli.find_best_app(module: ModuleType) Flask

Given a module instance this tries to find the best possible application in the module or raises an exception.

flask.cli.get_version(ctx: Context, param: Parameter, value: Any) None
flask.cli.load_dotenv(path: str | PathLike[str] | None = None, load_defaults: bool = True) bool

Load “dotenv” files to set environment variables. A given path takes precedence over .env, which takes precedence over .flaskenv. After loading and combining these files, values are only set if the key is not already set in os.environ.

This is a no-op if python-dotenv is not installed.

Parameters:
  • path – Load the file at this location.

  • load_defaults – Search for and load the default .flaskenv and .env files.

Returns:

True if at least one env var was loaded.

Changed in version 3.1: Added the load_defaults parameter. A given path takes precedence over default files.

Changed in version 2.0: The current directory is not changed to the location of the loaded file.

Changed in version 2.0: When loading the env files, set the default encoding to UTF-8.

Changed in version 1.1.0: Returns False when python-dotenv is not installed, or when the given path isn’t a file.

Added in version 1.0.

flask.cli.locate_app(module_name: str, app_name: str | None, raise_if_not_found: Literal[True] = True) Flask
flask.cli.locate_app(module_name: str, app_name: str | None, raise_if_not_found: Literal[False] = True) Flask | None
flask.cli.main() None
flask.cli.prepare_import(path: str) str

Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected.

flask.cli.show_server_banner(debug: bool, app_import_path: str | None) None

Show extra startup messages the first time the server is run, ignoring the reloader.

flask.cli.with_appcontext(f: F) F

Wraps a callback so that it’s guaranteed to be executed with the script’s application context.

Custom commands (and their options) registered under app.cli or blueprint.cli will always have an app context available, this decorator is not required in that case.

Changed in version 2.2: The app context is active for subcommands as well as the decorated callback. The app context is always available to app.cli command and parameter callbacks.

flask.config module

class flask.config.Config(root_path: str | PathLike[str], defaults: dict[str, Any] | None = None)

Bases: dict

Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config.

Either you can fill the config from a config file:

app.config.from_pyfile('yourconfig.cfg')

Or alternatively you can define the configuration options in the module that calls from_object() or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:

DEBUG = True
SECRET_KEY = 'development key'
app.config.from_object(__name__)

In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application.

Probably the most interesting way to load configurations is from an environment variable pointing to a file:

app.config.from_envvar('YOURAPPLICATION_SETTINGS')

In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:

export YOURAPPLICATION_SETTINGS='/path/to/config/file'

On windows use set instead.

Parameters:
  • root_path – path to which files are read relative from. When the config object is created by the application, this is the application’s root_path.

  • defaults – an optional dictionary of default values

from_envvar(variable_name: str, silent: bool = False) bool

Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:

app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
Parameters:
  • variable_name – name of the environment variable

  • silent – set to True if you want silent failure for missing files.

Returns:

True if the file was loaded successfully.

from_file(filename: str | PathLike[str], load: Callable[[IO[Any]], Mapping[str, Any]], silent: bool = False, text: bool = True) bool

Update the values in the config from a file that is loaded using the load parameter. The loaded data is passed to the from_mapping() method.

import json
app.config.from_file("config.json", load=json.load)

import tomllib
app.config.from_file("config.toml", load=tomllib.load, text=False)
Parameters:
  • filename – The path to the data file. This can be an absolute path or relative to the config root path.

  • load (Callable[[Reader], Mapping] where Reader implements a read method.) – A callable that takes a file handle and returns a mapping of loaded data from the file.

  • silent – Ignore the file if it doesn’t exist.

  • text – Open the file in text or binary mode.

Returns:

True if the file was loaded successfully.

Changed in version 2.3: The text parameter was added.

Added in version 2.0.

from_mapping(mapping: Mapping[str, Any] | None = None, **kwargs: Any) bool

Updates the config like update() ignoring items with non-upper keys.

Returns:

Always returns True.

Added in version 0.11.

from_object(obj: object | str) None

Updates the values from the given object. An object can be of one of the following two types:

  • a string: in this case the object with that name will be imported

  • an actual object reference: that object is used directly

Objects are usually either modules or classes. from_object() loads only the uppercase attributes of the module/class. A dict object will not work with from_object() because the keys of a dict are not attributes of the dict class.

Example of module-based configuration:

app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)

Nothing is done to the object before loading. If the object is a class and has @property attributes, it needs to be instantiated before being passed to this method.

You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with from_pyfile() and ideally from a location not within the package because the package might be installed system wide.

See config-dev-prod for an example of class-based configuration using from_object().

Parameters:

obj – an import name or object

from_prefixed_env(prefix: str = 'FLASK', *, loads: ~typing.Callable[[str], ~typing.Any] = <function loads>) bool

Load any environment variables that start with FLASK_, dropping the prefix from the env key for the config key. Values are passed through a loading function to attempt to convert them to more specific types than strings.

Keys are loaded in sorted() order.

The default loading function attempts to parse values as any valid JSON type, including dicts and lists.

Specific items in nested dicts can be set by separating the keys with double underscores (__). If an intermediate key doesn’t exist, it will be initialized to an empty dict.

Parameters:
  • prefix – Load env vars that start with this prefix, separated with an underscore (_).

  • loads – Pass each string value to this function and use the returned value as the config value. If any error is raised it is ignored and the value remains a string. The default is json.loads().

Added in version 2.1.

from_pyfile(filename: str | PathLike[str], silent: bool = False) bool

Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the from_object() function.

Parameters:
  • filename – the filename of the config. This can either be an absolute filename or a filename relative to the root path.

  • silent – set to True if you want silent failure for missing files.

Returns:

True if the file was loaded successfully.

Added in version 0.7: silent parameter.

get_namespace(namespace: str, lowercase: bool = True, trim_namespace: bool = True) dict[str, Any]

Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:

app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE_')

The resulting dictionary image_store_config would look like:

{
    'type': 'fs',
    'path': '/var/app/images',
    'base_url': 'http://img.website.com'
}

This is often useful when configuration options map directly to keyword arguments in functions or class constructors.

Parameters:
  • namespace – a configuration namespace

  • lowercase – a flag indicating if the keys of the resulting dictionary should be lowercase

  • trim_namespace – a flag indicating if the keys of the resulting dictionary should not include the namespace

Added in version 0.11.

class flask.config.ConfigAttribute(name: str, get_converter: Callable[[Any], T] | None = None)

Bases: Generic[T]

Makes an attribute forward to the config

flask.ctx module

class flask.ctx.AppContext(app: Flask)

Bases: object

The app context contains application-specific information. An app context is created and pushed at the beginning of each request if one is not already active. An app context is also pushed when running CLI commands.

pop(exc: BaseException | None = <object object>) None

Pops the app context.

push() None

Binds the app context to the current context.

class flask.ctx.RequestContext(app: Flask, environ: WSGIEnvironment, request: Request | None = None, session: SessionMixin | None = None)

Bases: object

The request context contains per-request information. The Flask app creates and pushes it at the beginning of the request, then pops it at the end of the request. It will create the URL adapter and request object for the WSGI environment provided.

Do not attempt to use this class directly, instead use test_request_context() and request_context() to create this object.

When the request context is popped, it will evaluate all the functions registered on the application for teardown execution (teardown_request()).

The request context is automatically popped at the end of the request. When using the interactive debugger, the context will be restored so request is still accessible. Similarly, the test client can preserve the context after the request ends. However, teardown functions may already have closed some resources such as database connections.

copy() RequestContext

Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked.

Added in version 0.10.

Changed in version 1.1: The current session object is used instead of reloading the original data. This prevents flask.session pointing to an out-of-date object.

match_request() None

Can be overridden by a subclass to hook into the matching of the request.

pop(exc: BaseException | None = <object object>) None

Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the teardown_request() decorator.

Changed in version 0.9: Added the exc argument.

push() None
flask.ctx.after_this_request(f: Callable[[Any], Any] | Callable[[Any], Awaitable[Any]]) Callable[[Any], Any] | Callable[[Any], Awaitable[Any]]

Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one.

Example:

@app.route('/')
def index():
    @after_this_request
    def add_header(response):
        response.headers['X-Foo'] = 'Parachute'
        return response
    return 'Hello World!'

This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object.

Added in version 0.9.

flask.ctx.copy_current_request_context(f: F) F

A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. The current session is also included in the copied request context.

Example:

import gevent
from flask import copy_current_request_context

@app.route('/')
def index():
    @copy_current_request_context
    def do_some_work():
        # do some work here, it can access flask.request or
        # flask.session like you would otherwise in the view function.
        ...
    gevent.spawn(do_some_work)
    return 'Regular response'

Added in version 0.10.

flask.ctx.has_app_context() bool

Works like has_request_context() but for the application context. You can also just do a boolean check on the current_app object instead.

Added in version 0.9.

flask.ctx.has_request_context() bool

If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable.

class User(db.Model):

    def __init__(self, username, remote_addr=None):
        self.username = username
        if remote_addr is None and has_request_context():
            remote_addr = request.remote_addr
        self.remote_addr = remote_addr

Alternatively you can also just test any of the context bound objects (such as request or g) for truthness:

class User(db.Model):

    def __init__(self, username, remote_addr=None):
        self.username = username
        if remote_addr is None and request:
            remote_addr = request.remote_addr
        self.remote_addr = remote_addr

Added in version 0.7.

flask.debughelpers module

exception flask.debughelpers.DebugFilesKeyError(request: Request, key: str)

Bases: KeyError, AssertionError

Raised from request.files during debugging. The idea is that it can provide a better error message than just a generic KeyError/BadRequest.

exception flask.debughelpers.FormDataRoutingRedirect(request: Request)

Bases: AssertionError

This exception is raised in debug mode if a routing redirect would cause the browser to drop the method or body. This happens when method is not GET, HEAD or OPTIONS and the status code is not 307 or 308.

exception flask.debughelpers.UnexpectedUnicodeError

Bases: AssertionError, UnicodeError

Raised in places where we want some better error reporting for unexpected unicode or binary data.

flask.debughelpers.explain_template_loading_attempts(app: App, template: str, attempts: list[tuple[BaseLoader, Scaffold, tuple[str, str | None, t.Callable[[], bool] | None] | None]]) None

This should help developers understand what failed

flask.globals module

flask.helpers module

flask.helpers.abort(code: int | Response, *args: Any, **kwargs: Any) NoReturn

Raise an HTTPException for the given status code.

If current_app is available, it will call its aborter object, otherwise it will use werkzeug.exceptions.abort().

Parameters:
  • code – The status code for the exception, which must be registered in app.aborter.

  • args – Passed to the exception.

  • kwargs – Passed to the exception.

Added in version 2.2: Calls current_app.aborter if available instead of always using Werkzeug’s default abort.

flask.helpers.flash(message: str, category: str = 'message') None

Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call get_flashed_messages().

Changed in version 0.3: category parameter added.

Parameters:
  • message – the message to be flashed.

  • category – the category for the message. The following values are recommended: 'message' for any kind of message, 'error' for errors, 'info' for information messages and 'warning' for warnings. However any kind of string can be used as category.

flask.helpers.get_debug_flag() bool

Get whether debug mode should be enabled for the app, indicated by the FLASK_DEBUG environment variable. The default is False.

flask.helpers.get_flashed_messages(with_categories: bool = False, category_filter: Iterable[str] = ()) list[str] | list[tuple[str, str]]

Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when with_categories is set to True, the return value will be a list of tuples in the form (category, message) instead.

Filter the flashed messages to one or more categories by providing those categories in category_filter. This allows rendering categories in separate html blocks. The with_categories and category_filter arguments are distinct:

  • with_categories controls whether categories are returned with message text (True gives a tuple, where False gives just the message text).

  • category_filter filters the messages down to only those matching the provided categories.

See /patterns/flashing for examples.

Changed in version 0.3: with_categories parameter added.

Changed in version 0.9: category_filter parameter added.

Parameters:
  • with_categories – set to True to also receive categories.

  • category_filter – filter of categories to limit return values. Only categories in the list will be returned.

flask.helpers.get_load_dotenv(default: bool = True) bool

Get whether the user has disabled loading default dotenv files by setting FLASK_SKIP_DOTENV. The default is True, load the files.

Parameters:

default – What to return if the env var isn’t set.

flask.helpers.get_template_attribute(template_name: str, attribute: str) Any

Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named _cider.html with the following contents:

{% macro hello(name) %}Hello {{ name }}!{% endmacro %}

You can access this from Python code like this:

hello = get_template_attribute('_cider.html', 'hello')
return hello('World')

Added in version 0.2.

Parameters:
  • template_name – the name of the template

  • attribute – the name of the variable of macro to access

flask.helpers.make_response(*args: t.Any) Response

Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.

If view looked like this and you want to add a new header:

def index():
    return render_template('index.html', foo=42)

You can now do something like this:

def index():
    response = make_response(render_template('index.html', foo=42))
    response.headers['X-Parachutes'] = 'parachutes are cool'
    return response

This function accepts the very same arguments you can return from a view function. This for example creates a response with a 404 error code:

response = make_response(render_template('not_found.html'), 404)

The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators:

response = make_response(view_function())
response.headers['X-Parachutes'] = 'parachutes are cool'

Internally this function does the following things:

  • if no arguments are passed, it creates a new response argument

  • if one argument is passed, flask.Flask.make_response() is invoked with it.

  • if more than one argument is passed, the arguments are passed to the flask.Flask.make_response() function as tuple.

Added in version 0.6.

flask.helpers.redirect(location: str, code: int = 302, Response: type[Response] | None = None) Response

Create a redirect response object.

If current_app is available, it will use its redirect() method, otherwise it will use werkzeug.utils.redirect().

Parameters:
  • location – The URL to redirect to.

  • code – The status code for the redirect.

  • Response – The response class to use. Not used when current_app is active, which uses app.response_class.

Added in version 2.2: Calls current_app.redirect if available instead of always using Werkzeug’s default redirect.

flask.helpers.send_file(path_or_file: os.PathLike[t.AnyStr] | str | t.BinaryIO, mimetype: str | None = None, as_attachment: bool = False, download_name: str | None = None, conditional: bool = True, etag: bool | str = True, last_modified: datetime | int | float | None = None, max_age: None | int | t.Callable[[str | None], int | None] = None) Response

Send the contents of a file to the client.

The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with io.BytesIO.

Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn’t intend. Use send_from_directory() to safely serve user-requested paths from within a directory.

If the WSGI server sets a file_wrapper in environ, it is used, otherwise Werkzeug’s built-in wrapper is used. Alternatively, if the HTTP server supports X-Sendfile, configuring Flask with USE_X_SENDFILE = True will tell the server to send the given path, which is much more efficient than reading it in Python.

Parameters:
  • path_or_file – The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data.

  • mimetype – The MIME type to send for the file. If not provided, it will try to detect it from the file name.

  • as_attachment – Indicate to a browser that it should offer to save the file instead of displaying it.

  • download_name – The default name browsers will use when saving the file. Defaults to the passed file name.

  • conditional – Enable conditional and range responses based on request headers. Requires passing a file path and environ.

  • etag – Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead.

  • last_modified – The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path.

  • max_age – How long the client should cache the file, in seconds. If set, Cache-Control will be public, otherwise it will be no-cache to prefer conditional caching.

Changed in version 2.0: download_name replaces the attachment_filename parameter. If as_attachment=False, it is passed with Content-Disposition: inline instead.

Changed in version 2.0: max_age replaces the cache_timeout parameter. conditional is enabled and max_age is not set by default.

Changed in version 2.0: etag replaces the add_etags parameter. It can be a string to use instead of generating one.

Changed in version 2.0: Passing a file-like object that inherits from TextIOBase will raise a ValueError rather than sending an empty file.

Added in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments.

Changed in version 1.1: filename may be a PathLike object.

Changed in version 1.1: Passing a BytesIO object supports range requests.

Changed in version 1.0.3: Filenames are encoded with ASCII instead of Latin-1 for broader compatibility with WSGI servers.

Changed in version 1.0: UTF-8 filenames as specified in RFC 2231 are supported.

Changed in version 0.12: The filename is no longer automatically inferred from file objects. If you want to use automatic MIME and etag support, pass a filename via filename_or_fp or attachment_filename.

Changed in version 0.12: attachment_filename is preferred over filename for MIME detection.

Changed in version 0.9: cache_timeout defaults to Flask.get_send_file_max_age().

Changed in version 0.7: MIME guessing and etag support for file-like objects was removed because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself.

Changed in version 0.5: The add_etags, cache_timeout and conditional parameters were added. The default behavior is to add etags.

Added in version 0.2.

flask.helpers.send_from_directory(directory: os.PathLike[str] | str, path: os.PathLike[str] | str, **kwargs: t.Any) Response

Send a file from within a directory using send_file().

@app.route("/uploads/<path:name>")
def download_file(name):
    return send_from_directory(
        app.config['UPLOAD_FOLDER'], name, as_attachment=True
    )

This is a secure way to serve files from a folder, such as static files or uploads. Uses safe_join() to ensure the path coming from the client is not maliciously crafted to point outside the specified directory.

If the final path does not point to an existing regular file, raises a 404 NotFound error.

Parameters:
  • directory – The directory that path must be located under, relative to the current application’s root path. This must not be a value provided by the client, otherwise it becomes insecure.

  • path – The path to the file to send, relative to directory.

  • kwargs – Arguments to pass to send_file().

Changed in version 2.0: path replaces the filename parameter.

Added in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments.

Added in version 0.5.

flask.helpers.stream_with_context(generator_or_function: Iterator) Iterator
flask.helpers.stream_with_context(generator_or_function: Callable[[...], Iterator]) Callable[[Iterator], Iterator]

Request contexts disappear when the response is started on the server. This is done for efficiency reasons and to make it less likely to encounter memory leaks with badly written WSGI middlewares. The downside is that if you are using streamed responses, the generator cannot access request bound information any more.

This function however can help you keep the context around for longer:

from flask import stream_with_context, request, Response

@app.route('/stream')
def streamed_response():
    @stream_with_context
    def generate():
        yield 'Hello '
        yield request.args['name']
        yield '!'
    return Response(generate())

Alternatively it can also be used around a specific generator:

from flask import stream_with_context, request, Response

@app.route('/stream')
def streamed_response():
    def generate():
        yield 'Hello '
        yield request.args['name']
        yield '!'
    return Response(stream_with_context(generate()))

Added in version 0.9.

flask.helpers.url_for(endpoint: str, *, _anchor: str | None = None, _method: str | None = None, _scheme: str | None = None, _external: bool | None = None, **values: Any) str

Generate a URL to the given endpoint with the given values.

This requires an active request or application context, and calls current_app.url_for(). See that method for full documentation.

Parameters:
  • endpoint – The endpoint name associated with the URL to generate. If this starts with a ., the current blueprint name (if any) will be used.

  • _anchor – If given, append this as #anchor to the URL.

  • _method – If given, generate the URL associated with this method for the endpoint.

  • _scheme – If given, the URL will have this scheme if it is external.

  • _external – If given, prefer the URL to be internal (False) or require it to be external (True). External URLs include the scheme and domain. When not in an active request, URLs are external by default.

  • values – Values to use for the variable parts of the URL rule. Unknown keys are appended as query string arguments, like ?a=b&c=d.

Changed in version 2.2: Calls current_app.url_for, allowing an app to override the behavior.

Changed in version 0.10: The _scheme parameter was added.

Changed in version 0.9: The _anchor and _method parameters were added.

Changed in version 0.9: Calls app.handle_url_build_error on build errors.

flask.logging module

flask.logging.create_logger(app: App) logging.Logger

Get the Flask app’s logger and configure it if needed.

The logger name will be the same as app.import_name.

When debug is enabled, set the logger level to logging.DEBUG if it is not set.

If there is no handler for the logger’s effective level, add a StreamHandler for wsgi_errors_stream() with a basic format.

flask.logging.default_handler = <StreamHandler <stderr> (NOTSET)>

Log messages to wsgi_errors_stream() with the format [%(asctime)s] %(levelname)s in %(module)s: %(message)s.

flask.logging.has_level_handler(logger: Logger) bool

Check if there is a handler in the logging chain that will handle the given logger’s effective level.

flask.sessions module

class flask.sessions.NullSession(initial: Mapping[str, Any] | Iterable[tuple[str, Any]] | None = None)

Bases: SecureCookieSession

Class used to generate nicer error messages if sessions are not available. Will still allow read-only access to the empty session but fail on setting.

clear() None.  Remove all items from D.
pop(k[, d]) v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem(*args: Any, **kwargs: Any) NoReturn

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault(*args: Any, **kwargs: Any) NoReturn

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) None.  Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

class flask.sessions.SecureCookieSession(initial: Mapping[str, Any] | Iterable[tuple[str, Any]] | None = None)

Bases: CallbackDict[str, Any], SessionMixin

Base class for sessions based on signed cookies.

This session backend will set the modified and accessed attributes. It cannot reliably track whether a session is new (vs. empty), so new remains hard coded to False.

accessed = False

header, which allows caching proxies to cache different pages for different users.

get(key: str, default: Any | None = None) Any

Return the value for key if key is in the dictionary, else default.

modified = False

When data is changed, this is set to True. Only the session dictionary itself is tracked; if the session contains mutable data (for example a nested dict) then this must be set to True manually when modifying that data. The session cookie will only be written to the response if this is True.

setdefault(key: str, default: Any | None = None) Any

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

class flask.sessions.SecureCookieSessionInterface

Bases: SessionInterface

The default session interface that stores sessions in signed cookies through the itsdangerous module.

static digest_method(string: bytes = b'') Any

the hash function to use for the signature. The default is sha1

get_signing_serializer(app: Flask) URLSafeTimedSerializer | None
key_derivation = 'hmac'

the name of the itsdangerous supported key derivation. The default is hmac.

open_session(app: Flask, request: Request) SecureCookieSession | None

This is called at the beginning of each request, after pushing the request context, before matching the URL.

This must return an object which implements a dictionary-like interface as well as the SessionMixin interface.

This will return None to indicate that loading failed in some way that is not immediately an error. The request context will fall back to using make_null_session() in this case.

salt = 'cookie-session'

the salt that should be applied on top of the secret key for the signing of cookie based sessions.

save_session(app: Flask, session: SessionMixin, response: Response) None

This is called at the end of each request, after generating a response, before removing the request context. It is skipped if is_null_session() returns True.

serializer = <flask.json.tag.TaggedJSONSerializer object>

A python serializer for the payload. The default is a compact JSON derived serializer with support for some extra Python types such as datetime objects or tuples.

session_class

alias of SecureCookieSession

class flask.sessions.SessionInterface

Bases: object

The basic interface you have to implement in order to replace the default session interface which uses werkzeug’s securecookie implementation. The only methods you have to implement are open_session() and save_session(), the others have useful defaults which you don’t need to change.

The session object returned by the open_session() method has to provide a dictionary like interface plus the properties and methods from the SessionMixin. We recommend just subclassing a dict and adding that mixin:

class Session(dict, SessionMixin):
    pass

If open_session() returns None Flask will call into make_null_session() to create a session that acts as replacement if the session support cannot work because some requirement is not fulfilled. The default NullSession class that is created will complain that the secret key was not set.

To replace the session interface on an application all you have to do is to assign flask.Flask.session_interface:

app = Flask(__name__)
app.session_interface = MySessionInterface()

Multiple requests with the same session may be sent and handled concurrently. When implementing a new session interface, consider whether reads or writes to the backing store must be synchronized. There is no guarantee on the order in which the session for each request is opened or saved, it will occur in the order that requests begin and end processing.

Added in version 0.8.

The value of the Domain parameter on the session cookie. If not set, browsers will only send the cookie to the exact domain it was set from. Otherwise, they will send it to any subdomain of the given value as well.

Uses the SESSION_COOKIE_DOMAIN config.

Changed in version 2.3: Not set by default, does not fall back to SERVER_NAME.

Returns True if the session cookie should be httponly. This currently just returns the value of the SESSION_COOKIE_HTTPONLY config var.

The name of the session cookie. Uses``app.config[“SESSION_COOKIE_NAME”]``.

Returns True if the cookie should be partitioned. By default, uses the value of SESSION_COOKIE_PARTITIONED.

Added in version 3.1.

Returns the path for which the cookie should be valid. The default implementation uses the value from the SESSION_COOKIE_PATH config var if it’s set, and falls back to APPLICATION_ROOT or uses / if it’s None.

Return 'Strict' or 'Lax' if the cookie should use the SameSite attribute. This currently just returns the value of the SESSION_COOKIE_SAMESITE setting.

Returns True if the cookie should be secure. This currently just returns the value of the SESSION_COOKIE_SECURE setting.

get_expiration_time(app: Flask, session: SessionMixin) datetime | None

A helper method that returns an expiration date for the session or None if the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application.

is_null_session(obj: object) bool

Checks if a given object is a null session. Null sessions are not asked to be saved.

This checks if the object is an instance of null_session_class by default.

make_null_session(app: Flask) NullSession

Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed.

This creates an instance of null_session_class by default.

null_session_class

make_null_session() will look here for the class that should be created when a null session is requested. Likewise the is_null_session() method will perform a typecheck against this type.

alias of NullSession

open_session(app: Flask, request: Request) SessionMixin | None

This is called at the beginning of each request, after pushing the request context, before matching the URL.

This must return an object which implements a dictionary-like interface as well as the SessionMixin interface.

This will return None to indicate that loading failed in some way that is not immediately an error. The request context will fall back to using make_null_session() in this case.

pickle_based = False

A flag that indicates if the session interface is pickle based. This can be used by Flask extensions to make a decision in regards to how to deal with the session object.

Added in version 0.10.

save_session(app: Flask, session: SessionMixin, response: Response) None

This is called at the end of each request, after generating a response, before removing the request context. It is skipped if is_null_session() returns True.

Used by session backends to determine if a Set-Cookie header should be set for this session cookie for this response. If the session has been modified, the cookie is set. If the session is permanent and the SESSION_REFRESH_EACH_REQUEST config is true, the cookie is always set.

This check is usually skipped if the session was deleted.

Added in version 0.11.

class flask.sessions.SessionMixin

Bases: MutableMapping[str, Any]

Expands a basic dictionary with session attributes.

accessed = True

Some implementations can detect when session data is read or written and set this when that happens. The mixin default is hard coded to True.

modified = True

Some implementations can detect changes to the session and set this when that happens. The mixin default is hard coded to True.

new = False
property permanent: bool

This reflects the '_permanent' key in the dict.

flask.signals module

flask.templating module

class flask.templating.DispatchingJinjaLoader(app: App)

Bases: BaseLoader

A loader that looks for templates in the application and all the blueprint folders.

get_source(environment: Environment, template: str) tuple[str, str | None, Callable[[], bool] | None]

Get the template source, filename and reload helper for a template. It’s passed the environment and template name and has to return a tuple in the form (source, filename, uptodate) or raise a TemplateNotFound error if it can’t locate the template.

The source part of the returned tuple must be the source of the template as a string. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise None. The filename is used by Python for the tracebacks if no loader extension is used.

The last item in the tuple is the uptodate function. If auto reloading is enabled it’s always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns False the template will be reloaded.

list_templates() list[str]

Iterates over all templates. If the loader does not support that it should raise a TypeError which is the default behavior.

class flask.templating.Environment(app: App, **options: t.Any)

Bases: Environment

Works like a regular Jinja2 environment but has some additional knowledge of how Flask’s blueprint works so that it can prepend the name of the blueprint to referenced templates if necessary.

flask.templating.render_template(template_name_or_list: str | Template | list[str | Template], **context: Any) str

Render a template by name with the given context.

Parameters:
  • template_name_or_list – The name of the template to render. If a list is given, the first name to exist will be rendered.

  • context – The variables to make available in the template.

flask.templating.render_template_string(source: str, **context: Any) str

Render a template from the given source string with the given context.

Parameters:
  • source – The source code of the template to render.

  • context – The variables to make available in the template.

flask.templating.stream_template(template_name_or_list: str | Template | list[str | Template], **context: Any) Iterator[str]

Render a template by name with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view.

Parameters:
  • template_name_or_list – The name of the template to render. If a list is given, the first name to exist will be rendered.

  • context – The variables to make available in the template.

Added in version 2.2.

flask.templating.stream_template_string(source: str, **context: Any) Iterator[str]

Render a template from the given source string with the given context as a stream. This returns an iterator of strings, which can be used as a streaming response from a view.

Parameters:
  • source – The source code of the template to render.

  • context – The variables to make available in the template.

Added in version 2.2.

flask.testing module

class flask.testing.EnvironBuilder(app: Flask, path: str = '/', base_url: str | None = None, subdomain: str | None = None, url_scheme: str | None = None, *args: t.Any, **kwargs: t.Any)

Bases: EnvironBuilder

An EnvironBuilder, that takes defaults from the application.

Parameters:
  • app – The Flask application to configure the environment from.

  • path – URL path being requested.

  • base_url – Base URL where the app is being served, which path is relative to. If not given, built from PREFERRED_URL_SCHEME, subdomain, SERVER_NAME, and APPLICATION_ROOT.

  • subdomain – Subdomain name to append to SERVER_NAME.

  • url_scheme – Scheme to use instead of PREFERRED_URL_SCHEME.

  • json – If given, this is serialized as JSON and passed as data. Also defaults content_type to application/json.

  • args – other positional arguments passed to EnvironBuilder.

  • kwargs – other keyword arguments passed to EnvironBuilder.

json_dumps(obj: Any, **kwargs: Any) str

Serialize obj to a JSON-formatted string.

The serialization will be configured according to the config associated with this EnvironBuilder’s app.

class flask.testing.FlaskCliRunner(app: Flask, **kwargs: t.Any)

Bases: CliRunner

A CliRunner for testing a Flask app’s CLI commands. Typically created using test_cli_runner(). See testing-cli.

invoke(cli: Any | None = None, args: Any | None = None, **kwargs: Any) Result

Invokes a CLI command in an isolated environment. See CliRunner.invoke for full method documentation. See testing-cli for examples.

If the obj argument is not given, passes an instance of ScriptInfo that knows how to load the Flask app being tested.

Parameters:
  • cli – Command object to invoke. Default is the app’s cli group.

  • args – List of strings to invoke the command with.

Returns:

a Result object.

class flask.testing.FlaskClient(*args: Any, **kwargs: Any)

Bases: Client

Works like a regular Werkzeug test client but has knowledge about Flask’s contexts to defer the cleanup of the request context until the end of a with block. For general information about how to use this class refer to werkzeug.test.Client.

Changed in version 0.12: app.test_client() includes preset default environment, which can be set after instantiation of the app.test_client() object in client.environ_base.

Basic usage is outlined in the /testing chapter.

application: Flask
open(*args: t.Any, buffered: bool = False, follow_redirects: bool = False, **kwargs: t.Any) TestResponse

Generate an environ dict from the given arguments, make a request to the application using it, and return the response.

Parameters:
  • args – Passed to EnvironBuilder to create the environ for the request. If a single arg is passed, it can be an existing EnvironBuilder or an environ dict.

  • buffered – Convert the iterator returned by the app into a list. If the iterator has a close() method, it is called automatically.

  • follow_redirects – Make additional requests to follow HTTP redirects until a non-redirect status is returned. TestResponse.history lists the intermediate responses.

Changed in version 2.1: Removed the as_tuple parameter.

Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed.

Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper.

Changed in version 0.5: Added the follow_redirects parameter.

session_transaction(*args: Any, **kwargs: Any) Iterator[SessionMixin]

When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back.

with client.session_transaction() as session:
    session['value'] = 42

Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as test_request_context() which are directly passed through.

flask.typing module

flask.views module

class flask.views.MethodView

Bases: View

Dispatches request methods to the corresponding instance methods. For example, if you implement a get method, it will be used to handle GET requests.

This can be useful for defining a REST API.

methods is automatically set based on the methods defined on the class.

See views for a detailed guide.

class CounterAPI(MethodView):
    def get(self):
        return str(session.get("counter", 0))

    def post(self):
        session["counter"] = session.get("counter", 0) + 1
        return redirect(url_for("counter"))

app.add_url_rule(
    "/counter", view_func=CounterAPI.as_view("counter")
)
dispatch_request(**kwargs: t.Any) ft.ResponseReturnValue

The actual view function behavior. Subclasses must override this and return a valid response. Any variables from the URL rule are passed as keyword arguments.

class flask.views.View

Bases: object

Subclass this class and override dispatch_request() to create a generic class-based view. Call as_view() to create a view function that creates an instance of the class with the given arguments and calls its dispatch_request method with any URL variables.

See views for a detailed guide.

class Hello(View):
    init_every_request = False

    def dispatch_request(self, name):
        return f"Hello, {name}!"

app.add_url_rule(
    "/hello/<name>", view_func=Hello.as_view("hello")
)

Set methods on the class to change what methods the view accepts.

Set decorators on the class to apply a list of decorators to the generated view function. Decorators applied to the class itself will not be applied to the generated view function!

Set init_every_request to False for efficiency, unless you need to store request-global data on self.

classmethod as_view(name: str, *class_args: t.Any, **class_kwargs: t.Any) ft.RouteCallable

Convert the class into a view function that can be registered for a route.

By default, the generated view will create a new instance of the view class for every request and call its dispatch_request() method. If the view class sets init_every_request to False, the same instance will be used for every request.

Except for name, all other arguments passed to this method are forwarded to the view class __init__ method.

Changed in version 2.2: Added the init_every_request class attribute.

decorators: ClassVar[list[Callable[[...], Any]]] = []

A list of decorators to apply, in order, to the generated view function. Remember that @decorator syntax is applied bottom to top, so the first decorator in the list would be the bottom decorator.

Added in version 0.8.

dispatch_request() ft.ResponseReturnValue

The actual view function behavior. Subclasses must override this and return a valid response. Any variables from the URL rule are passed as keyword arguments.

init_every_request: ClassVar[bool] = True

Create a new instance of this view class for every request by default. If a view subclass sets this to False, the same instance is used for every request.

A single instance is more efficient, especially if complex setup is done during init. However, storing data on self is no longer safe across requests, and g should be used instead.

Added in version 2.2.

methods: ClassVar[Collection[str] | None] = None

The methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.

provide_automatic_options: ClassVar[bool | None] = None

Control whether the OPTIONS method is handled automatically. Uses the same default (True) as route and add_url_rule by default.

flask.wrappers module

class flask.wrappers.Request(environ: WSGIEnvironment, populate_request: bool = True, shallow: bool = False)

Bases: Request

The request object used by default in Flask. Remembers the matched endpoint and view arguments.

It is what ends up as request. If you want to replace the request object used you can subclass this and set request_class to your subclass.

The request object is a Request subclass and provides all of the attributes Werkzeug defines plus a few Flask specific ones.

property blueprint: str | None

The registered name of the current blueprint.

This will be None if the endpoint is not part of a blueprint, or if URL matching failed or has not been performed yet.

This does not necessarily match the name the blueprint was created with. It may have been nested, or registered with a different name.

property blueprints: list[str]

The registered names of the current blueprint upwards through parent blueprints.

This will be an empty list if there is no current blueprint, or if URL matching failed.

Added in version 2.0.1.

property endpoint: str | None

The endpoint that matched the request URL.

This will be None if matching failed or has not been performed yet.

This in combination with view_args can be used to reconstruct the same URL or a modified URL.

json_module: t.Any = <module 'flask.json' from '/home/edgar/ucr/software_des/repo/flask/src/flask/json/__init__.py'>

A module or other object that has dumps and loads functions that match the API of the built-in json module.

property max_content_length: int | None

The maximum number of bytes that will be read during this request. If this limit is exceeded, a 413 RequestEntityTooLarge error is raised. If it is set to None, no limit is enforced at the Flask application level. However, if it is None and the request has no Content-Length header and the WSGI server does not indicate that it terminates the stream, then no data is read to avoid an infinite stream.

Each request defaults to the MAX_CONTENT_LENGTH config, which defaults to None. It can be set on a specific request to apply the limit to that specific view. This should be set appropriately based on an application’s or view’s specific needs.

Changed in version 3.1: This can be set per-request.

Changed in version 0.6: This is configurable through Flask config.

property max_form_memory_size: int | None

The maximum size in bytes any non-file form field may be in a multipart/form-data body. If this limit is exceeded, a 413 RequestEntityTooLarge error is raised. If it is set to None, no limit is enforced at the Flask application level.

Each request defaults to the MAX_FORM_MEMORY_SIZE config, which defaults to 500_000. It can be set on a specific request to apply the limit to that specific view. This should be set appropriately based on an application’s or view’s specific needs.

Changed in version 3.1: This is configurable through Flask config.

property max_form_parts: int | None

The maximum number of fields that may be present in a multipart/form-data body. If this limit is exceeded, a 413 RequestEntityTooLarge error is raised. If it is set to None, no limit is enforced at the Flask application level.

Each request defaults to the MAX_FORM_PARTS config, which defaults to 1_000. It can be set on a specific request to apply the limit to that specific view. This should be set appropriately based on an application’s or view’s specific needs.

Changed in version 3.1: This is configurable through Flask config.

on_json_loading_failed(e: ValueError | None) Any

Called if get_json() fails and isn’t silenced.

If this method returns a value, it is used as the return value for get_json(). The default implementation raises BadRequest.

Parameters:

e – If parsing failed, this is the exception. It will be None if the content type wasn’t application/json.

Changed in version 2.3: Raise a 415 error instead of 400.

routing_exception: HTTPException | None = None

If matching the URL failed, this is the exception that will be raised / was raised as part of the request handling. This is usually a NotFound exception or something similar.

url_rule: Rule | None = None

The internal URL rule that matched the request. This can be useful to inspect which methods are allowed for the URL from a before/after handler (request.url_rule.methods) etc. Though if the request’s method was invalid for the URL rule, the valid list is available in routing_exception.valid_methods instead (an attribute of the Werkzeug exception MethodNotAllowed) because the request was never internally bound.

Added in version 0.6.

view_args: dict[str, t.Any] | None = None

A dict of view arguments that matched the request. If an exception happened when matching, this will be None.

class flask.wrappers.Response(response: Iterable[bytes] | bytes | Iterable[str] | str | None = None, status: int | str | HTTPStatus | None = None, headers: Mapping[str, str | Iterable[str]] | Iterable[tuple[str, str]] | None = None, mimetype: str | None = None, content_type: str | None = None, direct_passthrough: bool = False)

Bases: Response

The response object that is used by default in Flask. Works like the response object from Werkzeug but is set to have an HTML mimetype by default. Quite often you don’t have to create this object yourself because make_response() will take care of that for you.

If you want to replace the response object used you can subclass this and set response_class to your subclass.

Changed in version 1.0: JSON support is added to the response, like the request. This is useful when testing to get the test client response data as JSON.

Changed in version 1.0: Added max_cookie_size.

autocorrect_location_header = False

If a redirect Location header is a relative URL, make it an absolute URL, including scheme and domain.

Changed in version 2.1: This is disabled by default, so responses will send relative redirects.

Added in version 0.8.

default_mimetype: str | None = 'text/html'

the default mimetype if none is provided.

json_module = <module 'flask.json' from '/home/edgar/ucr/software_des/repo/flask/src/flask/json/__init__.py'>

A module or other object that has dumps and loads functions that match the API of the built-in json module.

Read-only view of the MAX_COOKIE_SIZE config key.

See max_cookie_size in Werkzeug’s docs.

Module contents