Skip to main content

Flask

The Flask class implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application.

Constructor

Flask(
    import_name: str,
    static_url_path: str | None = None,
    static_folder: str | os.PathLike[str] | None = "static",
    static_host: str | None = None,
    host_matching: bool = False,
    subdomain_matching: bool = False,
    template_folder: str | os.PathLike[str] | None = "templates",
    instance_path: str | None = None,
    instance_relative_config: bool = False,
    root_path: str | None = None,
)
import_name
str
required
The name of the application package. Usually __name__.
static_url_path
str | None
default:"None"
Can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.
static_folder
str | os.PathLike[str] | None
default:"'static'"
The folder with static files that is served at static_url_path. Relative to the application root_path or an absolute path.
static_host
str | None
default:"None"
The host to use when adding the static route. Required when using host_matching=True with a static_folder configured.
host_matching
bool
default:"False"
Set url_map.host_matching attribute.
subdomain_matching
bool
default:"False"
Consider the subdomain relative to SERVER_NAME when matching routes.
template_folder
str | os.PathLike[str] | None
default:"'templates'"
The folder that contains the templates that should be used by the application.
instance_path
str | None
default:"None"
An alternative instance path for the application. By default the folder 'instance' next to the package or module is assumed to be the instance path.
instance_relative_config
bool
default:"False"
If set to True relative filenames for loading the config are assumed to be relative to the instance path instead of the application root.
root_path
str | None
default:"None"
The path to the root of the application files. This should only be set manually when it can’t be detected automatically, such as for namespace packages.

Example

from flask import Flask

app = Flask(__name__)

Routing Methods

route()

Decorate a view function to register it with the given URL rule and options.
@app.route(rule: str, **options) -> Callable
rule
str
required
The URL rule string.
methods
list[str]
default:"['GET']"
A list of HTTP methods this rule should handle. HEAD and OPTIONS are added automatically.
endpoint
str
default:"None"
The endpoint name for the route. Defaults to the name of the view function.

Example

@app.route('/')
def index():
    return 'Hello, World!'

@app.route('/user/<username>', methods=['GET', 'POST'])
def show_user(username):
    return f'User: {username}'

add_url_rule()

Register a rule for routing incoming requests and building URLs.
app.add_url_rule(
    rule: str,
    endpoint: str | None = None,
    view_func: Callable | None = None,
    provide_automatic_options: bool | None = None,
    **options
) -> None
rule
str
required
The URL rule string.
endpoint
str | None
default:"None"
The endpoint name to associate with the rule and view function. Defaults to view_func.__name__.
view_func
Callable | None
default:"None"
The view function to associate with the endpoint name.
provide_automatic_options
bool | None
default:"None"
Add the OPTIONS method and respond to OPTIONS requests automatically.

Example

def index():
    return 'Hello, World!'

app.add_url_rule('/', view_func=index)

HTTP Method Shortcuts

Flask provides shortcuts for common HTTP methods:
@app.get(rule: str, **options)
@app.post(rule: str, **options)
@app.put(rule: str, **options)
@app.delete(rule: str, **options)
@app.patch(rule: str, **options)

Example

@app.get('/users')
def list_users():
    return {'users': []}

@app.post('/users')
def create_user():
    return {'created': True}

Request Handling Hooks

before_request()

Register a function to run before each request.
@app.before_request
def before_request_func() -> None | Response:
    pass
The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped.

Example

@app.before_request
def load_user():
    if 'user_id' in session:
        g.user = db.session.get(session['user_id'])

after_request()

Register a function to run after each request.
@app.after_request
def after_request_func(response: Response) -> Response:
    return response
response
Response
required
The response object that will be sent to the client.
Returns the modified response object.

Example

@app.after_request
def add_header(response):
    response.headers['X-Custom-Header'] = 'Value'
    return response

teardown_request()

Register a function to be called when the request context is popped.
@app.teardown_request
def teardown_request_func(exception: BaseException | None = None) -> None:
    pass
exception
BaseException | None
An unhandled exception that occurred during the request, if any.

Example

@app.teardown_request
def close_db_connection(exception):
    db.close()

teardown_appcontext()

Register a function to be called when the application context is destroyed.
@app.teardown_appcontext
def teardown_appcontext_func(exception: BaseException | None = None) -> None:
    pass

Error Handling

errorhandler()

Register a function to handle errors by code or exception class.
@app.errorhandler(code_or_exception: type[Exception] | int)
def error_handler(error: Exception) -> Response:
    return response
code_or_exception
type[Exception] | int
required
The HTTP status code as an integer or an exception class.

Example

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

@app.errorhandler(ValueError)
def handle_value_error(error):
    return str(error), 400

register_error_handler()

Non-decorator alternative to errorhandler().
app.register_error_handler(
    code_or_exception: type[Exception] | int,
    f: Callable
) -> None

Template Context

context_processor()

Register a template context processor function.
@app.context_processor
def context_processor_func() -> dict:
    return {'key': 'value'}
The returned dict keys are added as variables available in templates.

Example

@app.context_processor
def inject_user():
    return {'current_user': g.user}

template_filter()

Register a custom template filter.
@app.template_filter(name: str | None = None)
def filter_func(value):
    return modified_value

template_global()

Register a custom template global function.
@app.template_global(name: str | None = None)
def global_func():
    return value

template_test()

Register a custom template test.
@app.template_test(name: str | None = None)
def test_func(value):
    return True or False

URL Building

url_for()

Generate a URL to the given endpoint with the given values.
app.url_for(
    endpoint: str,
    *,
    _anchor: str | None = None,
    _method: str | None = None,
    _scheme: str | None = None,
    _external: bool | None = None,
    **values
) -> str
endpoint
str
required
The endpoint name associated with the URL to generate.
_anchor
str | None
default:"None"
If given, append this as #anchor to the URL.
_method
str | None
default:"None"
If given, generate the URL associated with this method for the endpoint.
_scheme
str | None
default:"None"
If given, the URL will have this scheme if it is external.
_external
bool | None
default:"None"
If given, prefer the URL to be internal (False) or require it to be external (True).
**values
Values to use for the variable parts of the URL rule. Unknown keys are appended as query string arguments.

url_defaults()

Register a function to modify keyword arguments when generating URLs.
@app.url_defaults
def url_defaults_func(endpoint: str, values: dict) -> None:
    pass

url_value_preprocessor()

Register a URL value preprocessor function.
@app.url_value_preprocessor
def url_value_preprocessor_func(endpoint: str, values: dict) -> None:
    pass

Running the Application

run()

Runs the application on a local development server.
app.run(
    host: str | None = None,
    port: int | None = None,
    debug: bool | None = None,
    load_dotenv: bool = True,
    **options
) -> None
host
str | None
default:"'127.0.0.1'"
The hostname to listen on. Set to '0.0.0.0' to have the server available externally.
port
int | None
default:"5000"
The port of the webserver.
debug
bool | None
default:"None"
If given, enable or disable debug mode.
load_dotenv
bool
default:"True"
Load the nearest .env and .flaskenv files to set environment variables.
Do not use run() in a production setting. It is not intended to meet security and performance requirements for a production server.

Example

if __name__ == '__main__':
    app.run(debug=True, port=8000)

Testing

test_client()

Creates a test client for this application.
app.test_client(use_cookies: bool = True, **kwargs) -> FlaskClient
use_cookies
bool
default:"True"
Whether to enable cookies in the test client.
Returns a FlaskClient instance.

Example

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

with client:
    response = client.get('/')
    assert response.status_code == 200

test_cli_runner()

Create a CLI runner for testing CLI commands.
app.test_cli_runner(**kwargs) -> FlaskCliRunner
Returns a FlaskCliRunner instance.

Other Utility Methods

make_response()

Convert the return value from a view function to an instance of response_class.
app.make_response(rv) -> Response

open_resource()

Open a resource file relative to root_path for reading.
app.open_resource(
    resource: str,
    mode: str = "rb",
    encoding: str | None = None
) -> IO
resource
str
required
Path to the resource relative to root_path.
mode
str
default:"'rb'"
Open the file in this mode. Only reading is supported: "r" (or "rt") and "rb".
encoding
str | None
default:"None"
Open the file with this encoding when opening in text mode.

Example

with app.open_resource('schema.sql') as f:
    conn.executescript(f.read())

shell_context_processor()

Register a shell context processor function.
@app.shell_context_processor
def shell_context() -> dict:
    return {'db': db, 'User': User}

Build docs developers (and LLMs) love