* [with\_appcontext() (in module flask.cli)](../api/#flask.cli.with_appcontext) | * [wsgi\_app() (flask.Flask method)](../api/#flask.Flask.wsgi_app)
* [www\_authenticate (flask.Response property)](../api/#flask.Response.www_authenticate) |
Y
-
* [YOURAPPLICATION\_SETTINGS](../config/#index-1)
[](../)
### Navigation
* [Overview](../)
### Quick search
---
# Installation — Flask Documentation (3.1.x)
### Navigation
* [index](../genindex/ "General Index")
* [modules](../py-modindex/ "Python Module Index")
|
* [next](../quickstart/ "Quickstart")
|
* [previous](../ "Welcome to Flask")
|
* [Flask Documentation (3.1.x)](../)
»
* Installation
Installation[¶](#installation "Link to this heading")
======================================================
Python Version[¶](#python-version "Link to this heading")
----------------------------------------------------------
We recommend using the latest version of Python. Flask supports Python 3.9 and newer.
Dependencies[¶](#dependencies "Link to this heading")
------------------------------------------------------
These distributions will be installed automatically when installing Flask.
* [Werkzeug](https://palletsprojects.com/p/werkzeug/)
implements WSGI, the standard Python interface between applications and servers.
* [Jinja](https://palletsprojects.com/p/jinja/)
is a template language that renders the pages your application serves.
* [MarkupSafe](https://palletsprojects.com/p/markupsafe/)
comes with Jinja. It escapes untrusted input when rendering templates to avoid injection attacks.
* [ItsDangerous](https://palletsprojects.com/p/itsdangerous/)
securely signs data to ensure its integrity. This is used to protect Flask’s session cookie.
* [Click](https://palletsprojects.com/p/click/)
is a framework for writing command line applications. It provides the `flask` command and allows adding custom management commands.
* [Blinker](https://blinker.readthedocs.io/)
provides support for [Signals](../signals/)
.
### Optional dependencies[¶](#optional-dependencies "Link to this heading")
These distributions will not be installed automatically. Flask will detect and use them if you install them.
* [python-dotenv](https://github.com/theskumar/python-dotenv#readme)
enables support for [Environment Variables From dotenv](../cli/#dotenv)
when running `flask` commands.
* [Watchdog](https://pythonhosted.org/watchdog/)
provides a faster, more efficient reloader for the development server.
### greenlet[¶](#greenlet "Link to this heading")
You may choose to use gevent or eventlet with your application. In this case, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is required.
These are not minimum supported versions, they only indicate the first versions that added necessary features. You should use the latest versions of each.
Virtual environments[¶](#virtual-environments "Link to this heading")
----------------------------------------------------------------------
Use a virtual environment to manage the dependencies for your project, both in development and in production.
What problem does a virtual environment solve? The more Python projects you have, the more likely it is that you need to work with different versions of Python libraries, or even Python itself. Newer versions of libraries for one project can break compatibility in another project.
Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system’s packages.
Python comes bundled with the [`venv`](https://docs.python.org/3/library/venv.html#module-venv "(in Python v3.13)")
module to create virtual environments.
### Create an environment[¶](#create-an-environment "Link to this heading")
Create a project folder and a `.venv` folder within:
macOS/LinuxWindows
$ mkdir myproject
$ cd myproject
$ python3 -m venv .venv
\> mkdir myproject
> cd myproject
> py -3 -m venv .venv
### Activate the environment[¶](#activate-the-environment "Link to this heading")
Before you work on your project, activate the corresponding environment:
macOS/LinuxWindows
$ . .venv/bin/activate
\> .venv\\Scripts\\activate
Your shell prompt will change to show the name of the activated environment.
Install Flask[¶](#install-flask "Link to this heading")
--------------------------------------------------------
Within the activated environment, use the following command to install Flask:
$ pip install Flask
Flask is now installed. Check out the [Quickstart](../quickstart/)
or go to the [Documentation Overview](../)
.
[](../)
### Contents
* [Installation](#)
* [Python Version](#python-version)
* [Dependencies](#dependencies)
* [Optional dependencies](#optional-dependencies)
* [greenlet](#greenlet)
* [Virtual environments](#virtual-environments)
* [Create an environment](#create-an-environment)
* [Activate the environment](#activate-the-environment)
* [Install Flask](#install-flask)
### Navigation
* [Overview](../)
* Previous: [Welcome to Flask](../ "previous chapter")
* Next: [Quickstart](../quickstart/ "next chapter")
### Quick search
---
# Quickstart — Flask Documentation (3.1.x)
### Navigation
* [index](../genindex/ "General Index")
* [modules](../py-modindex/ "Python Module Index")
|
* [next](../tutorial/ "Tutorial")
|
* [previous](../installation/ "Installation")
|
* [Flask Documentation (3.1.x)](../)
»
* Quickstart
Quickstart[¶](#quickstart "Link to this heading")
==================================================
Eager to get started? This page gives a good introduction to Flask. Follow [Installation](../installation/)
to set up a project and install Flask first.
A Minimal Application[¶](#a-minimal-application "Link to this heading")
------------------------------------------------------------------------
A minimal Flask application looks something like this:
from flask import Flask
app \= Flask(\_\_name\_\_)
@app.route("/")
def hello\_world():
return "
Hello, World!
"
So what did that code do?
1. First we imported the [`Flask`](../api/#flask.Flask "flask.Flask")
class. An instance of this class will be our WSGI application.
2. Next we create an instance of this class. The first argument is the name of the application’s module or package. `__name__` is a convenient shortcut for this that is appropriate for most cases. This is needed so that Flask knows where to look for resources such as templates and static files.
3. We then use the [`route()`](../api/#flask.Flask.route "flask.Flask.route")
decorator to tell Flask what URL should trigger our function.
4. The function returns the message we want to display in the user’s browser. The default content type is HTML, so HTML in the string will be rendered by the browser.
Save it as `hello.py` or something similar. Make sure to not call your application `flask.py` because this would conflict with Flask itself.
To run the application, use the `flask` command or `python -m flask`. You need to tell the Flask where your application is with the `--app` option.
$ flask --app hello run
\* Serving Flask app 'hello'
\* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
Application Discovery Behavior
As a shortcut, if the file is named `app.py` or `wsgi.py`, you don’t have to use `--app`. See [Command Line Interface](../cli/)
for more details.
This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see [Deploying to Production](../deploying/)
.
Now head over to [http://127.0.0.1:5000/](http://127.0.0.1:5000/)
, and you should see your hello world greeting.
If another program is already using port 5000, you’ll see `OSError: [Errno 98]` or `OSError: [WinError 10013]` when the server tries to start. See [Address already in use](../server/#address-already-in-use)
for how to handle that.
Externally Visible Server
If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.
If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding `--host=0.0.0.0` to the command line:
$ flask run --host=0.0.0.0
This tells your operating system to listen on all public IPs.
Debug Mode[¶](#debug-mode "Link to this heading")
--------------------------------------------------
The `flask run` command can do more than just start the development server. By enabling debug mode, the server will automatically reload if code changes, and will show an interactive debugger in the browser if an error occurs during a request.

Warning
The debugger allows executing arbitrary Python code from the browser. It is protected by a pin, but still represents a major security risk. Do not run the development server or debugger in a production environment.
To enable debug mode, use the `--debug` option.
$ flask --app hello run --debug
\* Serving Flask app 'hello'
\* Debug mode: on
\* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
\* Restarting with stat
\* Debugger is active!
\* Debugger PIN: nnn-nnn-nnn
See also:
* [Development Server](../server/)
and [Command Line Interface](../cli/)
for information about running in debug mode.
* [Debugging Application Errors](../debugging/)
for information about using the built-in debugger and other debuggers.
* [Logging](../logging/)
and [Handling Application Errors](../errorhandling/)
to log errors and display nice error pages.
HTML Escaping[¶](#html-escaping "Link to this heading")
--------------------------------------------------------
When returning HTML (the default response type in Flask), any user-provided values rendered in the output must be escaped to protect from injection attacks. HTML templates rendered with Jinja, introduced later, will do this automatically.
`escape()`, shown here, can be used manually. It is omitted in most examples for brevity, but you should always be aware of how you’re using untrusted data.
from markupsafe import escape
@app.route("/")
def hello(name):
return f"Hello, {escape(name)}!"
If a user managed to submit the name ``, escaping causes it to be rendered as text, rather than running the script in the user’s browser.
`` in the route captures a value from the URL and passes it to the view function. These variable rules are explained below.
Routing[¶](#routing "Link to this heading")
--------------------------------------------
Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page.
Use the [`route()`](../api/#flask.Flask.route "flask.Flask.route")
decorator to bind a function to a URL.
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'
You can do more! You can make parts of the URL dynamic and attach multiple rules to a function.
### Variable Rules[¶](#variable-rules "Link to this heading")
You can add variable sections to a URL by marking sections with ``. Your function then receives the `` as a keyword argument. Optionally, you can use a converter to specify the type of the argument like ``.
from markupsafe import escape
@app.route('/user/')
def show\_user\_profile(username):
\# show the user profile for that user
return f'User {escape(username)}'
@app.route('/post/')
def show\_post(post\_id):
\# show the post with the given id, the id is an integer
return f'Post {post\_id}'
@app.route('/path/')
def show\_subpath(subpath):
\# show the subpath after /path/
return f'Subpath {escape(subpath)}'
Converter types:
| | |
| --- | --- |
| `string` | (default) accepts any text without a slash |
| `int` | accepts positive integers |
| `float` | accepts positive floating point values |
| `path` | like `string` but also accepts slashes |
| `uuid` | accepts UUID strings |
### Unique URLs / Redirection Behavior[¶](#unique-urls-redirection-behavior "Link to this heading")
The following two rules differ in their use of a trailing slash.
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
The canonical URL for the `projects` endpoint has a trailing slash. It’s similar to a folder in a file system. If you access the URL without a trailing slash (`/projects`), Flask redirects you to the canonical URL with the trailing slash (`/projects/`).
The canonical URL for the `about` endpoint does not have a trailing slash. It’s similar to the pathname of a file. Accessing the URL with a trailing slash (`/about/`) produces a 404 “Not Found” error. This helps keep URLs unique for these resources, which helps search engines avoid indexing the same page twice.
### URL Building[¶](#url-building "Link to this heading")
To build a URL to a specific function, use the [`url_for()`](../api/#flask.url_for "flask.url_for")
function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters.
Why would you want to build URLs using the URL reversing function [`url_for()`](../api/#flask.url_for "flask.url_for")
instead of hard-coding them into your templates?
1. Reversing is often more descriptive than hard-coding the URLs.
2. You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs.
3. URL building handles escaping of special characters transparently.
4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers.
5. If your application is placed outside the URL root, for example, in `/myapplication` instead of `/`, [`url_for()`](../api/#flask.url_for "flask.url_for")
properly handles that for you.
For example, here we use the [`test_request_context()`](../api/#flask.Flask.test_request_context "flask.Flask.test_request_context")
method to try out [`url_for()`](../api/#flask.url_for "flask.url_for")
. [`test_request_context()`](../api/#flask.Flask.test_request_context "flask.Flask.test_request_context")
tells Flask to behave as though it’s handling a request even while we use a Python shell. See [Context Locals](#context-locals)
.
from flask import url\_for
@app.route('/')
def index():
return 'index'
@app.route('/login')
def login():
return 'login'
@app.route('/user/')
def profile(username):
return f'{username}\\'s profile'
with app.test\_request\_context():
print(url\_for('index'))
print(url\_for('login'))
print(url\_for('login', next\='/'))
print(url\_for('profile', username\='John Doe'))
/
/login
/login?next=/
/user/John%20Doe
### HTTP Methods[¶](#http-methods "Link to this heading")
Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to `GET` requests. You can use the `methods` argument of the [`route()`](../api/#flask.Flask.route "flask.Flask.route")
decorator to handle different HTTP methods.
from flask import request
@app.route('/login', methods\=\['GET', 'POST'\])
def login():
if request.method \== 'POST':
return do\_the\_login()
else:
return show\_the\_login\_form()
The example above keeps all methods for the route within one function, which can be useful if each part uses some common data.
You can also separate views for different methods into different functions. Flask provides a shortcut for decorating such routes with [`get()`](../api/#flask.Flask.get "flask.Flask.get")
, [`post()`](../api/#flask.Flask.post "flask.Flask.post")
, etc. for each common HTTP method.
@app.get('/login')
def login\_get():
return show\_the\_login\_form()
@app.post('/login')
def login\_post():
return do\_the\_login()
If `GET` is present, Flask automatically adds support for the `HEAD` method and handles `HEAD` requests according to the [HTTP RFC](https://www.ietf.org/rfc/rfc2068.txt)
. Likewise, `OPTIONS` is automatically implemented for you.
Static Files[¶](#static-files "Link to this heading")
------------------------------------------------------
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called `static` in your package or next to your module and it will be available at `/static` on the application.
To generate URLs for static files, use the special `'static'` endpoint name:
url\_for('static', filename\='style.css')
The file has to be stored on the filesystem as `static/style.css`.
Rendering Templates[¶](#rendering-templates "Link to this heading")
--------------------------------------------------------------------
Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures the [Jinja2](https://palletsprojects.com/p/jinja/)
template engine for you automatically.
Templates can be used to generate any type of text file. For web applications, you’ll primarily be generating HTML pages, but you can also generate markdown, plain text for emails, and anything else.
For a reference to HTML, CSS, and other web APIs, use the [MDN Web Docs](https://developer.mozilla.org/)
.
To render a template you can use the [`render_template()`](../api/#flask.render_template "flask.render_template")
method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here’s a simple example of how to render a template:
from flask import render\_template
@app.route('/hello/')
@app.route('/hello/')
def hello(name\=None):
return render\_template('hello.html', person\=name)
Flask will look for templates in the `templates` folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:
**Case 1**: a module:
/application.py
/templates
/hello.html
**Case 2**: a package:
/application
/\_\_init\_\_.py
/templates
/hello.html
For templates you can use the full power of Jinja2 templates. Head over to the official [Jinja2 Template Documentation](https://jinja.palletsprojects.com/templates/)
for more information.
Here is an example template:
Hello from Flask
{% if person %}
Hello {{ person }}!
{% else %}
Hello, World!
{% endif %}
Inside templates you also have access to the [`config`](../api/#flask.Flask.config "flask.Flask.config")
, [`request`](../api/#flask.request "flask.request")
, [`session`](../api/#flask.session "flask.session")
and [`g`](../api/#flask.g "flask.g")
[\[1\]](#id3)
objects as well as the [`url_for()`](../api/#flask.url_for "flask.url_for")
and [`get_flashed_messages()`](../api/#flask.get_flashed_messages "flask.get_flashed_messages")
functions.
Templates are especially useful if inheritance is used. If you want to know how that works, see [Template Inheritance](../patterns/templateinheritance/)
. Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer).
Automatic escaping is enabled, so if `person` contains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the `Markup` class or by using the `|safe` filter in the template. Head over to the Jinja 2 documentation for more examples.
Here is a basic introduction to how the `Markup` class works:
\>>> from markupsafe import Markup
\>>> Markup('Hello %s!') % ''
Markup('Hello <blink>hacker</blink>!')
\>>> Markup.escape('')
Markup('<blink>hacker</blink>')
\>>> Markup('Marked up » HTML').striptags()
'Marked up » HTML'
Changelog
Changed in version 0.5: Autoescaping is no longer enabled for all templates. The following extensions for templates trigger autoescaping: `.html`, `.htm`, `.xml`, `.xhtml`. Templates loaded from a string will have autoescaping disabled.
Accessing Request Data[¶](#accessing-request-data "Link to this heading")
--------------------------------------------------------------------------
For web applications it’s crucial to react to the data a client sends to the server. In Flask this information is provided by the global [`request`](../api/#flask.request "flask.request")
object. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer is context locals:
### Context Locals[¶](#context-locals "Link to this heading")
Insider Information
If you want to understand how that works and how you can implement tests with context locals, read this section, otherwise just skip it.
Certain objects in Flask are global objects, but not of the usual kind. These objects are actually proxies to objects that are local to a specific context. What a mouthful. But that is actually quite easy to understand.
Imagine the context being the handling thread. A request comes in and the web server decides to spawn a new thread (or something else, the underlying object is capable of dealing with concurrency systems other than threads). When Flask starts its internal request handling it figures out that the current thread is the active context and binds the current application and the WSGI environments to that context (thread). It does that in an intelligent way so that one application can invoke another application without breaking.
So what does this mean to you? Basically you can completely ignore that this is the case unless you are doing something like unit testing. You will notice that code which depends on a request object will suddenly break because there is no request object. The solution is creating a request object yourself and binding it to the context. The easiest solution for unit testing is to use the [`test_request_context()`](../api/#flask.Flask.test_request_context "flask.Flask.test_request_context")
context manager. In combination with the `with` statement it will bind a test request so that you can interact with it. Here is an example:
from flask import request
with app.test\_request\_context('/hello', method\='POST'):
\# now you can do something with the request until the
\# end of the with block, such as basic assertions:
assert request.path \== '/hello'
assert request.method \== 'POST'
The other possibility is passing a whole WSGI environment to the [`request_context()`](../api/#flask.Flask.request_context "flask.Flask.request_context")
method:
with app.request\_context(environ):
assert request.method \== 'POST'
### The Request Object[¶](#the-request-object "Link to this heading")
The request object is documented in the API section and we will not cover it here in detail (see [`Request`](../api/#flask.Request "flask.Request")
). Here is a broad overview of some of the most common operations. First of all you have to import it from the `flask` module:
from flask import request
The current request method is available by using the [`method`](../api/#flask.Request.method "flask.Request.method")
attribute. To access form data (data transmitted in a `POST` or `PUT` request) you can use the [`form`](../api/#flask.Request.form "flask.Request.form")
attribute. Here is a full example of the two attributes mentioned above:
@app.route('/login', methods\=\['POST', 'GET'\])
def login():
error \= None
if request.method \== 'POST':
if valid\_login(request.form\['username'\],
request.form\['password'\]):
return log\_the\_user\_in(request.form\['username'\])
else:
error \= 'Invalid username/password'
\# the code below is executed if the request method
\# was GET or the credentials were invalid
return render\_template('login.html', error\=error)
What happens if the key does not exist in the `form` attribute? In that case a special [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.13)")
is raised. You can catch it like a standard [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.13)")
but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.
To access parameters submitted in the URL (`?key=value`) you can use the [`args`](../api/#flask.Request.args "flask.Request.args")
attribute:
searchword \= request.args.get('key', '')
We recommend accessing URL parameters with `get` or by catching the [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.13)")
because users might change the URL and presenting them a 400 bad request page in that case is not user friendly.
For a full list of methods and attributes of the request object, head over to the [`Request`](../api/#flask.Request "flask.Request")
documentation.
### File Uploads[¶](#file-uploads "Link to this heading")
You can handle uploaded files with Flask easily. Just make sure not to forget to set the `enctype="multipart/form-data"` attribute on your HTML form, otherwise the browser will not transmit your files at all.
Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the `files` attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python `file` object, but it also has a [`save()`](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.FileStorage.save "(in Werkzeug v3.1.x)")
method that allows you to store that file on the filesystem of the server. Here is a simple example showing how that works:
from flask import request
@app.route('/upload', methods\=\['GET', 'POST'\])
def upload\_file():
if request.method \== 'POST':
f \= request.files\['the\_file'\]
f.save('/var/www/uploads/uploaded\_file.txt')
...
If you want to know how the file was named on the client before it was uploaded to your application, you can access the [`filename`](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.FileStorage.filename "(in Werkzeug v3.1.x)")
attribute. However please keep in mind that this value can be forged so never ever trust that value. If you want to use the filename of the client to store the file on the server, pass it through the [`secure_filename()`](https://werkzeug.palletsprojects.com/en/stable/utils/#werkzeug.utils.secure_filename "(in Werkzeug v3.1.x)")
function that Werkzeug provides for you:
from werkzeug.utils import secure\_filename
@app.route('/upload', methods\=\['GET', 'POST'\])
def upload\_file():
if request.method \== 'POST':
file \= request.files\['the\_file'\]
file.save(f"/var/www/uploads/{secure\_filename(file.filename)}")
...
For some better examples, see [Uploading Files](../patterns/fileuploads/)
.
### Cookies[¶](#cookies "Link to this heading")
To access cookies you can use the [`cookies`](../api/#flask.Request.cookies "flask.Request.cookies")
attribute. To set cookies you can use the [`set_cookie`](../api/#flask.Response.set_cookie "flask.Response.set_cookie")
method of response objects. The [`cookies`](../api/#flask.Request.cookies "flask.Request.cookies")
attribute of request objects is a dictionary with all the cookies the client transmits. If you want to use sessions, do not use the cookies directly but instead use the [Sessions](#sessions)
in Flask that add some security on top of cookies for you.
Reading cookies:
from flask import request
@app.route('/')
def index():
username \= request.cookies.get('username')
\# use cookies.get(key) instead of cookies\[key\] to not get a
\# KeyError if the cookie is missing.
Storing cookies:
from flask import make\_response
@app.route('/')
def index():
resp \= make\_response(render\_template(...))
resp.set\_cookie('username', 'the username')
return resp
Note that cookies are set on response objects. Since you normally just return strings from the view functions Flask will convert them into response objects for you. If you explicitly want to do that you can use the [`make_response()`](../api/#flask.make_response "flask.make_response")
function and then modify it.
Sometimes you might want to set a cookie at a point where the response object does not exist yet. This is possible by utilizing the [Deferred Request Callbacks](../patterns/deferredcallbacks/)
pattern.
For this also see [About Responses](#about-responses)
.
Redirects and Errors[¶](#redirects-and-errors "Link to this heading")
----------------------------------------------------------------------
To redirect a user to another endpoint, use the [`redirect()`](../api/#flask.redirect "flask.redirect")
function; to abort a request early with an error code, use the [`abort()`](../api/#flask.abort "flask.abort")
function:
from flask import abort, redirect, url\_for
@app.route('/')
def index():
return redirect(url\_for('login'))
@app.route('/login')
def login():
abort(401)
this\_is\_never\_executed()
This is a rather pointless example because a user will be redirected from the index to a page they cannot access (401 means access denied) but it shows how that works.
By default a black and white error page is shown for each error code. If you want to customize the error page, you can use the [`errorhandler()`](../api/#flask.Flask.errorhandler "flask.Flask.errorhandler")
decorator:
from flask import render\_template
@app.errorhandler(404)
def page\_not\_found(error):
return render\_template('page\_not\_found.html'), 404
Note the `404` after the [`render_template()`](../api/#flask.render_template "flask.render_template")
call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well.
See [Handling Application Errors](../errorhandling/)
for more details.
About Responses[¶](#about-responses "Link to this heading")
------------------------------------------------------------
The return value from a view function is automatically converted into a response object for you. If the return value is a string it’s converted into a response object with the string as response body, a `200 OK` status code and a _text/html_ mimetype. If the return value is a dict or list, `jsonify()` is called to produce a response. The logic that Flask applies to converting return values into response objects is as follows:
1. If a response object of the correct type is returned it’s directly returned from the view.
2. If it’s a string, a response object is created with that data and the default parameters.
3. If it’s an iterator or generator returning strings or bytes, it is treated as a streaming response.
4. If it’s a dict or list, a response object is created using [`jsonify()`](../api/#flask.json.jsonify "flask.json.jsonify")
.
5. If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form `(response, status)`, `(response, headers)`, or `(response, status, headers)`. The `status` value will override the status code and `headers` can be a list or dictionary of additional header values.
6. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object.
If you want to get hold of the resulting response object inside the view you can use the [`make_response()`](../api/#flask.make_response "flask.make_response")
function.
Imagine you have a view like this:
from flask import render\_template
@app.errorhandler(404)
def not\_found(error):
return render\_template('error.html'), 404
You just need to wrap the return expression with [`make_response()`](../api/#flask.make_response "flask.make_response")
and get the response object to modify it, then return it:
from flask import make\_response
@app.errorhandler(404)
def not\_found(error):
resp \= make\_response(render\_template('error.html'), 404)
resp.headers\['X-Something'\] \= 'A value'
return resp
### APIs with JSON[¶](#apis-with-json "Link to this heading")
A common response format when writing an API is JSON. It’s easy to get started writing such an API with Flask. If you return a `dict` or `list` from a view, it will be converted to a JSON response.
@app.route("/me")
def me\_api():
user \= get\_current\_user()
return {
"username": user.username,
"theme": user.theme,
"image": url\_for("user\_image", filename\=user.image),
}
@app.route("/users")
def users\_api():
users \= get\_all\_users()
return \[user.to\_json() for user in users\]
This is a shortcut to passing the data to the [`jsonify()`](../api/#flask.json.jsonify "flask.json.jsonify")
function, which will serialize any supported JSON data type. That means that all the data in the dict or list must be JSON serializable.
For complex types such as database models, you’ll want to use a serialization library to convert the data to valid JSON types first. There are many serialization libraries and Flask API extensions maintained by the community that support more complex applications.
Sessions[¶](#sessions "Link to this heading")
----------------------------------------------
In addition to the request object there is also a second object called [`session`](../api/#flask.session "flask.session")
which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing.
In order to use sessions you have to set a secret key. Here is how sessions work:
from flask import session
\# Set the secret key to some random bytes. Keep this really secret!
app.secret\_key \= b'\_5#y2L"F4Q8z\\n\\xec\]/'
@app.route('/')
def index():
if 'username' in session:
return f'Logged in as {session\["username"\]}'
return 'You are not logged in'
@app.route('/login', methods\=\['GET', 'POST'\])
def login():
if request.method \== 'POST':
session\['username'\] \= request.form\['username'\]
return redirect(url\_for('index'))
return '''
'''
@app.route('/logout')
def logout():
\# remove the username from the session if it's there
session.pop('username', None)
return redirect(url\_for('index'))
How to generate good secret keys
A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for `Flask.secret_key` (or [`SECRET_KEY`](../config/#SECRET_KEY "SECRET_KEY")
):
$ python -c 'import secrets; print(secrets.token\_hex())'
'192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. If you are finding some values do not persist across requests, cookies are indeed enabled, and you are not getting a clear error message, check the size of the cookie in your page responses compared to the size supported by web browsers.
Besides the default client-side based sessions, if you want to handle sessions on the server-side instead, there are several Flask extensions that support this.
Message Flashing[¶](#message-flashing "Link to this heading")
--------------------------------------------------------------
Good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request. This is usually combined with a layout template to expose the message.
To flash a message use the [`flash()`](../api/#flask.flash "flask.flash")
method, to get hold of the messages you can use [`get_flashed_messages()`](../api/#flask.get_flashed_messages "flask.get_flashed_messages")
which is also available in the templates. See [Message Flashing](../patterns/flashing/)
for a full example.
Logging[¶](#logging "Link to this heading")
--------------------------------------------
Changelog
Added in version 0.3.
Sometimes you might be in a situation where you deal with data that should be correct, but actually is not. For example you may have some client-side code that sends an HTTP request to the server but it’s obviously malformed. This might be caused by a user tampering with the data, or the client code failing. Most of the time it’s okay to reply with `400 Bad Request` in that situation, but sometimes that won’t do and the code has to continue working.
You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you to use.
Here are some example log calls:
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
The attached [`logger`](../api/#flask.Flask.logger "flask.Flask.logger")
is a standard logging [`Logger`](https://docs.python.org/3/library/logging.html#logging.Logger "(in Python v3.13)")
, so head over to the official [`logging`](https://docs.python.org/3/library/logging.html#module-logging "(in Python v3.13)")
docs for more information.
See [Handling Application Errors](../errorhandling/)
.
Hooking in WSGI Middleware[¶](#hooking-in-wsgi-middleware "Link to this heading")
----------------------------------------------------------------------------------
To add WSGI middleware to your Flask application, wrap the application’s `wsgi_app` attribute. For example, to apply Werkzeug’s [`ProxyFix`](https://werkzeug.palletsprojects.com/en/stable/middleware/proxy_fix/#werkzeug.middleware.proxy_fix.ProxyFix "(in Werkzeug v3.1.x)")
middleware for running behind Nginx:
from werkzeug.middleware.proxy\_fix import ProxyFix
app.wsgi\_app \= ProxyFix(app.wsgi\_app)
Wrapping `app.wsgi_app` instead of `app` means that `app` still points at your Flask application, not at the middleware, so you can continue to use and configure `app` directly.
Using Flask Extensions[¶](#using-flask-extensions "Link to this heading")
--------------------------------------------------------------------------
Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask.
For more on Flask extensions, see [Extensions](../extensions/)
.
Deploying to a Web Server[¶](#deploying-to-a-web-server "Link to this heading")
--------------------------------------------------------------------------------
Ready to deploy your new Flask app? See [Deploying to Production](../deploying/)
.
[](../)
### Contents
* [Quickstart](#)
* [A Minimal Application](#a-minimal-application)
* [Debug Mode](#debug-mode)
* [HTML Escaping](#html-escaping)
* [Routing](#routing)
* [Variable Rules](#variable-rules)
* [Unique URLs / Redirection Behavior](#unique-urls-redirection-behavior)
* [URL Building](#url-building)
* [HTTP Methods](#http-methods)
* [Static Files](#static-files)
* [Rendering Templates](#rendering-templates)
* [Accessing Request Data](#accessing-request-data)
* [Context Locals](#context-locals)
* [The Request Object](#the-request-object)
* [File Uploads](#file-uploads)
* [Cookies](#cookies)
* [Redirects and Errors](#redirects-and-errors)
* [About Responses](#about-responses)
* [APIs with JSON](#apis-with-json)
* [Sessions](#sessions)
* [Message Flashing](#message-flashing)
* [Logging](#logging)
* [Hooking in WSGI Middleware](#hooking-in-wsgi-middleware)
* [Using Flask Extensions](#using-flask-extensions)
* [Deploying to a Web Server](#deploying-to-a-web-server)
### Navigation
* [Overview](../)
* Previous: [Installation](../installation/ "previous chapter")
* Next: [Tutorial](../tutorial/ "next chapter")
### Quick search
---
# Tutorial — Flask Documentation (3.1.x)
### Navigation
* [index](../genindex/ "General Index")
* [modules](../py-modindex/ "Python Module Index")
|
* [next](layout/ "Project Layout")
|
* [previous](../quickstart/ "Quickstart")
|
* [Flask Documentation (3.1.x)](../)
»
* Tutorial
Tutorial[¶](#tutorial "Link to this heading")
==============================================
Contents:
* [Project Layout](layout/)
* [Application Setup](factory/)
* [Define and Access the Database](database/)
* [Blueprints and Views](views/)
* [Templates](templates/)
* [Static Files](static/)
* [Blog Blueprint](blog/)
* [Make the Project Installable](install/)
* [Test Coverage](tests/)
* [Deploy to Production](deploy/)
* [Keep Developing!](next/)
This tutorial will walk you through creating a basic blog application called Flaskr. Users will be able to register, log in, create posts, and edit or delete their own posts. You will be able to package and install the application on other computers.

It’s assumed that you’re already familiar with Python. The [official tutorial](https://docs.python.org/3/tutorial/)
in the Python docs is a great way to learn or review first.
While it’s designed to give a good starting point, the tutorial doesn’t cover all of Flask’s features. Check out the [Quickstart](../quickstart/)
for an overview of what Flask can do, then dive into the docs to find out more. The tutorial only uses what’s provided by Flask and Python. In another project, you might decide to use [Extensions](../extensions/)
or other libraries to make some tasks simpler.

Flask is flexible. It doesn’t require you to use any particular project or code layout. However, when first starting, it’s helpful to use a more structured approach. This means that the tutorial will require a bit of boilerplate up front, but it’s done to avoid many common pitfalls that new developers encounter, and it creates a project that’s easy to expand on. Once you become more comfortable with Flask, you can step out of this structure and take full advantage of Flask’s flexibility.

[The tutorial project is available as an example in the Flask repository](https://github.com/pallets/flask/tree/main/examples/tutorial)
, if you want to compare your project with the final product as you follow the tutorial.
Continue to [Project Layout](layout/)
.
[](../)
### Navigation
* [Overview](../)
* Previous: [Quickstart](../quickstart/ "previous chapter")
* Next: [Project Layout](layout/ "next chapter")
### Quick search
---
# Python Module Index — Flask Documentation (3.1.x)
### Navigation
* [index](../genindex/ "General Index")
* [modules](# "Python Module Index")
|
* [Flask Documentation (3.1.x)](../)
»
* Python Module Index
Python Module Index
===================
[**f**](#cap-f)
| | | |
| --- | --- | --- |
| | | |
| | **f** | |
|  | [`flask`](../api/#module-flask) | |
| | [`flask.json`](../api/#module-flask.json) | |
| | [`flask.json.tag`](../api/#module-flask.json.tag) | |
[](../)
### Navigation
* [Overview](../)
### Quick search
---
# Patterns for Flask — Flask Documentation (3.1.x)
### Navigation
* [index](../genindex/ "General Index")
* [modules](../py-modindex/ "Python Module Index")
|
* [next](packages/ "Large Applications as Packages")
|
* [previous](../shell/ "Working with the Shell")
|
* [Flask Documentation (3.1.x)](../)
»
* Patterns for Flask
Patterns for Flask[¶](#patterns-for-flask "Link to this heading")
==================================================================
Certain features and interactions are common enough that you will find them in most web applications. For example, many applications use a relational database and user authentication. They will open a database connection at the beginning of the request and get the information for the logged in user. At the end of the request, the database connection is closed.
These types of patterns may be a bit outside the scope of Flask itself, but Flask makes it easy to implement them. Some common patterns are collected in the following pages.
* [Large Applications as Packages](packages/)
* [Simple Packages](packages/#simple-packages)
* [Working with Blueprints](packages/#working-with-blueprints)
* [Application Factories](appfactories/)
* [Basic Factories](appfactories/#basic-factories)
* [Factories & Extensions](appfactories/#factories-extensions)
* [Using Applications](appfactories/#using-applications)
* [Factory Improvements](appfactories/#factory-improvements)
* [Application Dispatching](appdispatch/)
* [Working with this Document](appdispatch/#working-with-this-document)
* [Combining Applications](appdispatch/#combining-applications)
* [Dispatch by Subdomain](appdispatch/#dispatch-by-subdomain)
* [Dispatch by Path](appdispatch/#dispatch-by-path)
* [Using URL Processors](urlprocessors/)
* [Internationalized Application URLs](urlprocessors/#internationalized-application-urls)
* [Internationalized Blueprint URLs](urlprocessors/#internationalized-blueprint-urls)
* [Using SQLite 3 with Flask](sqlite3/)
* [Connect on Demand](sqlite3/#connect-on-demand)
* [Easy Querying](sqlite3/#easy-querying)
* [Initial Schemas](sqlite3/#initial-schemas)
* [SQLAlchemy in Flask](sqlalchemy/)
* [Flask-SQLAlchemy Extension](sqlalchemy/#flask-sqlalchemy-extension)
* [Declarative](sqlalchemy/#declarative)
* [Manual Object Relational Mapping](sqlalchemy/#manual-object-relational-mapping)
* [SQL Abstraction Layer](sqlalchemy/#sql-abstraction-layer)
* [Uploading Files](fileuploads/)
* [A Gentle Introduction](fileuploads/#a-gentle-introduction)
* [Improving Uploads](fileuploads/#improving-uploads)
* [Upload Progress Bars](fileuploads/#upload-progress-bars)
* [An Easier Solution](fileuploads/#an-easier-solution)
* [Caching](caching/)
* [View Decorators](viewdecorators/)
* [Login Required Decorator](viewdecorators/#login-required-decorator)
* [Caching Decorator](viewdecorators/#caching-decorator)
* [Templating Decorator](viewdecorators/#templating-decorator)
* [Endpoint Decorator](viewdecorators/#endpoint-decorator)
* [Form Validation with WTForms](wtforms/)
* [The Forms](wtforms/#the-forms)
* [In the View](wtforms/#in-the-view)
* [Forms in Templates](wtforms/#forms-in-templates)
* [Template Inheritance](templateinheritance/)
* [Base Template](templateinheritance/#base-template)
* [Child Template](templateinheritance/#child-template)
* [Message Flashing](flashing/)
* [Simple Flashing](flashing/#simple-flashing)
* [Flashing With Categories](flashing/#flashing-with-categories)
* [Filtering Flash Messages](flashing/#filtering-flash-messages)
* [JavaScript, `fetch`, and JSON](javascript/)
* [Rendering Templates](javascript/#rendering-templates)
* [Generating URLs](javascript/#generating-urls)
* [Making a Request with `fetch`](javascript/#making-a-request-with-fetch)
* [Following Redirects](javascript/#following-redirects)
* [Replacing Content](javascript/#replacing-content)
* [Return JSON from Views](javascript/#return-json-from-views)
* [Receiving JSON in Views](javascript/#receiving-json-in-views)
* [Lazily Loading Views](lazyloading/)
* [Converting to Centralized URL Map](lazyloading/#converting-to-centralized-url-map)
* [Loading Late](lazyloading/#loading-late)
* [MongoDB with MongoEngine](mongoengine/)
* [Configuration](mongoengine/#configuration)
* [Mapping Documents](mongoengine/#mapping-documents)
* [Creating Data](mongoengine/#creating-data)
* [Queries](mongoengine/#queries)
* [Documentation](mongoengine/#documentation)
* [Adding a favicon](favicon/)
* [See also](favicon/#see-also)
* [Streaming Contents](streaming/)
* [Basic Usage](streaming/#basic-usage)
* [Streaming from Templates](streaming/#streaming-from-templates)
* [Streaming with Context](streaming/#streaming-with-context)
* [Deferred Request Callbacks](deferredcallbacks/)
* [Adding HTTP Method Overrides](methodoverrides/)
* [Request Content Checksums](requestchecksum/)
* [Background Tasks with Celery](celery/)
* [Install](celery/#install)
* [Integrate Celery with Flask](celery/#integrate-celery-with-flask)
* [Application Factory](celery/#application-factory)
* [Defining Tasks](celery/#defining-tasks)
* [Calling Tasks](celery/#calling-tasks)
* [Getting Results](celery/#getting-results)
* [Passing Data to Tasks](celery/#passing-data-to-tasks)
* [Subclassing Flask](subclassing/)
* [Single-Page Applications](singlepageapplications/)
[](../)
### Navigation
* [Overview](../)
* Previous: [Working with the Shell](../shell/ "previous chapter")
* Next: [Large Applications as Packages](packages/ "next chapter")
### Quick search
---
# Project Layout — Flask Documentation (3.1.x)
### Navigation
* [index](../../genindex/ "General Index")
* [modules](../../py-modindex/ "Python Module Index")
|
* [next](../factory/ "Application Setup")
|
* [previous](../ "Tutorial")
|
* [Flask Documentation (3.1.x)](../../)
»
* [Tutorial](../)
»
* Project Layout
Project Layout[¶](#project-layout "Link to this heading")
==========================================================
Create a project directory and enter it:
$ mkdir flask-tutorial
$ cd flask-tutorial
Then follow the [installation instructions](../../installation/)
to set up a Python virtual environment and install Flask for your project.
The tutorial will assume you’re working from the `flask-tutorial` directory from now on. The file names at the top of each code block are relative to this directory.
* * *
A Flask application can be as simple as a single file.
`hello.py`[¶](#id1 "Link to this code")
from flask import Flask
app \= Flask(\_\_name\_\_)
@app.route('/')
def hello():
return 'Hello, World!'
However, as a project gets bigger, it becomes overwhelming to keep all the code in one file. Python projects use _packages_ to organize code into multiple modules that can be imported where needed, and the tutorial will do this as well.
The project directory will contain:
* `flaskr/`, a Python package containing your application code and files.
* `tests/`, a directory containing test modules.
* `.venv/`, a Python virtual environment where Flask and other dependencies are installed.
* Installation files telling Python how to install your project.
* Version control config, such as [git](https://git-scm.com/)
. You should make a habit of using some type of version control for all your projects, no matter the size.
* Any other project files you might add in the future.
By the end, your project layout will look like this:
/home/user/Projects/flask-tutorial
├── flaskr/
│ ├── \_\_init\_\_.py
│ ├── db.py
│ ├── schema.sql
│ ├── auth.py
│ ├── blog.py
│ ├── templates/
│ │ ├── base.html
│ │ ├── auth/
│ │ │ ├── login.html
│ │ │ └── register.html
│ │ └── blog/
│ │ ├── create.html
│ │ ├── index.html
│ │ └── update.html
│ └── static/
│ └── style.css
├── tests/
│ ├── conftest.py
│ ├── data.sql
│ ├── test\_factory.py
│ ├── test\_db.py
│ ├── test\_auth.py
│ └── test\_blog.py
├── .venv/
├── pyproject.toml
└── MANIFEST.in
If you’re using version control, the following files that are generated while running your project should be ignored. There may be other files based on the editor you use. In general, ignore files that you didn’t write. For example, with git:
`.gitignore`[¶](#id2 "Link to this code")
.venv/
\*.pyc
\_\_pycache\_\_/
instance/
.pytest\_cache/
.coverage
htmlcov/
dist/
build/
\*.egg-info/
Continue to [Application Setup](../factory/)
.
[](../../)
### Navigation
* [Overview](../../)
* [Tutorial](../)
* Previous: [Tutorial](../ "previous chapter")
* Next: [Application Setup](../factory/ "next chapter")
### Quick search
---
# Templates — Flask Documentation (3.1.x)
### Navigation
* [index](../../genindex/ "General Index")
* [modules](../../py-modindex/ "Python Module Index")
|
* [next](../static/ "Static Files")
|
* [previous](../views/ "Blueprints and Views")
|
* [Flask Documentation (3.1.x)](../../)
»
* [Tutorial](../)
»
* Templates
Templates[¶](#templates "Link to this heading")
================================================
You’ve written the authentication views for your application, but if you’re running the server and try to go to any of the URLs, you’ll see a `TemplateNotFound` error. That’s because the views are calling [`render_template()`](../../api/#flask.render_template "flask.render_template")
, but you haven’t written the templates yet. The template files will be stored in the `templates` directory inside the `flaskr` package.
Templates are files that contain static data as well as placeholders for dynamic data. A template is rendered with specific data to produce a final document. Flask uses the [Jinja](https://jinja.palletsprojects.com/templates/)
template library to render templates.
In your application, you will use templates to render [HTML](https://developer.mozilla.org/docs/Web/HTML)
which will display in the user’s browser. In Flask, Jinja is configured to _autoescape_ any data that is rendered in HTML templates. This means that it’s safe to render user input; any characters they’ve entered that could mess with the HTML, such as `<` and `>` will be _escaped_ with _safe_ values that look the same in the browser but don’t cause unwanted effects.
Jinja looks and behaves mostly like Python. Special delimiters are used to distinguish Jinja syntax from the static data in the template. Anything between `{{` and `}}` is an expression that will be output to the final document. `{%` and `%}` denotes a control flow statement like `if` and `for`. Unlike Python, blocks are denoted by start and end tags rather than indentation since static text within a block could change indentation.
The Base Layout[¶](#the-base-layout "Link to this heading")
------------------------------------------------------------
Each page in the application will have the same basic layout around a different body. Instead of writing the entire HTML structure in each template, each template will _extend_ a base template and override specific sections.
`flaskr/templates/base.html`[¶](#id1 "Link to this code")
{% block title %}{% endblock %} - Flaskr
{% block header %}{% endblock %}
{% for message in get\_flashed\_messages() %}
{{ message }}
{% endfor %}
{% block content %}{% endblock %}
[`g`](../../api/#flask.g "flask.g")
is automatically available in templates. Based on if `g.user` is set (from `load_logged_in_user`), either the username and a log out link are displayed, or links to register and log in are displayed. [`url_for()`](../../api/#flask.url_for "flask.url_for")
is also automatically available, and is used to generate URLs to views instead of writing them out manually.
After the page title, and before the content, the template loops over each message returned by [`get_flashed_messages()`](../../api/#flask.get_flashed_messages "flask.get_flashed_messages")
. You used [`flash()`](../../api/#flask.flash "flask.flash")
in the views to show error messages, and this is the code that will display them.
There are three blocks defined here that will be overridden in the other templates:
1. `{% block title %}` will change the title displayed in the browser’s tab and window title.
2. `{% block header %}` is similar to `title` but will change the title displayed on the page.
3. `{% block content %}` is where the content of each page goes, such as the login form or a blog post.
The base template is directly in the `templates` directory. To keep the others organized, the templates for a blueprint will be placed in a directory with the same name as the blueprint.
Register[¶](#register "Link to this heading")
----------------------------------------------
`flaskr/templates/auth/register.html`[¶](#id2 "Link to this code")
{% extends 'base.html' %}
{% block header %}
{% block title %}Register{% endblock %}
{% endblock %}
{% block content %}
{% endblock %}
`{% extends 'base.html' %}` tells Jinja that this template should replace the blocks from the base template. All the rendered content must appear inside `{% block %}` tags that override blocks from the base template.
A useful pattern used here is to place `{% block title %}` inside `{% block header %}`. This will set the title block and then output the value of it into the header block, so that both the window and page share the same title without writing it twice.
The `input` tags are using the `required` attribute here. This tells the browser not to submit the form until those fields are filled in. If the user is using an older browser that doesn’t support that attribute, or if they are using something besides a browser to make requests, you still want to validate the data in the Flask view. It’s important to always fully validate the data on the server, even if the client does some validation as well.
Log In[¶](#log-in "Link to this heading")
------------------------------------------
This is identical to the register template except for the title and submit button.
`flaskr/templates/auth/login.html`[¶](#id3 "Link to this code")
{% extends 'base.html' %}
{% block header %}
{% block title %}Log In{% endblock %}
{% endblock %}
{% block content %}
{% endblock %}
Register A User[¶](#register-a-user "Link to this heading")
------------------------------------------------------------
Now that the authentication templates are written, you can register a user. Make sure the server is still running (`flask run` if it’s not), then go to [http://127.0.0.1:5000/auth/register](http://127.0.0.1:5000/auth/register)
.
Try clicking the “Register” button without filling out the form and see that the browser shows an error message. Try removing the `required` attributes from the `register.html` template and click “Register” again. Instead of the browser showing an error, the page will reload and the error from [`flash()`](../../api/#flask.flash "flask.flash")
in the view will be shown.
Fill out a username and password and you’ll be redirected to the login page. Try entering an incorrect username, or the correct username and incorrect password. If you log in you’ll get an error because there’s no `index` view to redirect to yet.
Continue to [Static Files](../static/)
.
[](../../)
### Contents
* [Templates](#)
* [The Base Layout](#the-base-layout)
* [Register](#register)
* [Log In](#log-in)
* [Register A User](#register-a-user)
### Navigation
* [Overview](../../)
* [Tutorial](../)
* Previous: [Blueprints and Views](../views/ "previous chapter")
* Next: [Static Files](../static/ "next chapter")
### Quick search
---
# Static Files — Flask Documentation (3.1.x)
### Navigation
* [index](../../genindex/ "General Index")
* [modules](../../py-modindex/ "Python Module Index")
|
* [next](../blog/ "Blog Blueprint")
|
* [previous](../templates/ "Templates")
|
* [Flask Documentation (3.1.x)](../../)
»
* [Tutorial](../)
»
* Static Files
Static Files[¶](#static-files "Link to this heading")
======================================================
The authentication views and templates work, but they look very plain right now. Some [CSS](https://developer.mozilla.org/docs/Web/CSS)
can be added to add style to the HTML layout you constructed. The style won’t change, so it’s a _static_ file rather than a template.
Flask automatically adds a `static` view that takes a path relative to the `flaskr/static` directory and serves it. The `base.html` template already has a link to the `style.css` file:
{{ url\_for('static', filename\='style.css') }}
Besides CSS, other types of static files might be files with JavaScript functions, or a logo image. They are all placed under the `flaskr/static` directory and referenced with `url_for('static', filename='...')`.
This tutorial isn’t focused on how to write CSS, so you can just copy the following into the `flaskr/static/style.css` file:
`flaskr/static/style.css`[¶](#id1 "Link to this code")
html { font-family: sans-serif; background: #eee; padding: 1rem; }
body { max-width: 960px; margin: 0 auto; background: white; }
h1 { font-family: serif; color: #377ba8; margin: 1rem 0; }
a { color: #377ba8; }
hr { border: none; border-top: 1px solid lightgray; }
nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; }
nav h1 { flex: auto; margin: 0; }
nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; }
nav ul { display: flex; list-style: none; margin: 0; padding: 0; }
nav ul li a, nav ul li span, header .action { display: block; padding: 0.5rem; }
.content { padding: 0 1rem 1rem; }
.content \> header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; }
.content \> header h1 { flex: auto; margin: 1rem 0 0.25rem 0; }
.flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; }
.post \> header { display: flex; align-items: flex-end; font-size: 0.85em; }
.post \> header \> div:first-of-type { flex: auto; }
.post \> header h1 { font-size: 1.5em; margin-bottom: 0; }
.post .about { color: slategray; font-style: italic; }
.post .body { white-space: pre-line; }
.content:last-child { margin-bottom: 0; }
.content form { margin: 1em 0; display: flex; flex-direction: column; }
.content label { font-weight: bold; margin-bottom: 0.5em; }
.content input, .content textarea { margin-bottom: 1em; }
.content textarea { min-height: 12em; resize: vertical; }
input.danger { color: #cc2f2e; }
input\[type\=submit\] { align-self: start; min-width: 10em; }
You can find a less compact version of `style.css` in the [example code](https://github.com/pallets/flask/tree/main/examples/tutorial/flaskr/static/style.css)
.
Go to [http://127.0.0.1:5000/auth/login](http://127.0.0.1:5000/auth/login)
and the page should look like the screenshot below.

You can read more about CSS from [Mozilla’s documentation](https://developer.mozilla.org/docs/Web/CSS)
. If you change a static file, refresh the browser page. If the change doesn’t show up, try clearing your browser’s cache.
Continue to [Blog Blueprint](../blog/)
.
[](../../)
### Navigation
* [Overview](../../)
* [Tutorial](../)
* Previous: [Templates](../templates/ "previous chapter")
* Next: [Blog Blueprint](../blog/ "next chapter")
### Quick search
---
# Signals — Flask Documentation (3.1.x)
### Navigation
* [index](../genindex/ "General Index")
* [modules](../py-modindex/ "Python Module Index")
|
* [next](../views/ "Class-based Views")
|
* [previous](../config/ "Configuration Handling")
|
* [Flask Documentation (3.1.x)](../)
»
* Signals
Signals[¶](#signals "Link to this heading")
============================================
Signals are a lightweight way to notify subscribers of certain events during the lifecycle of the application and each request. When an event occurs, it emits the signal, which calls each subscriber.
Signals are implemented by the [Blinker](https://pypi.org/project/blinker/)
library. See its documentation for detailed information. Flask provides some built-in signals. Extensions may provide their own.
Many signals mirror Flask’s decorator-based callbacks with similar names. For example, the [`request_started`](../api/#flask.request_started "flask.request_started")
signal is similar to the [`before_request()`](../api/#flask.Flask.before_request "flask.Flask.before_request")
decorator. The advantage of signals over handlers is that they can be subscribed to temporarily, and can’t directly affect the application. This is useful for testing, metrics, auditing, and more. For example, if you want to know what templates were rendered at what parts of what requests, there is a signal that will notify you of that information.
Core Signals[¶](#core-signals "Link to this heading")
------------------------------------------------------
See [Signals](../api/#core-signals-list)
for a list of all built-in signals. The [Application Structure and Lifecycle](../lifecycle/)
page also describes the order that signals and decorators execute.
Subscribing to Signals[¶](#subscribing-to-signals "Link to this heading")
--------------------------------------------------------------------------
To subscribe to a signal, you can use the `connect()` method of a signal. The first argument is the function that should be called when the signal is emitted, the optional second argument specifies a sender. To unsubscribe from a signal, you can use the `disconnect()` method.
For all core Flask signals, the sender is the application that issued the signal. When you subscribe to a signal, be sure to also provide a sender unless you really want to listen for signals from all applications. This is especially true if you are developing an extension.
For example, here is a helper context manager that can be used in a unit test to determine which templates were rendered and what variables were passed to the template:
from flask import template\_rendered
from contextlib import contextmanager
@contextmanager
def captured\_templates(app):
recorded \= \[\]
def record(sender, template, context, \*\*extra):
recorded.append((template, context))
template\_rendered.connect(record, app)
try:
yield recorded
finally:
template\_rendered.disconnect(record, app)
This can now easily be paired with a test client:
with captured\_templates(app) as templates:
rv \= app.test\_client().get('/')
assert rv.status\_code \== 200
assert len(templates) \== 1
template, context \= templates\[0\]
assert template.name \== 'index.html'
assert len(context\['items'\]) \== 10
Make sure to subscribe with an extra `**extra` argument so that your calls don’t fail if Flask introduces new arguments to the signals.
All the template rendering in the code issued by the application `app` in the body of the `with` block will now be recorded in the `templates` variable. Whenever a template is rendered, the template object as well as context are appended to it.
Additionally there is a convenient helper method (`connected_to()`) that allows you to temporarily subscribe a function to a signal with a context manager on its own. Because the return value of the context manager cannot be specified that way, you have to pass the list in as an argument:
from flask import template\_rendered
def captured\_templates(app, recorded, \*\*extra):
def record(sender, template, context):
recorded.append((template, context))
return template\_rendered.connected\_to(record, app)
The example above would then look like this:
templates \= \[\]
with captured\_templates(app, templates, \*\*extra):
...
template, context \= templates\[0\]
Creating Signals[¶](#creating-signals "Link to this heading")
--------------------------------------------------------------
If you want to use signals in your own application, you can use the blinker library directly. The most common use case are named signals in a custom [`Namespace`](https://blinker.readthedocs.io/en/stable/#blinker.Namespace "(in Blinker v1.9)")
. This is what is recommended most of the time:
from blinker import Namespace
my\_signals \= Namespace()
Now you can create new signals like this:
model\_saved \= my\_signals.signal('model-saved')
The name for the signal here makes it unique and also simplifies debugging. You can access the name of the signal with the `name` attribute.
Sending Signals[¶](#sending-signals "Link to this heading")
------------------------------------------------------------
If you want to emit a signal, you can do so by calling the `send()` method. It accepts a sender as first argument and optionally some keyword arguments that are forwarded to the signal subscribers:
class Model(object):
...
def save(self):
model\_saved.send(self)
Try to always pick a good sender. If you have a class that is emitting a signal, pass `self` as sender. If you are emitting a signal from a random function, you can pass `current_app._get_current_object()` as sender.
Passing Proxies as Senders
Never pass [`current_app`](../api/#flask.current_app "flask.current_app")
as sender to a signal. Use `current_app._get_current_object()` instead. The reason for this is that [`current_app`](../api/#flask.current_app "flask.current_app")
is a proxy and not the real application object.
Signals and Flask’s Request Context[¶](#signals-and-flask-s-request-context "Link to this heading")
----------------------------------------------------------------------------------------------------
Signals fully support [The Request Context](../reqcontext/)
when receiving signals. Context-local variables are consistently available between [`request_started`](../api/#flask.request_started "flask.request_started")
and [`request_finished`](../api/#flask.request_finished "flask.request_finished")
, so you can rely on [`flask.g`](../api/#flask.g "flask.g")
and others as needed. Note the limitations described in [Sending Signals](#signals-sending)
and the [`request_tearing_down`](../api/#flask.request_tearing_down "flask.request_tearing_down")
signal.
Decorator Based Signal Subscriptions[¶](#decorator-based-signal-subscriptions "Link to this heading")
------------------------------------------------------------------------------------------------------
You can also easily subscribe to signals by using the `connect_via()` decorator:
from flask import template\_rendered
@template\_rendered.connect\_via(app)
def when\_template\_rendered(sender, template, context, \*\*extra):
print(f'Template {template.name} is rendered with {context}')
[](../)
### Contents
* [Signals](#)
* [Core Signals](#core-signals)
* [Subscribing to Signals](#subscribing-to-signals)
* [Creating Signals](#creating-signals)
* [Sending Signals](#sending-signals)
* [Signals and Flask’s Request Context](#signals-and-flask-s-request-context)
* [Decorator Based Signal Subscriptions](#decorator-based-signal-subscriptions)
### Navigation
* [Overview](../)
* Previous: [Configuration Handling](../config/ "previous chapter")
* Next: [Class-based Views](../views/ "next chapter")
### Quick search
---
# Blog Blueprint — Flask Documentation (3.1.x)
### Navigation
* [index](../../genindex/ "General Index")
* [modules](../../py-modindex/ "Python Module Index")
|
* [next](../install/ "Make the Project Installable")
|
* [previous](../static/ "Static Files")
|
* [Flask Documentation (3.1.x)](../../)
»
* [Tutorial](../)
»
* Blog Blueprint
Blog Blueprint[¶](#blog-blueprint "Link to this heading")
==========================================================
You’ll use the same techniques you learned about when writing the authentication blueprint to write the blog blueprint. The blog should list all posts, allow logged in users to create posts, and allow the author of a post to edit or delete it.
As you implement each view, keep the development server running. As you save your changes, try going to the URL in your browser and testing them out.
The Blueprint[¶](#the-blueprint "Link to this heading")
--------------------------------------------------------
Define the blueprint and register it in the application factory.
`flaskr/blog.py`[¶](#id1 "Link to this code")
from flask import (
Blueprint, flash, g, redirect, render\_template, request, url\_for
)
from werkzeug.exceptions import abort
from flaskr.auth import login\_required
from flaskr.db import get\_db
bp \= Blueprint('blog', \_\_name\_\_)
Import and register the blueprint from the factory using [`app.register_blueprint()`](../../api/#flask.Flask.register_blueprint "flask.Flask.register_blueprint")
. Place the new code at the end of the factory function before returning the app.
`flaskr/__init__.py`[¶](#id2 "Link to this code")
def create\_app():
app \= ...
\# existing code omitted
from . import blog
app.register\_blueprint(blog.bp)
app.add\_url\_rule('/', endpoint\='index')
return app
Unlike the auth blueprint, the blog blueprint does not have a `url_prefix`. So the `index` view will be at `/`, the `create` view at `/create`, and so on. The blog is the main feature of Flaskr, so it makes sense that the blog index will be the main index.
However, the endpoint for the `index` view defined below will be `blog.index`. Some of the authentication views referred to a plain `index` endpoint. [`app.add_url_rule()`](../../api/#flask.Flask.add_url_rule "flask.Flask.add_url_rule")
associates the endpoint name `'index'` with the `/` url so that `url_for('index')` or `url_for('blog.index')` will both work, generating the same `/` URL either way.
In another application you might give the blog blueprint a `url_prefix` and define a separate `index` view in the application factory, similar to the `hello` view. Then the `index` and `blog.index` endpoints and URLs would be different.
Index[¶](#index "Link to this heading")
----------------------------------------
The index will show all of the posts, most recent first. A `JOIN` is used so that the author information from the `user` table is available in the result.
`flaskr/blog.py`[¶](#id3 "Link to this code")
@bp.route('/')
def index():
db \= get\_db()
posts \= db.execute(
'SELECT p.id, title, body, created, author\_id, username'
' FROM post p JOIN user u ON p.author\_id = u.id'
' ORDER BY created DESC'
).fetchall()
return render\_template('blog/index.html', posts\=posts)
`flaskr/templates/blog/index.html`[¶](#id4 "Link to this code")
{% extends 'base.html' %}
{% block header %}
{% block title %}Posts{% endblock %}
{% if g.user %}
New
{% endif %}
{% endblock %}
{% block content %}
{% for post in posts %}
{{ post\['title'\] }}
by {{ post\['username'\] }} on {{ post\['created'\].strftime('%Y-%m-%d') }}
{% if g.user\['id'\] \== post\['author\_id'\] %}
Edit
{% endif %}
{{ post\['body'\] }}
{% if not loop.last %}
{% endif %}
{% endfor %}
{% endblock %}
When a user is logged in, the `header` block adds a link to the `create` view. When the user is the author of a post, they’ll see an “Edit” link to the `update` view for that post. `loop.last` is a special variable available inside [Jinja for loops](https://jinja.palletsprojects.com/templates/#for)
. It’s used to display a line after each post except the last one, to visually separate them.
Create[¶](#create "Link to this heading")
------------------------------------------
The `create` view works the same as the auth `register` view. Either the form is displayed, or the posted data is validated and the post is added to the database or an error is shown.
The `login_required` decorator you wrote earlier is used on the blog views. A user must be logged in to visit these views, otherwise they will be redirected to the login page.
`flaskr/blog.py`[¶](#id5 "Link to this code")
@bp.route('/create', methods\=('GET', 'POST'))
@login\_required
def create():
if request.method \== 'POST':
title \= request.form\['title'\]
body \= request.form\['body'\]
error \= None
if not title:
error \= 'Title is required.'
if error is not None:
flash(error)
else:
db \= get\_db()
db.execute(
'INSERT INTO post (title, body, author\_id)'
' VALUES (?, ?, ?)',
(title, body, g.user\['id'\])
)
db.commit()
return redirect(url\_for('blog.index'))
return render\_template('blog/create.html')
`flaskr/templates/blog/create.html`[¶](#id6 "Link to this code")
{% extends 'base.html' %}
{% block header %}
{% block title %}New Post{% endblock %}
{% endblock %}
{% block content %}
{% endblock %}
Update[¶](#update "Link to this heading")
------------------------------------------
Both the `update` and `delete` views will need to fetch a `post` by `id` and check if the author matches the logged in user. To avoid duplicating code, you can write a function to get the `post` and call it from each view.
`flaskr/blog.py`[¶](#id7 "Link to this code")
def get\_post(id, check\_author\=True):
post \= get\_db().execute(
'SELECT p.id, title, body, created, author\_id, username'
' FROM post p JOIN user u ON p.author\_id = u.id'
' WHERE p.id = ?',
(id,)
).fetchone()
if post is None:
abort(404, f"Post id {id} doesn't exist.")
if check\_author and post\['author\_id'\] != g.user\['id'\]:
abort(403)
return post
[`abort()`](../../api/#flask.abort "flask.abort")
will raise a special exception that returns an HTTP status code. It takes an optional message to show with the error, otherwise a default message is used. `404` means “Not Found”, and `403` means “Forbidden”. (`401` means “Unauthorized”, but you redirect to the login page instead of returning that status.)
The `check_author` argument is defined so that the function can be used to get a `post` without checking the author. This would be useful if you wrote a view to show an individual post on a page, where the user doesn’t matter because they’re not modifying the post.
`flaskr/blog.py`[¶](#id8 "Link to this code")
@bp.route('//update', methods\=('GET', 'POST'))
@login\_required
def update(id):
post \= get\_post(id)
if request.method \== 'POST':
title \= request.form\['title'\]
body \= request.form\['body'\]
error \= None
if not title:
error \= 'Title is required.'
if error is not None:
flash(error)
else:
db \= get\_db()
db.execute(
'UPDATE post SET title = ?, body = ?'
' WHERE id = ?',
(title, body, id)
)
db.commit()
return redirect(url\_for('blog.index'))
return render\_template('blog/update.html', post\=post)
Unlike the views you’ve written so far, the `update` function takes an argument, `id`. That corresponds to the `` in the route. A real URL will look like `/1/update`. Flask will capture the `1`, ensure it’s an [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
, and pass it as the `id` argument. If you don’t specify `int:` and instead do ``, it will be a string. To generate a URL to the update page, [`url_for()`](../../api/#flask.url_for "flask.url_for")
needs to be passed the `id` so it knows what to fill in: `url_for('blog.update', id=post['id'])`. This is also in the `index.html` file above.
The `create` and `update` views look very similar. The main difference is that the `update` view uses a `post` object and an `UPDATE` query instead of an `INSERT`. With some clever refactoring, you could use one view and template for both actions, but for the tutorial it’s clearer to keep them separate.
`flaskr/templates/blog/update.html`[¶](#id9 "Link to this code")
{% extends 'base.html' %}
{% block header %}
{% block title %}Edit "{{ post\['title'\] }}"{% endblock %}
{% endblock %}
{% block content %}
{% endblock %}
This template has two forms. The first posts the edited data to the current page (`//update`). The other form contains only a button and specifies an `action` attribute that posts to the delete view instead. The button uses some JavaScript to show a confirmation dialog before submitting.
The pattern `{{ request.form['title'] or post['title'] }}` is used to choose what data appears in the form. When the form hasn’t been submitted, the original `post` data appears, but if invalid form data was posted you want to display that so the user can fix the error, so `request.form` is used instead. [`request`](../../api/#flask.request "flask.request")
is another variable that’s automatically available in templates.
Delete[¶](#delete "Link to this heading")
------------------------------------------
The delete view doesn’t have its own template, the delete button is part of `update.html` and posts to the `//delete` URL. Since there is no template, it will only handle the `POST` method and then redirect to the `index` view.
`flaskr/blog.py`[¶](#id10 "Link to this code")
@bp.route('//delete', methods\=('POST',))
@login\_required
def delete(id):
get\_post(id)
db \= get\_db()
db.execute('DELETE FROM post WHERE id = ?', (id,))
db.commit()
return redirect(url\_for('blog.index'))
Congratulations, you’ve now finished writing your application! Take some time to try out everything in the browser. However, there’s still more to do before the project is complete.
Continue to [Make the Project Installable](../install/)
.
[](../../)
### Contents
* [Blog Blueprint](#)
* [The Blueprint](#the-blueprint)
* [Index](#index)
* [Create](#create)
* [Update](#update)
* [Delete](#delete)
### Navigation
* [Overview](../../)
* [Tutorial](../)
* Previous: [Static Files](../static/ "previous chapter")
* Next: [Make the Project Installable](../install/ "next chapter")
### Quick search
---
# Make the Project Installable — Flask Documentation (3.1.x)
### Navigation
* [index](../../genindex/ "General Index")
* [modules](../../py-modindex/ "Python Module Index")
|
* [next](../tests/ "Test Coverage")
|
* [previous](../blog/ "Blog Blueprint")
|
* [Flask Documentation (3.1.x)](../../)
»
* [Tutorial](../)
»
* Make the Project Installable
Make the Project Installable[¶](#make-the-project-installable "Link to this heading")
======================================================================================
Making your project installable means that you can build a _wheel_ file and install that in another environment, just like you installed Flask in your project’s environment. This makes deploying your project the same as installing any other library, so you’re using all the standard Python tools to manage everything.
Installing also comes with other benefits that might not be obvious from the tutorial or as a new Python user, including:
* Currently, Python and Flask understand how to use the `flaskr` package only because you’re running from your project’s directory. Installing means you can import it no matter where you run from.
* You can manage your project’s dependencies just like other packages do, so `pip install yourproject.whl` installs them.
* Test tools can isolate your test environment from your development environment.
Note
This is being introduced late in the tutorial, but in your future projects you should always start with this.
Describe the Project[¶](#describe-the-project "Link to this heading")
----------------------------------------------------------------------
The `pyproject.toml` file describes your project and how to build it.
`pyproject.toml`[¶](#id1 "Link to this code")
\[project\]
name \= "flaskr"
version \= "1.0.0"
description \= "The basic blog app built in the Flask tutorial."
dependencies \= \[\
"flask",\
\]
\[build-system\]
requires \= \["flit\_core<4"\]
build-backend \= "flit\_core.buildapi"
See the official [Packaging tutorial](https://packaging.python.org/tutorials/packaging-projects/)
for more explanation of the files and options used.
Install the Project[¶](#install-the-project "Link to this heading")
--------------------------------------------------------------------
Use `pip` to install your project in the virtual environment.
$ pip install -e .
This tells pip to find `pyproject.toml` in the current directory and install the project in _editable_ or _development_ mode. Editable mode means that as you make changes to your local code, you’ll only need to re-install if you change the metadata about the project, such as its dependencies.
You can observe that the project is now installed with `pip list`.
$ pip list
Package Version Location
-------------- --------- ----------------------------------
click 6.7
Flask 1.0
flaskr 1.0.0 /home/user/Projects/flask-tutorial
itsdangerous 0.24
Jinja2 2.10
MarkupSafe 1.0
pip 9.0.3
Werkzeug 0.14.1
Nothing changes from how you’ve been running your project so far. `--app` is still set to `flaskr` and `flask run` still runs the application, but you can call it from anywhere, not just the `flask-tutorial` directory.
Continue to [Test Coverage](../tests/)
.
[](../../)
### Contents
* [Make the Project Installable](#)
* [Describe the Project](#describe-the-project)
* [Install the Project](#install-the-project)
### Navigation
* [Overview](../../)
* [Tutorial](../)
* Previous: [Blog Blueprint](../blog/ "previous chapter")
* Next: [Test Coverage](../tests/ "next chapter")
### Quick search
---
# API — Flask Documentation (3.1.x)
### Navigation
* [index](../genindex/ "General Index")
* [modules](../py-modindex/ "Python Module Index")
|
* [next](../design/ "Design Decisions in Flask")
|
* [previous](../async-await/ "Using async and await")
|
* [Flask Documentation (3.1.x)](../)
»
* API
API[¶](#module-flask "Link to this heading")
=============================================
This part of the documentation covers all the interfaces of Flask. For parts where Flask depends on external libraries, we document the most important right here and provide links to the canonical documentation.
Application Object[¶](#application-object "Link to this heading")
------------------------------------------------------------------
_class_ flask.Flask(_import\_name_, _static\_url\_path\=None_, _static\_folder\='static'_, _static\_host\=None_, _host\_matching\=False_, _subdomain\_matching\=False_, _template\_folder\='templates'_, _instance\_path\=None_, _instance\_relative\_config\=False_, _root\_path\=None_)[¶](#flask.Flask "Link to this definition")
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()`](#flask.Flask.open_resource "flask.Flask.open_resource")
.
Usually you create a [`Flask`](#flask.Flask "flask.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`)
Changelog
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`](../config/#SERVER_NAME "SERVER_NAME")
does not implicitly enable it.
Added in version 0.11: The `root_path` parameter was added.
Added in version 0.8: The `instance_path` and `instance_relative_config` parameters were added.
Added in version 0.7: The `static_url_path`, `static_folder`, and `template_folder` parameters were added.
Parameters:
* **import\_name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – the name of the application package
* **static\_url\_path** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _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_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ [_os.PathLike_](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.13)")
_\[_[_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
_\]_ _|_ _None_) – 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** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the host to use when adding the static route. Defaults to None. Required when using `host_matching=True` with a `static_folder` configured.
* **host\_matching** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
) – set `url_map.host_matching` attribute. Defaults to False.
* **subdomain\_matching** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
) – consider the subdomain relative to [`SERVER_NAME`](../config/#SERVER_NAME "SERVER_NAME")
when matching routes. Defaults to False.
* **template\_folder** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ [_os.PathLike_](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.13)")
_\[_[_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
_\]_ _|_ _None_) – 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** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _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_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
) – 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_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _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.
request\_class[¶](#flask.Flask.request_class "Link to this definition")
alias of [`Request`](#flask.Request "flask.wrappers.Request")
response\_class[¶](#flask.Flask.response_class "Link to this definition")
alias of [`Response`](#flask.Response "flask.wrappers.Response")
session\_interface_: [SessionInterface](#flask.sessions.SessionInterface "flask.sessions.SessionInterface")
_ _\= _[¶](#flask.Flask.session_interface "Link to this definition")
the session interface to use. By default an instance of [`SecureCookieSessionInterface`](#flask.sessions.SecureCookieSessionInterface "flask.sessions.SecureCookieSessionInterface")
is used here.
Changelog
Added in version 0.8.
cli_: Group_[¶](#flask.Flask.cli "Link to this definition")
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_)[¶](#flask.Flask.get_send_file_max_age "Link to this definition")
Used by [`send_file()`](#flask.send_file "flask.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`](../config/#SEND_FILE_MAX_AGE_DEFAULT "SEND_FILE_MAX_AGE_DEFAULT")
from the configuration of [`current_app`](#flask.current_app "flask.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.
Changelog
Changed in version 2.0: The default configuration is `None` instead of 12 hours.
Added in version 0.9.
Parameters:
**filename** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_)
Return type:
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
| None
send\_static\_file(_filename_)[¶](#flask.Flask.send_static_file "Link to this definition")
The view function used to serve files from [`static_folder`](#flask.Flask.static_folder "flask.Flask.static_folder")
. A route is automatically registered for this view at [`static_url_path`](#flask.Flask.static_url_path "flask.Flask.static_url_path")
if [`static_folder`](#flask.Flask.static_folder "flask.Flask.static_folder")
is set.
Note this is a duplicate of the same method in the Flask class.
Changelog
Added in version 0.5.
Parameters:
**filename** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
Return type:
[_Response_](#flask.Response "flask.wrappers.Response")
open\_resource(_resource_, _mode\='rb'_, _encoding\=None_)[¶](#flask.Flask.open_resource "Link to this definition")
Open a resource file relative to [`root_path`](#flask.Flask.root_path "flask.Flask.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** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – Path to the resource relative to [`root_path`](#flask.Flask.root_path "flask.Flask.root_path")
.
* **mode** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – Open the file in this mode. Only reading is supported, valid values are `"r"` (or `"rt"`) and `"rb"`.
* **encoding** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – Open the file with this encoding when opening in text mode. This is ignored when opening in binary mode.
Return type:
[_IO_](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.13)")
Changed in version 3.1: Added the `encoding` parameter.
open\_instance\_resource(_resource_, _mode\='rb'_, _encoding\='utf-8'_)[¶](#flask.Flask.open_instance_resource "Link to this definition")
Open a resource file relative to the application’s instance folder [`instance_path`](#flask.Flask.instance_path "flask.Flask.instance_path")
. Unlike [`open_resource()`](#flask.Flask.open_resource "flask.Flask.open_resource")
, files in the instance folder can be opened for writing.
Parameters:
* **resource** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – Path to the resource relative to [`instance_path`](#flask.Flask.instance_path "flask.Flask.instance_path")
.
* **mode** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – Open the file in this mode.
* **encoding** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – Open the file with this encoding when opening in text mode. This is ignored when opening in binary mode.
Return type:
[_IO_](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.13)")
Changed in version 3.1: Added the `encoding` parameter.
create\_jinja\_environment()[¶](#flask.Flask.create_jinja_environment "Link to this definition")
Create the Jinja environment based on [`jinja_options`](#flask.Flask.jinja_options "flask.Flask.jinja_options")
and the various Jinja-related methods of the app. Changing [`jinja_options`](#flask.Flask.jinja_options "flask.Flask.jinja_options")
after this will have no effect. Also adds Flask-related globals and filters to the environment.
Changelog
Changed in version 0.11: `Environment.auto_reload` set in accordance with `TEMPLATES_AUTO_RELOAD` configuration option.
Added in version 0.5.
Return type:
_Environment_
create\_url\_adapter(_request_)[¶](#flask.Flask.create_url_adapter "Link to this definition")
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`](../config/#SERVER_NAME "SERVER_NAME")
is set, it does not restrict requests to only that domain, for both `subdomain_matching` and `host_matching`.
Changelog
Changed in version 1.0: [`SERVER_NAME`](../config/#SERVER_NAME "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.
Parameters:
**request** ([_Request_](#flask.Request "flask.wrappers.Request")
_|_ _None_)
Return type:
[_MapAdapter_](https://werkzeug.palletsprojects.com/en/stable/routing/#werkzeug.routing.MapAdapter "(in Werkzeug v3.1.x)")
| None
update\_template\_context(_context_)[¶](#flask.Flask.update_template_context "Link to this definition")
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** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
_\[_[_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
_,_ [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_\]_) – the context as a dictionary that is updated in place to add extra variables.
Return type:
None
make\_shell\_context()[¶](#flask.Flask.make_shell_context "Link to this definition")
Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors.
Changelog
Added in version 0.11.
Return type:
[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
\]
run(_host\=None_, _port\=None_, _debug\=None_, _load\_dotenv\=True_, _\*\*options_)[¶](#flask.Flask.run "Link to this definition")
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 to Production](../deploying/)
for WSGI server recommendations.
If the [`debug`](#flask.Flask.debug "flask.Flask.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()`](#flask.Flask.run "flask.Flask.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** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – 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** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
_|_ _None_) – the port of the webserver. Defaults to `5000` or the port defined in the `SERVER_NAME` config variable if present.
* **debug** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
_|_ _None_) – if given, enable or disable debug mode. See [`debug`](#flask.Flask.debug "flask.Flask.debug")
.
* **load\_dotenv** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
) – 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** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
) – the options to be forwarded to the underlying Werkzeug server. See [`werkzeug.serving.run_simple()`](https://werkzeug.palletsprojects.com/en/stable/serving/#werkzeug.serving.run_simple "(in Werkzeug v3.1.x)")
for more information.
Return type:
None
Changelog
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`](#flask.Flask.debug "flask.Flask.debug")
.
Threaded mode is enabled by default.
Changed in version 0.10: The default port is now picked from the `SERVER_NAME` variable.
test\_client(_use\_cookies\=True_, _\*\*kwargs_)[¶](#flask.Flask.test_client "Link to this definition")
Creates a test client for this application. For information about unit testing head over to [Testing Flask Applications](../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`](#flask.Flask.testing "flask.Flask.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`](#flask.Flask.test_client_class "flask.Flask.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`](#flask.testing.FlaskClient "flask.testing.FlaskClient")
for more information.
Changelog
Changed in version 0.11: Added `**kwargs` to support passing additional keyword arguments to the constructor of [`test_client_class`](#flask.Flask.test_client_class "flask.Flask.test_client_class")
.
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`](#flask.Flask.test_client_class "flask.Flask.test_client_class")
attribute.
Changed in version 0.4: added support for `with` block usage for the client.
Parameters:
* **use\_cookies** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
)
* **kwargs** (_t.Any_)
Return type:
[FlaskClient](#flask.testing.FlaskClient "flask.testing.FlaskClient")
test\_cli\_runner(_\*\*kwargs_)[¶](#flask.Flask.test_cli_runner "Link to this definition")
Create a CLI runner for testing CLI commands. See [Running Commands with the CLI Runner](../testing/#testing-cli)
.
Returns an instance of [`test_cli_runner_class`](#flask.Flask.test_cli_runner_class "flask.Flask.test_cli_runner_class")
, by default [`FlaskCliRunner`](#flask.testing.FlaskCliRunner "flask.testing.FlaskCliRunner")
. The Flask app object is passed as the first argument.
Changelog
Added in version 1.0.
Parameters:
**kwargs** (_t.Any_)
Return type:
[FlaskCliRunner](#flask.testing.FlaskCliRunner "flask.testing.FlaskCliRunner")
handle\_http\_exception(_e_)[¶](#flask.Flask.handle_http_exception "Link to this definition")
Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.
Changelog
Changed in version 1.0.3: `RoutingException`, used internally for actions such as slash redirects during routing, is not passed to error handlers.
Changed in version 1.0: Exceptions are looked up by code _and_ by MRO, so `HTTPException` subclasses can be handled with a catch-all handler for the base `HTTPException`.
Added in version 0.3.
Parameters:
**e** (_HTTPException_)
Return type:
HTTPException | ft.ResponseReturnValue
handle\_user\_exception(_e_)[¶](#flask.Flask.handle_user_exception "Link to this definition")
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()`](#flask.Flask.handle_http_exception "flask.Flask.handle_http_exception")
method. This function will either return a response value or reraise the exception with the same traceback.
Changelog
Changed in version 1.0: Key errors raised from request data like `form` show the bad key in debug mode rather than a generic bad request message.
Added in version 0.7.
Parameters:
**e** ([_Exception_](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")
)
Return type:
HTTPException | ft.ResponseReturnValue
handle\_exception(_e_)[¶](#flask.Flask.handle_exception "Link to this definition")
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`](#flask.got_request_exception "flask.got_request_exception")
signal.
If [`PROPAGATE_EXCEPTIONS`](../config/#PROPAGATE_EXCEPTIONS "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`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.InternalServerError "(in Werkzeug v3.1.x)")
is returned.
If an error handler is registered for `InternalServerError` or `500`, it will be used. For consistency, the handler will always receive the `InternalServerError`. The original unhandled exception is available as `e.original_exception`.
Changelog
Changed in version 1.1.0: Always passes the `InternalServerError` instance to the handler, setting `original_exception` to the unhandled error.
Changed in version 1.1.0: `after_request` functions and other finalization is done even for the default 500 response when there is no handler.
Added in version 0.3.
Parameters:
**e** ([_Exception_](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")
)
Return type:
[_Response_](#flask.Response "flask.wrappers.Response")
log\_exception(_exc\_info_)[¶](#flask.Flask.log_exception "Link to this definition")
Logs an exception. This is called by [`handle_exception()`](#flask.Flask.handle_exception "flask.Flask.handle_exception")
if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the [`logger`](#flask.Flask.logger "flask.Flask.logger")
.
Changelog
Added in version 0.8.
Parameters:
**exc\_info** ([_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.13)")
_\[_[_type_](https://docs.python.org/3/library/functions.html#type "(in Python v3.13)")\
_,_ [_BaseException_](https://docs.python.org/3/library/exceptions.html#BaseException "(in Python v3.13)")\
_,_ [_TracebackType_](https://docs.python.org/3/library/types.html#types.TracebackType "(in Python v3.13)")\
_\]_ _|_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.13)")
_\[__None__,_ _None__,_ _None__\]_)
Return type:
None
dispatch\_request()[¶](#flask.Flask.dispatch_request "Link to this definition")
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()`](#flask.make_response "flask.make_response")
.
Changelog
Changed in version 0.7: This no longer does the exception handling, this code was moved to the new [`full_dispatch_request()`](#flask.Flask.full_dispatch_request "flask.Flask.full_dispatch_request")
.
Return type:
ft.ResponseReturnValue
full\_dispatch\_request()[¶](#flask.Flask.full_dispatch_request "Link to this definition")
Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling.
Changelog
Added in version 0.7.
Return type:
[_Response_](#flask.Response "flask.wrappers.Response")
make\_default\_options\_response()[¶](#flask.Flask.make_default_options_response "Link to this definition")
This method is called to create the default `OPTIONS` response. This can be changed through subclassing to change the default behavior of `OPTIONS` responses.
Changelog
Added in version 0.7.
Return type:
[_Response_](#flask.Response "flask.wrappers.Response")
ensure\_sync(_func_)[¶](#flask.Flask.ensure_sync "Link to this definition")
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.
Changelog
Added in version 2.0.
Parameters:
**func** ([_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
_\[__\[__...__\]__,_ [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_\]_)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[…\], [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
\]
async\_to\_sync(_func_)[¶](#flask.Flask.async_to_sync "Link to this definition")
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.
Changelog
Added in version 2.0.
Parameters:
**func** ([_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
_\[__\[__...__\]__,_ [_Coroutine_](https://docs.python.org/3/library/typing.html#typing.Coroutine "(in Python v3.13)")\
_\[_[_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_,_ [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_,_ [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_\]__\]_)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[…\], [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
\]
url\_for(_endpoint_, _\*_, _\_anchor\=None_, _\_method\=None_, _\_scheme\=None_, _\_external\=None_, _\*\*values_)[¶](#flask.Flask.url_for "Link to this definition")
Generate a URL to the given endpoint with the given values.
This is called by [`flask.url_for()`](#flask.url_for "flask.url_for")
, and can be called directly as well.
An _endpoint_ is the name of a URL rule, usually added with [`@app.route()`](#flask.Flask.route "flask.Flask.route")
, and usually the same name as the view function. A route defined in a [`Blueprint`](#flask.Blueprint "flask.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`](../config/#SERVER_NAME "SERVER_NAME")
so Flask knows what domain to use. [`APPLICATION_ROOT`](../config/#APPLICATION_ROOT "APPLICATION_ROOT")
and [`PREFERRED_URL_SCHEME`](../config/#PREFERRED_URL_SCHEME "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()`](#flask.Flask.url_defaults "flask.Flask.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()`](#flask.Flask.handle_url_build_error "flask.Flask.handle_url_build_error")
method is called. If that returns a string, that is returned, otherwise a `BuildError` is raised.
Parameters:
* **endpoint** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – The endpoint name associated with the URL to generate. If this starts with a `.`, the current blueprint name (if any) will be used.
* **\_anchor** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – If given, append this as `#anchor` to the URL.
* **\_method** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – If given, generate the URL associated with this method for the endpoint.
* **\_scheme** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – If given, the URL will have this scheme if it is external.
* **\_external** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
_|_ _None_) – 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** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
) – Values to use for the variable parts of the URL rule. Unknown keys are appended as query string arguments, like `?a=b&c=d`.
Return type:
[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
Changelog
Added in version 2.2: Moved from `flask.url_for`, which calls this method.
make\_response(_rv_)[¶](#flask.Flask.make_response "Link to this definition")
Convert the return value from a view function to an instance of [`response_class`](#flask.Flask.response_class "flask.Flask.response_class")
.
Parameters:
**rv** (_ft.ResponseReturnValue_) –
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`](#flask.Flask.response_class "flask.Flask.response_class")
instance, `status` overwrites the exiting value and `headers` are extended.
[`response_class`](#flask.Flask.response_class "flask.Flask.response_class")
The object is returned unchanged.
other [`Response`](https://werkzeug.palletsprojects.com/en/stable/wrappers/#werkzeug.wrappers.Response "(in Werkzeug v3.1.x)")
class
The object is coerced to [`response_class`](#flask.Flask.response_class "flask.Flask.response_class")
.
[`callable()`](https://docs.python.org/3/library/functions.html#callable "(in Python v3.13)")
The function is called as a WSGI application. The result is used to create a response object.
Return type:
[Response](#flask.Response "flask.Response")
Changelog
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.
preprocess\_request()[¶](#flask.Flask.preprocess_request "Link to this definition")
Called before the request is dispatched. Calls [`url_value_preprocessors`](#flask.Flask.url_value_preprocessors "flask.Flask.url_value_preprocessors")
registered with the app and the current blueprint (if any). Then calls [`before_request_funcs`](#flask.Flask.before_request_funcs "flask.Flask.before_request_funcs")
registered with the app and the blueprint.
If any [`before_request()`](#flask.Flask.before_request "flask.Flask.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.
Return type:
ft.ResponseReturnValue | None
process\_response(_response_)[¶](#flask.Flask.process_response "Link to this definition")
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()`](#flask.Flask.after_request "flask.Flask.after_request")
decorated functions.
Changelog
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** ([_Response_](#flask.Response "flask.wrappers.Response")
) – a [`response_class`](#flask.Flask.response_class "flask.Flask.response_class")
object.
Returns:
a new response object or the same, has to be an instance of [`response_class`](#flask.Flask.response_class "flask.Flask.response_class")
.
Return type:
[_Response_](#flask.Response "flask.wrappers.Response")
do\_teardown\_request(_exc\=\_sentinel_)[¶](#flask.Flask.do_teardown_request "Link to this definition")
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()`](#flask.Flask.teardown_request "flask.Flask.teardown_request")
, and [`Blueprint.teardown_request()`](#flask.Blueprint.teardown_request "flask.Blueprint.teardown_request")
if a blueprint handled the request. Finally, the [`request_tearing_down`](#flask.request_tearing_down "flask.request_tearing_down")
signal is sent.
This is called by [`RequestContext.pop()`](#flask.ctx.RequestContext.pop "flask.ctx.RequestContext.pop")
, which may be delayed during testing to maintain access to resources.
Parameters:
**exc** ([_BaseException_](https://docs.python.org/3/library/exceptions.html#BaseException "(in Python v3.13)")
_|_ _None_) – An unhandled exception raised while dispatching the request. Detected from the current exception information if not passed. Passed to each teardown function.
Return type:
None
Changelog
Changed in version 0.9: Added the `exc` argument.
do\_teardown\_appcontext(_exc\=\_sentinel_)[¶](#flask.Flask.do_teardown_appcontext "Link to this definition")
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()`](#flask.Flask.do_teardown_request "flask.Flask.do_teardown_request")
.
This calls all functions decorated with [`teardown_appcontext()`](#flask.Flask.teardown_appcontext "flask.Flask.teardown_appcontext")
. Then the [`appcontext_tearing_down`](#flask.appcontext_tearing_down "flask.appcontext_tearing_down")
signal is sent.
This is called by [`AppContext.pop()`](#flask.ctx.AppContext.pop "flask.ctx.AppContext.pop")
.
Changelog
Added in version 0.9.
Parameters:
**exc** ([_BaseException_](https://docs.python.org/3/library/exceptions.html#BaseException "(in Python v3.13)")
_|_ _None_)
Return type:
None
app\_context()[¶](#flask.Flask.app_context "Link to this definition")
Create an [`AppContext`](#flask.ctx.AppContext "flask.ctx.AppContext")
. Use as a `with` block to push the context, which will make [`current_app`](#flask.current_app "flask.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 [The Application Context](../appcontext/)
.
Changelog
Added in version 0.9.
Return type:
[_AppContext_](#flask.ctx.AppContext "flask.ctx.AppContext")
request\_context(_environ_)[¶](#flask.Flask.request_context "Link to this definition")
Create a [`RequestContext`](#flask.ctx.RequestContext "flask.ctx.RequestContext")
representing a WSGI environment. Use a `with` block to push the context, which will make [`request`](#flask.request "flask.request")
point at this request.
See [The Request Context](../reqcontext/)
.
Typically you should not call this from your own code. A request context is automatically pushed by the [`wsgi_app()`](#flask.Flask.wsgi_app "flask.Flask.wsgi_app")
when handling a request. Use [`test_request_context()`](#flask.Flask.test_request_context "flask.Flask.test_request_context")
to create an environment and context instead of this method.
Parameters:
**environ** (_WSGIEnvironment_) – a WSGI environment
Return type:
[RequestContext](#flask.ctx.RequestContext "flask.ctx.RequestContext")
test\_request\_context(_\*args_, _\*\*kwargs_)[¶](#flask.Flask.test_request_context "Link to this definition")
Create a [`RequestContext`](#flask.ctx.RequestContext "flask.ctx.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 [The Request Context](../reqcontext/)
.
Use a `with` block to push the context, which will make [`request`](#flask.request "flask.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`](https://werkzeug.palletsprojects.com/en/stable/test/#werkzeug.test.EnvironBuilder "(in Werkzeug v3.1.x)")
, 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`](../config/#PREFERRED_URL_SCHEME "PREFERRED_URL_SCHEME")
, `subdomain`, [`SERVER_NAME`](../config/#SERVER_NAME "SERVER_NAME")
, and [`APPLICATION_ROOT`](../config/#APPLICATION_ROOT "APPLICATION_ROOT")
.
* **subdomain** – Subdomain name to append to [`SERVER_NAME`](../config/#SERVER_NAME "SERVER_NAME")
.
* **url\_scheme** – Scheme to use instead of [`PREFERRED_URL_SCHEME`](../config/#PREFERRED_URL_SCHEME "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** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
) – other positional arguments passed to [`EnvironBuilder`](https://werkzeug.palletsprojects.com/en/stable/test/#werkzeug.test.EnvironBuilder "(in Werkzeug v3.1.x)")
.
* **kwargs** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
) – other keyword arguments passed to [`EnvironBuilder`](https://werkzeug.palletsprojects.com/en/stable/test/#werkzeug.test.EnvironBuilder "(in Werkzeug v3.1.x)")
.
Return type:
[_RequestContext_](#flask.ctx.RequestContext "flask.ctx.RequestContext")
wsgi\_app(_environ_, _start\_response_)[¶](#flask.Flask.wsgi_app "Link to this definition")
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.
Changelog
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](../reqcontext/#callbacks-and-errors)
.
Parameters:
* **environ** (_WSGIEnvironment_) – A WSGI environment.
* **start\_response** (_StartResponse_) – A callable accepting a status code, a list of headers, and an optional exception context to start the response.
Return type:
cabc.Iterable\[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.13)")\
\]
aborter\_class[¶](#flask.Flask.aborter_class "Link to this definition")
alias of [`Aborter`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.Aborter "(in Werkzeug v3.1.x)")
add\_template\_filter(_f_, _name\=None_)[¶](#flask.Flask.add_template_filter "Link to this definition")
Register a custom template filter. Works exactly like the [`template_filter()`](#flask.Flask.template_filter "flask.Flask.template_filter")
decorator.
Parameters:
* **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the filter, otherwise the function name will be used.
* **f** ([_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
_\[__\[__...__\]__,_ [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_\]_)
Return type:
None
add\_template\_global(_f_, _name\=None_)[¶](#flask.Flask.add_template_global "Link to this definition")
Register a custom template global function. Works exactly like the [`template_global()`](#flask.Flask.template_global "flask.Flask.template_global")
decorator.
Changelog
Added in version 0.10.
Parameters:
* **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the global function, otherwise the function name will be used.
* **f** ([_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
_\[__\[__...__\]__,_ [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_\]_)
Return type:
None
add\_template\_test(_f_, _name\=None_)[¶](#flask.Flask.add_template_test "Link to this definition")
Register a custom template test. Works exactly like the [`template_test()`](#flask.Flask.template_test "flask.Flask.template_test")
decorator.
Changelog
Added in version 0.10.
Parameters:
* **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the test, otherwise the function name will be used.
* **f** ([_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
_\[__\[__...__\]__,_ [_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")\
_\]_)
Return type:
None
add\_url\_rule(_rule_, _endpoint\=None_, _view\_func\=None_, _provide\_automatic\_options\=None_, _\*\*options_)[¶](#flask.Flask.add_url_rule "Link to this definition")
Register a rule for routing incoming requests and building URLs. The [`route()`](#flask.Flask.route "flask.Flask.route")
decorator is a shortcut to call this with the `view_func` argument. These are equivalent:
@app.route("/")
def index():
...
def index():
...
app.add\_url\_rule("/", view\_func\=index)
See [URL Route Registrations](#url-route-registrations)
.
The endpoint name for the route defaults to the name of the view function if the `endpoint` parameter isn’t passed. An error will be raised if a function has already been registered for the endpoint.
The `methods` parameter defaults to `["GET"]`. `HEAD` is always added automatically, and `OPTIONS` is added automatically by default.
`view_func` does not necessarily need to be passed, but if the rule should participate in routing an endpoint name must be associated with a view function at some point with the [`endpoint()`](#flask.Flask.endpoint "flask.Flask.endpoint")
decorator.
app.add\_url\_rule("/", endpoint\="index")
@app.endpoint("index")
def index():
...
If `view_func` has a `required_methods` attribute, those methods are added to the passed and automatic methods. If it has a `provide_automatic_methods` attribute, it is used as the default if the parameter is not passed.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – The URL rule string.
* **endpoint** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – The endpoint name to associate with the rule and view function. Used when routing and building URLs. Defaults to `view_func.__name__`.
* **view\_func** (_ft.RouteCallable_ _|_ _None_) – The view function to associate with the endpoint name.
* **provide\_automatic\_options** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
_|_ _None_) – Add the `OPTIONS` method and respond to `OPTIONS` requests automatically.
* **options** (_t.Any_) – Extra options passed to the [`Rule`](https://werkzeug.palletsprojects.com/en/stable/routing/#werkzeug.routing.Rule "(in Werkzeug v3.1.x)")
object.
Return type:
None
after\_request(_f_)[¶](#flask.Flask.after_request "Link to this definition")
Register a function to run after each request to this object.
The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent.
If a function raises an exception, any remaining `after_request` functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use [`teardown_request()`](#flask.Flask.teardown_request "flask.Flask.teardown_request")
for that.
This is available on both app and blueprint objects. When used on an app, this executes after every request. When used on a blueprint, this executes after every request that the blueprint handles. To register with a blueprint and execute after every request, use [`Blueprint.after_app_request()`](#flask.Blueprint.after_app_request "flask.Blueprint.after_app_request")
.
Parameters:
**f** (_T\_after\_request_)
Return type:
_T\_after\_request_
app\_ctx\_globals\_class[¶](#flask.Flask.app_ctx_globals_class "Link to this definition")
alias of [`_AppCtxGlobals`](#flask.ctx._AppCtxGlobals "flask.ctx._AppCtxGlobals")
auto\_find\_instance\_path()[¶](#flask.Flask.auto_find_instance_path "Link to this definition")
Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named `instance` next to your main file or the package.
Changelog
Added in version 0.8.
Return type:
[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
before\_request(_f_)[¶](#flask.Flask.before_request "Link to this definition")
Register a function to run before each request.
For example, this can be used to open a database connection, or to load the logged in user from the session.
@app.before\_request
def load\_user():
if "user\_id" in session:
g.user \= db.session.get(session\["user\_id"\])
The function will be called without any arguments. If it returns a non-`None` value, the value is handled as if it was the return value from the view, and further request handling is stopped.
This is available on both app and blueprint objects. When used on an app, this executes before every request. When used on a blueprint, this executes before every request that the blueprint handles. To register with a blueprint and execute before every request, use [`Blueprint.before_app_request()`](#flask.Blueprint.before_app_request "flask.Blueprint.before_app_request")
.
Parameters:
**f** (_T\_before\_request_)
Return type:
_T\_before\_request_
config\_class[¶](#flask.Flask.config_class "Link to this definition")
alias of [`Config`](#flask.Config "flask.config.Config")
context\_processor(_f_)[¶](#flask.Flask.context_processor "Link to this definition")
Registers a template context processor function. These functions run before rendering a template. The keys of the returned dict are added as variables available in the template.
This is available on both app and blueprint objects. When used on an app, this is called for every rendered template. When used on a blueprint, this is called for templates rendered from the blueprint’s views. To register with a blueprint and affect every template, use [`Blueprint.app_context_processor()`](#flask.Blueprint.app_context_processor "flask.Blueprint.app_context_processor")
.
Parameters:
**f** (_T\_template\_context\_processor_)
Return type:
_T\_template\_context\_processor_
create\_global\_jinja\_loader()[¶](#flask.Flask.create_global_jinja_loader "Link to this definition")
Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It’s discouraged to override this function. Instead one should override the [`jinja_loader()`](#flask.Flask.jinja_loader "flask.Flask.jinja_loader")
function instead.
The global loader dispatches between the loaders of the application and the individual blueprints.
Changelog
Added in version 0.7.
Return type:
_DispatchingJinjaLoader_
_property_ debug_: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
_[¶](#flask.Flask.debug "Link to this definition")
Whether debug mode is enabled. When using `flask run` to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. This maps to the [`DEBUG`](../config/#DEBUG "DEBUG")
config key. It may not behave as expected if set late.
**Do not enable debug mode when deploying in production.**
Default: `False`
delete(_rule_, _\*\*options_)[¶](#flask.Flask.delete "Link to this definition")
Shortcut for [`route()`](#flask.Flask.route "flask.Flask.route")
with `methods=["DELETE"]`.
Changelog
Added in version 2.0.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
endpoint(_endpoint_)[¶](#flask.Flask.endpoint "Link to this definition")
Decorate a view function to register it for the given endpoint. Used if a rule is added without a `view_func` with [`add_url_rule()`](#flask.Flask.add_url_rule "flask.Flask.add_url_rule")
.
app.add\_url\_rule("/ex", endpoint\="example")
@app.endpoint("example")
def example():
...
Parameters:
**endpoint** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – The endpoint name to associate with the view function.
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_F_\], _F_\]
errorhandler(_code\_or\_exception_)[¶](#flask.Flask.errorhandler "Link to this definition")
Register a function to handle errors by code or exception class.
A decorator that is used to register a function given an error code. Example:
@app.errorhandler(404)
def page\_not\_found(error):
return 'This page does not exist', 404
You can also register handlers for arbitrary exceptions:
@app.errorhandler(DatabaseError)
def special\_exception\_handler(error):
return 'Database connection failed', 500
This is available on both app and blueprint objects. When used on an app, this can handle errors from every request. When used on a blueprint, this can handle errors from requests that the blueprint handles. To register with a blueprint and affect every request, use [`Blueprint.app_errorhandler()`](#flask.Blueprint.app_errorhandler "flask.Blueprint.app_errorhandler")
.
Changelog
Added in version 0.7: Use [`register_error_handler()`](#flask.Flask.register_error_handler "flask.Flask.register_error_handler")
instead of modifying [`error_handler_spec`](#flask.Flask.error_handler_spec "flask.Flask.error_handler_spec")
directly, for application wide error handlers.
Added in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the [`HTTPException`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.HTTPException "(in Werkzeug v3.1.x)")
class.
Parameters:
**code\_or\_exception** ([_type_](https://docs.python.org/3/library/functions.html#type "(in Python v3.13)")
_\[_[_Exception_](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")\
_\]_ _|_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
) – the code as integer for the handler, or an arbitrary exception
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_error\_handler_\], _T\_error\_handler_\]
get(_rule_, _\*\*options_)[¶](#flask.Flask.get "Link to this definition")
Shortcut for [`route()`](#flask.Flask.route "flask.Flask.route")
with `methods=["GET"]`.
Changelog
Added in version 2.0.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
handle\_url\_build\_error(_error_, _endpoint_, _values_)[¶](#flask.Flask.handle_url_build_error "Link to this definition")
Called by [`url_for()`](#flask.Flask.url_for "flask.Flask.url_for")
if a `BuildError` was raised. If this returns a value, it will be returned by `url_for`, otherwise the error will be re-raised.
Each function in [`url_build_error_handlers`](#flask.Flask.url_build_error_handlers "flask.Flask.url_build_error_handlers")
is called with `error`, `endpoint` and `values`. If a function returns `None` or raises a `BuildError`, it is skipped. Otherwise, its return value is returned by `url_for`.
Parameters:
* **error** (_BuildError_) – The active `BuildError` being handled.
* **endpoint** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – The endpoint being built.
* **values** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
_\[_[_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
_,_ [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_\]_) – The keyword arguments passed to `url_for`.
Return type:
[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_property_ has\_static\_folder_: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
_[¶](#flask.Flask.has_static_folder "Link to this definition")
`True` if [`static_folder`](#flask.Flask.static_folder "flask.Flask.static_folder")
is set.
Changelog
Added in version 0.5.
inject\_url\_defaults(_endpoint_, _values_)[¶](#flask.Flask.inject_url_defaults "Link to this definition")
Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building.
Changelog
Added in version 0.7.
Parameters:
* **endpoint** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **values** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
_\[_[_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
_,_ [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_\]_)
Return type:
None
iter\_blueprints()[¶](#flask.Flask.iter_blueprints "Link to this definition")
Iterates over all blueprints by the order they were registered.
Changelog
Added in version 0.11.
Return type:
t.ValuesView\[[Blueprint](#flask.Blueprint "flask.Blueprint")\
\]
_property_ jinja\_env_: Environment_[¶](#flask.Flask.jinja_env "Link to this definition")
The Jinja environment used to load templates.
The environment is created the first time this property is accessed. Changing [`jinja_options`](#flask.Flask.jinja_options "flask.Flask.jinja_options")
after that will have no effect.
jinja\_environment[¶](#flask.Flask.jinja_environment "Link to this definition")
alias of `Environment`
_property_ jinja\_loader_: [BaseLoader](https://jinja.palletsprojects.com/en/stable/api/#jinja2.BaseLoader "(in Jinja v3.1.x)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Flask.jinja_loader "Link to this definition")
The Jinja loader for this object’s templates. By default this is a class [`jinja2.loaders.FileSystemLoader`](https://jinja.palletsprojects.com/en/stable/api/#jinja2.FileSystemLoader "(in Jinja v3.1.x)")
to [`template_folder`](#flask.Flask.template_folder "flask.Flask.template_folder")
if it is set.
Changelog
Added in version 0.5.
jinja\_options_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, t.Any\]_ _\= {}_[¶](#flask.Flask.jinja_options "Link to this definition")
Options that are passed to the Jinja environment in [`create_jinja_environment()`](#flask.Flask.create_jinja_environment "flask.Flask.create_jinja_environment")
. Changing these options after the environment is created (accessing [`jinja_env`](#flask.Flask.jinja_env "flask.Flask.jinja_env")
) will have no effect.
Changelog
Changed in version 1.1.0: This is a `dict` instead of an `ImmutableDict` to allow easier configuration.
json\_provider\_class[¶](#flask.Flask.json_provider_class "Link to this definition")
alias of [`DefaultJSONProvider`](#flask.json.provider.DefaultJSONProvider "flask.json.provider.DefaultJSONProvider")
_property_ logger_: [Logger](https://docs.python.org/3/library/logging.html#logging.Logger "(in Python v3.13)")
_[¶](#flask.Flask.logger "Link to this definition")
A standard Python [`Logger`](https://docs.python.org/3/library/logging.html#logging.Logger "(in Python v3.13)")
for the app, with the same name as [`name`](#flask.Flask.name "flask.Flask.name")
.
In debug mode, the logger’s [`level`](https://docs.python.org/3/library/logging.html#logging.Logger.level "(in Python v3.13)")
will be set to [`DEBUG`](https://docs.python.org/3/library/logging.html#logging.DEBUG "(in Python v3.13)")
.
If there are no handlers configured, a default handler will be added. See [Logging](../logging/)
for more information.
Changelog
Changed in version 1.1.0: The logger takes the same name as [`name`](#flask.Flask.name "flask.Flask.name")
rather than hard-coding `"flask.app"`.
Changed in version 1.0.0: Behavior was simplified. The logger is always named `"flask.app"`. The level is only set during configuration, it doesn’t check `app.debug` each time. Only one format is used, not different ones depending on `app.debug`. No handlers are removed, and a handler is only added if no handlers are already configured.
Added in version 0.3.
make\_aborter()[¶](#flask.Flask.make_aborter "Link to this definition")
Create the object to assign to [`aborter`](#flask.Flask.aborter "flask.Flask.aborter")
. That object is called by [`flask.abort()`](#flask.abort "flask.abort")
to raise HTTP errors, and can be called directly as well.
By default, this creates an instance of [`aborter_class`](#flask.Flask.aborter_class "flask.Flask.aborter_class")
, which defaults to [`werkzeug.exceptions.Aborter`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.Aborter "(in Werkzeug v3.1.x)")
.
Changelog
Added in version 2.2.
Return type:
[_Aborter_](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.Aborter "(in Werkzeug v3.1.x)")
make\_config(_instance\_relative\=False_)[¶](#flask.Flask.make_config "Link to this definition")
Used to create the config attribute by the Flask constructor. The `instance_relative` parameter is passed in from the constructor of Flask (there named `instance_relative_config`) and indicates if the config should be relative to the instance path or the root path of the application.
Changelog
Added in version 0.8.
Parameters:
**instance\_relative** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
)
Return type:
[_Config_](#flask.Config "flask.config.Config")
_property_ name_: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_[¶](#flask.Flask.name "Link to this definition")
The name of the application. This is usually the import name with the difference that it’s guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value.
Changelog
Added in version 0.8.
patch(_rule_, _\*\*options_)[¶](#flask.Flask.patch "Link to this definition")
Shortcut for [`route()`](#flask.Flask.route "flask.Flask.route")
with `methods=["PATCH"]`.
Changelog
Added in version 2.0.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
permanent\_session\_lifetime[¶](#flask.Flask.permanent_session_lifetime "Link to this definition")
A [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.13)")
which is used to set the expiration date of a permanent session. The default is 31 days which makes a permanent session survive for roughly one month.
This attribute can also be configured from the config with the `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to `timedelta(days=31)`
post(_rule_, _\*\*options_)[¶](#flask.Flask.post "Link to this definition")
Shortcut for [`route()`](#flask.Flask.route "flask.Flask.route")
with `methods=["POST"]`.
Changelog
Added in version 2.0.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
put(_rule_, _\*\*options_)[¶](#flask.Flask.put "Link to this definition")
Shortcut for [`route()`](#flask.Flask.route "flask.Flask.route")
with `methods=["PUT"]`.
Changelog
Added in version 2.0.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
redirect(_location_, _code\=302_)[¶](#flask.Flask.redirect "Link to this definition")
Create a redirect response object.
This is called by [`flask.redirect()`](#flask.redirect "flask.redirect")
, and can be called directly as well.
Parameters:
* **location** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – The URL to redirect to.
* **code** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
) – The status code for the redirect.
Return type:
BaseResponse
Changelog
Added in version 2.2: Moved from `flask.redirect`, which calls this method.
register\_blueprint(_blueprint_, _\*\*options_)[¶](#flask.Flask.register_blueprint "Link to this definition")
Register a [`Blueprint`](#flask.Blueprint "flask.Blueprint")
on the application. Keyword arguments passed to this method will override the defaults set on the blueprint.
Calls the blueprint’s [`register()`](#flask.Blueprint.register "flask.Blueprint.register")
method after recording the blueprint in the application’s [`blueprints`](#flask.Flask.blueprints "flask.Flask.blueprints")
.
Parameters:
* **blueprint** ([_Blueprint_](#flask.Blueprint "flask.Blueprint")
) – The blueprint to register.
* **url\_prefix** – Blueprint routes will be prefixed with this.
* **subdomain** – Blueprint routes will match on this subdomain.
* **url\_defaults** – Blueprint routes will use these default values for view arguments.
* **options** (_t.Any_) – Additional keyword arguments are passed to [`BlueprintSetupState`](#flask.blueprints.BlueprintSetupState "flask.blueprints.BlueprintSetupState")
. They can be accessed in [`record()`](#flask.Blueprint.record "flask.Blueprint.record")
callbacks.
Return type:
None
Changelog
Changed in version 2.0.1: The `name` option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for `url_for`.
Added in version 0.7.
register\_error\_handler(_code\_or\_exception_, _f_)[¶](#flask.Flask.register_error_handler "Link to this definition")
Alternative error attach function to the [`errorhandler()`](#flask.Flask.errorhandler "flask.Flask.errorhandler")
decorator that is more straightforward to use for non decorator usage.
Changelog
Added in version 0.7.
Parameters:
* **code\_or\_exception** ([_type_](https://docs.python.org/3/library/functions.html#type "(in Python v3.13)")
_\[_[_Exception_](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")\
_\]_ _|_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
)
* **f** (_ft.ErrorHandlerCallable_)
Return type:
None
route(_rule_, _\*\*options_)[¶](#flask.Flask.route "Link to this definition")
Decorate a view function to register it with the given URL rule and options. Calls [`add_url_rule()`](#flask.Flask.add_url_rule "flask.Flask.add_url_rule")
, which has more details about the implementation.
@app.route("/")
def index():
return "Hello, World!"
See [URL Route Registrations](#url-route-registrations)
.
The endpoint name for the route defaults to the name of the view function if the `endpoint` parameter isn’t passed.
The `methods` parameter defaults to `["GET"]`. `HEAD` and `OPTIONS` are added automatically.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – The URL rule string.
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
) – Extra options passed to the [`Rule`](https://werkzeug.palletsprojects.com/en/stable/routing/#werkzeug.routing.Rule "(in Werkzeug v3.1.x)")
object.
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
secret\_key[¶](#flask.Flask.secret_key "Link to this definition")
If a secret key is set, cryptographic components can use this to sign cookies and other things. Set this to a complex random value when you want to use the secure cookie for instance.
This attribute can also be configured from the config with the [`SECRET_KEY`](../config/#SECRET_KEY "SECRET_KEY")
configuration key. Defaults to `None`.
select\_jinja\_autoescape(_filename_)[¶](#flask.Flask.select_jinja_autoescape "Link to this definition")
Returns `True` if autoescaping should be active for the given template name. If no template name is given, returns `True`.
Changelog
Changed in version 2.2: Autoescaping is now enabled by default for `.svg` files.
Added in version 0.5.
Parameters:
**filename** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
Return type:
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
shell\_context\_processor(_f_)[¶](#flask.Flask.shell_context_processor "Link to this definition")
Registers a shell context processor function.
Changelog
Added in version 0.11.
Parameters:
**f** (_T\_shell\_context\_processor_)
Return type:
_T\_shell\_context\_processor_
should\_ignore\_error(_error_)[¶](#flask.Flask.should_ignore_error "Link to this definition")
This is called to figure out if an error should be ignored or not as far as the teardown system is concerned. If this function returns `True` then the teardown handlers will not be passed the error.
Changelog
Added in version 0.10.
Parameters:
**error** ([_BaseException_](https://docs.python.org/3/library/exceptions.html#BaseException "(in Python v3.13)")
_|_ _None_)
Return type:
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
_property_ static\_folder_: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Flask.static_folder "Link to this definition")
The absolute path to the configured static folder. `None` if no static folder is set.
_property_ static\_url\_path_: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Flask.static_url_path "Link to this definition")
The URL prefix that the static route will be accessible from.
If it was not configured during init, it is derived from [`static_folder`](#flask.Flask.static_folder "flask.Flask.static_folder")
.
teardown\_appcontext(_f_)[¶](#flask.Flask.teardown_appcontext "Link to this definition")
Registers a function to be called when the application context is popped. The application context is typically popped after the request context for each request, at the end of CLI commands, or after a manually pushed context ends.
with app.app\_context():
...
When the `with` block exits (or `ctx.pop()` is called), the teardown functions are called just before the app context is made inactive. Since a request context typically also manages an application context it would also be called when you pop a request context.
When a teardown function was called because of an unhandled exception it will be passed an error object. If an [`errorhandler()`](#flask.Flask.errorhandler "flask.Flask.errorhandler")
is registered, it will handle the exception and the teardown will not receive it.
Teardown functions must avoid raising exceptions. If they execute code that might fail they must surround that code with a `try`/`except` block and log any errors.
The return values of teardown functions are ignored.
Changelog
Added in version 0.9.
Parameters:
**f** (_T\_teardown_)
Return type:
_T\_teardown_
teardown\_request(_f_)[¶](#flask.Flask.teardown_request "Link to this definition")
Register a function to be called when the request context is popped. Typically this happens at the end of each request, but contexts may be pushed manually as well during testing.
with app.test\_request\_context():
...
When the `with` block exits (or `ctx.pop()` is called), the teardown functions are called just before the request context is made inactive.
When a teardown function was called because of an unhandled exception it will be passed an error object. If an [`errorhandler()`](#flask.Flask.errorhandler "flask.Flask.errorhandler")
is registered, it will handle the exception and the teardown will not receive it.
Teardown functions must avoid raising exceptions. If they execute code that might fail they must surround that code with a `try`/`except` block and log any errors.
The return values of teardown functions are ignored.
This is available on both app and blueprint objects. When used on an app, this executes after every request. When used on a blueprint, this executes after every request that the blueprint handles. To register with a blueprint and execute after every request, use [`Blueprint.teardown_app_request()`](#flask.Blueprint.teardown_app_request "flask.Blueprint.teardown_app_request")
.
Parameters:
**f** (_T\_teardown_)
Return type:
_T\_teardown_
template\_filter(_name\=None_)[¶](#flask.Flask.template_filter "Link to this definition")
A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:
@app.template\_filter()
def reverse(s):
return s\[::\-1\]
Parameters:
**name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the filter, otherwise the function name will be used.
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_template\_filter_\], _T\_template\_filter_\]
template\_global(_name\=None_)[¶](#flask.Flask.template_global "Link to this definition")
A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:
@app.template\_global()
def double(n):
return 2 \* n
Changelog
Added in version 0.10.
Parameters:
**name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the global function, otherwise the function name will be used.
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_template\_global_\], _T\_template\_global_\]
template\_test(_name\=None_)[¶](#flask.Flask.template_test "Link to this definition")
A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example:
@app.template\_test()
def is\_prime(n):
if n \== 2:
return True
for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
if n % i \== 0:
return False
return True
Changelog
Added in version 0.10.
Parameters:
**name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the test, otherwise the function name will be used.
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_template\_test_\], _T\_template\_test_\]
test\_cli\_runner\_class_: [type](https://docs.python.org/3/library/functions.html#type "(in Python v3.13)")
\[[FlaskCliRunner](#flask.testing.FlaskCliRunner "flask.testing.FlaskCliRunner")\
\] | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_ _\= None_[¶](#flask.Flask.test_cli_runner_class "Link to this definition")
The [`CliRunner`](https://click.palletsprojects.com/en/stable/api/#click.testing.CliRunner "(in Click v8.1.x)")
subclass, by default [`FlaskCliRunner`](#flask.testing.FlaskCliRunner "flask.testing.FlaskCliRunner")
that is used by [`test_cli_runner()`](#flask.Flask.test_cli_runner "flask.Flask.test_cli_runner")
. Its `__init__` method should take a Flask app object as the first argument.
Changelog
Added in version 1.0.
test\_client\_class_: [type](https://docs.python.org/3/library/functions.html#type "(in Python v3.13)")
\[[FlaskClient](#flask.testing.FlaskClient "flask.testing.FlaskClient")\
\] | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_ _\= None_[¶](#flask.Flask.test_client_class "Link to this definition")
The [`test_client()`](#flask.Flask.test_client "flask.Flask.test_client")
method creates an instance of this test client class. Defaults to [`FlaskClient`](#flask.testing.FlaskClient "flask.testing.FlaskClient")
.
Changelog
Added in version 0.7.
testing[¶](#flask.Flask.testing "Link to this definition")
The testing flag. Set this to `True` to enable the test mode of Flask extensions (and in the future probably also Flask itself). For example this might activate test helpers that have an additional runtime cost which should not be enabled by default.
If this is enabled and PROPAGATE\_EXCEPTIONS is not changed from the default it’s implicitly enabled.
This attribute can also be configured from the config with the `TESTING` configuration key. Defaults to `False`.
trap\_http\_exception(_e_)[¶](#flask.Flask.trap_http_exception "Link to this definition")
Checks if an HTTP exception should be trapped or not. By default this will return `False` for all exceptions except for a bad request key error if `TRAP_BAD_REQUEST_ERRORS` is set to `True`. It also returns `True` if `TRAP_HTTP_EXCEPTIONS` is set to `True`.
This is called for all HTTP exceptions raised by a view function. If it returns `True` for any exception the error handler for this exception is not called and it shows up as regular exception in the traceback. This is helpful for debugging implicitly raised HTTP exceptions.
Changelog
Changed in version 1.0: Bad request errors are not trapped by default in debug mode.
Added in version 0.8.
Parameters:
**e** ([_Exception_](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")
)
Return type:
[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
url\_defaults(_f_)[¶](#flask.Flask.url_defaults "Link to this definition")
Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place.
This is available on both app and blueprint objects. When used on an app, this is called for every request. When used on a blueprint, this is called for requests that the blueprint handles. To register with a blueprint and affect every request, use [`Blueprint.app_url_defaults()`](#flask.Blueprint.app_url_defaults "flask.Blueprint.app_url_defaults")
.
Parameters:
**f** (_T\_url\_defaults_)
Return type:
_T\_url\_defaults_
url\_map\_class[¶](#flask.Flask.url_map_class "Link to this definition")
alias of [`Map`](https://werkzeug.palletsprojects.com/en/stable/routing/#werkzeug.routing.Map "(in Werkzeug v3.1.x)")
url\_rule\_class[¶](#flask.Flask.url_rule_class "Link to this definition")
alias of [`Rule`](https://werkzeug.palletsprojects.com/en/stable/routing/#werkzeug.routing.Rule "(in Werkzeug v3.1.x)")
url\_value\_preprocessor(_f_)[¶](#flask.Flask.url_value_preprocessor "Link to this definition")
Register a URL value preprocessor function for all view functions in the application. These functions will be called before the [`before_request()`](#flask.Flask.before_request "flask.Flask.before_request")
functions.
The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in `g` rather than pass it to every view.
The function is passed the endpoint name and values dict. The return value is ignored.
This is available on both app and blueprint objects. When used on an app, this is called for every request. When used on a blueprint, this is called for requests that the blueprint handles. To register with a blueprint and affect every request, use [`Blueprint.app_url_value_preprocessor()`](#flask.Blueprint.app_url_value_preprocessor "flask.Blueprint.app_url_value_preprocessor")
.
Parameters:
**f** (_T\_url\_value\_preprocessor_)
Return type:
_T\_url\_value\_preprocessor_
instance\_path[¶](#flask.Flask.instance_path "Link to this definition")
Holds the path to the instance folder.
Changelog
Added in version 0.8.
config[¶](#flask.Flask.config "Link to this definition")
The configuration dictionary as [`Config`](#flask.Config "flask.Config")
. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.
aborter[¶](#flask.Flask.aborter "Link to this definition")
An instance of [`aborter_class`](#flask.Flask.aborter_class "flask.Flask.aborter_class")
created by [`make_aborter()`](#flask.Flask.make_aborter "flask.Flask.make_aborter")
. This is called by [`flask.abort()`](#flask.abort "flask.abort")
to raise HTTP errors, and can be called directly as well.
Changelog
Added in version 2.2: Moved from `flask.abort`, which calls this object.
json_: [JSONProvider](#flask.json.provider.JSONProvider "flask.json.provider.JSONProvider")
_[¶](#flask.Flask.json "Link to this definition")
Provides access to JSON methods. Functions in `flask.json` will call methods on this provider when the application context is active. Used for handling JSON requests and responses.
An instance of [`json_provider_class`](#flask.Flask.json_provider_class "flask.Flask.json_provider_class")
. Can be customized by changing that attribute on a subclass, or by assigning to this attribute afterwards.
The default, [`DefaultJSONProvider`](#flask.json.provider.DefaultJSONProvider "flask.json.provider.DefaultJSONProvider")
, uses Python’s built-in [`json`](https://docs.python.org/3/library/json.html#module-json "(in Python v3.13)")
library. A different provider can use a different JSON library.
Changelog
Added in version 2.2.
url\_build\_error\_handlers_: [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")
\[t.Callable\[\[[Exception](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")\
, [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")\
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, t.Any\]\], [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
\]\]_[¶](#flask.Flask.url_build_error_handlers "Link to this definition")
A list of functions that are called by [`handle_url_build_error()`](#flask.Flask.handle_url_build_error "flask.Flask.handle_url_build_error")
when [`url_for()`](#flask.Flask.url_for "flask.Flask.url_for")
raises a `BuildError`. Each function is called with `error`, `endpoint` and `values`. If a function returns `None` or raises a `BuildError`, it is skipped. Otherwise, its return value is returned by `url_for`.
Changelog
Added in version 0.9.
teardown\_appcontext\_funcs_: [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")
\[ft.TeardownCallable\]_[¶](#flask.Flask.teardown_appcontext_funcs "Link to this definition")
A list of functions that are called when the application context is destroyed. Since the application context is also torn down if the request ends this is the place to store code that disconnects from databases.
Changelog
Added in version 0.9.
shell\_context\_processors_: [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")
\[ft.ShellContextProcessorCallable\]_[¶](#flask.Flask.shell_context_processors "Link to this definition")
A list of shell context processor functions that should be run when a shell context is created.
Changelog
Added in version 0.11.
blueprints_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, [Blueprint](#flask.Blueprint "flask.Blueprint")\
\]_[¶](#flask.Flask.blueprints "Link to this definition")
Maps registered blueprint names to blueprint objects. The dict retains the order the blueprints were registered in. Blueprints can be registered multiple times, this dict does not track how often they were attached.
Changelog
Added in version 0.7.
extensions_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, t.Any\]_[¶](#flask.Flask.extensions "Link to this definition")
a place where extensions can store application specific state. For example this is where an extension could store database engines and similar things.
The key must match the name of the extension module. For example in case of a “Flask-Foo” extension in `flask_foo`, the key would be `'foo'`.
Changelog
Added in version 0.7.
url\_map[¶](#flask.Flask.url_map "Link to this definition")
The [`Map`](https://werkzeug.palletsprojects.com/en/stable/routing/#werkzeug.routing.Map "(in Werkzeug v3.1.x)")
for this instance. You can use this to change the routing converters after the class was created but before any routes are connected. Example:
from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter):
def to\_python(self, value):
return value.split(',')
def to\_url(self, values):
return ','.join(super(ListConverter, self).to\_url(value)
for value in values)
app \= Flask(\_\_name\_\_)
app.url\_map.converters\['list'\] \= ListConverter
import\_name[¶](#flask.Flask.import_name "Link to this definition")
The name of the package or module that this object belongs to. Do not change this once it is set by the constructor.
template\_folder[¶](#flask.Flask.template_folder "Link to this definition")
The path to the templates folder, relative to [`root_path`](#flask.Flask.root_path "flask.Flask.root_path")
, to add to the template loader. `None` if templates should not be added.
root\_path[¶](#flask.Flask.root_path "Link to this definition")
Absolute path to the package on the filesystem. Used to look up resources contained in the package.
view\_functions_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, ft.RouteCallable\]_[¶](#flask.Flask.view_functions "Link to this definition")
A dictionary mapping endpoint names to view functions.
To register a view function, use the [`route()`](#flask.Flask.route "flask.Flask.route")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
error\_handler\_spec_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")\
\[[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")\
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")\
, [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")\
\[[type](https://docs.python.org/3/library/functions.html#type "(in Python v3.13)")\
\[[Exception](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")\
\], ft.ErrorHandlerCallable\]\]\]_[¶](#flask.Flask.error_handler_spec "Link to this definition")
A data structure of registered error handlers, in the format `{scope: {code: {class: handler}}}`. The `scope` key is the name of a blueprint the handlers are active for, or `None` for all requests. The `code` key is the HTTP status code for `HTTPException`, or `None` for other exceptions. The innermost dictionary maps exception classes to handler functions.
To register an error handler, use the [`errorhandler()`](#flask.Flask.errorhandler "flask.Flask.errorhandler")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
before\_request\_funcs_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.BeforeRequestCallable\]\]_[¶](#flask.Flask.before_request_funcs "Link to this definition")
A data structure of functions to call at the beginning of each request, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`before_request()`](#flask.Flask.before_request "flask.Flask.before_request")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
after\_request\_funcs_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.AfterRequestCallable\[t.Any\]\]\]_[¶](#flask.Flask.after_request_funcs "Link to this definition")
A data structure of functions to call at the end of each request, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`after_request()`](#flask.Flask.after_request "flask.Flask.after_request")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
teardown\_request\_funcs_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.TeardownCallable\]\]_[¶](#flask.Flask.teardown_request_funcs "Link to this definition")
A data structure of functions to call at the end of each request even if an exception is raised, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`teardown_request()`](#flask.Flask.teardown_request "flask.Flask.teardown_request")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
template\_context\_processors_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.TemplateContextProcessorCallable\]\]_[¶](#flask.Flask.template_context_processors "Link to this definition")
A data structure of functions to call to pass extra context values when rendering templates, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`context_processor()`](#flask.Flask.context_processor "flask.Flask.context_processor")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
url\_value\_preprocessors_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.URLValuePreprocessorCallable\]\]_[¶](#flask.Flask.url_value_preprocessors "Link to this definition")
A data structure of functions to call to modify the keyword arguments passed to the view function, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`url_value_preprocessor()`](#flask.Flask.url_value_preprocessor "flask.Flask.url_value_preprocessor")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
url\_default\_functions_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.URLDefaultCallable\]\]_[¶](#flask.Flask.url_default_functions "Link to this definition")
A data structure of functions to call to modify the keyword arguments when generating URLs, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`url_defaults()`](#flask.Flask.url_defaults "flask.Flask.url_defaults")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
Blueprint Objects[¶](#blueprint-objects "Link to this heading")
----------------------------------------------------------------
_class_ flask.Blueprint(_name_, _import\_name_, _static\_folder\=None_, _static\_url\_path\=None_, _template\_folder\=None_, _url\_prefix\=None_, _subdomain\=None_, _url\_defaults\=None_, _root\_path\=None_, _cli\_group\=\_sentinel_)[¶](#flask.Blueprint "Link to this definition")
Parameters:
* **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **import\_name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **static\_folder** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ [_os.PathLike_](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.13)")
_\[_[_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
_\]_ _|_ _None_)
* **static\_url\_path** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_)
* **template\_folder** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ [_os.PathLike_](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.13)")
_\[_[_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
_\]_ _|_ _None_)
* **url\_prefix** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_)
* **subdomain** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_)
* **url\_defaults** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
_\[_[_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
_,_ _t.Any__\]_ _|_ _None_)
* **root\_path** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_)
* **cli\_group** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_)
cli_: Group_[¶](#flask.Blueprint.cli "Link to this definition")
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_)[¶](#flask.Blueprint.get_send_file_max_age "Link to this definition")
Used by [`send_file()`](#flask.send_file "flask.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`](../config/#SEND_FILE_MAX_AGE_DEFAULT "SEND_FILE_MAX_AGE_DEFAULT")
from the configuration of [`current_app`](#flask.current_app "flask.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.
Changelog
Changed in version 2.0: The default configuration is `None` instead of 12 hours.
Added in version 0.9.
Parameters:
**filename** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_)
Return type:
[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
| None
send\_static\_file(_filename_)[¶](#flask.Blueprint.send_static_file "Link to this definition")
The view function used to serve files from [`static_folder`](#flask.Blueprint.static_folder "flask.Blueprint.static_folder")
. A route is automatically registered for this view at [`static_url_path`](#flask.Blueprint.static_url_path "flask.Blueprint.static_url_path")
if [`static_folder`](#flask.Blueprint.static_folder "flask.Blueprint.static_folder")
is set.
Note this is a duplicate of the same method in the Flask class.
Changelog
Added in version 0.5.
Parameters:
**filename** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
Return type:
[Response](#flask.Response "flask.Response")
open\_resource(_resource_, _mode\='rb'_, _encoding\='utf-8'_)[¶](#flask.Blueprint.open_resource "Link to this definition")
Open a resource file relative to [`root_path`](#flask.Blueprint.root_path "flask.Blueprint.root_path")
for reading. The blueprint-relative equivalent of the app’s [`open_resource()`](#flask.Flask.open_resource "flask.Flask.open_resource")
method.
Parameters:
* **resource** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – Path to the resource relative to [`root_path`](#flask.Blueprint.root_path "flask.Blueprint.root_path")
.
* **mode** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – Open the file in this mode. Only reading is supported, valid values are `"r"` (or `"rt"`) and `"rb"`.
* **encoding** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – Open the file with this encoding when opening in text mode. This is ignored when opening in binary mode.
Return type:
[_IO_](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.13)")
Changed in version 3.1: Added the `encoding` parameter.
add\_app\_template\_filter(_f_, _name\=None_)[¶](#flask.Blueprint.add_app_template_filter "Link to this definition")
Register a template filter, available in any template rendered by the application. Works like the [`app_template_filter()`](#flask.Blueprint.app_template_filter "flask.Blueprint.app_template_filter")
decorator. Equivalent to [`Flask.add_template_filter()`](#flask.Flask.add_template_filter "flask.Flask.add_template_filter")
.
Parameters:
* **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the filter, otherwise the function name will be used.
* **f** ([_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
_\[__\[__...__\]__,_ [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_\]_)
Return type:
None
add\_app\_template\_global(_f_, _name\=None_)[¶](#flask.Blueprint.add_app_template_global "Link to this definition")
Register a template global, available in any template rendered by the application. Works like the [`app_template_global()`](#flask.Blueprint.app_template_global "flask.Blueprint.app_template_global")
decorator. Equivalent to [`Flask.add_template_global()`](#flask.Flask.add_template_global "flask.Flask.add_template_global")
.
Changelog
Added in version 0.10.
Parameters:
* **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the global, otherwise the function name will be used.
* **f** ([_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
_\[__\[__...__\]__,_ [_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\
_\]_)
Return type:
None
add\_app\_template\_test(_f_, _name\=None_)[¶](#flask.Blueprint.add_app_template_test "Link to this definition")
Register a template test, available in any template rendered by the application. Works like the [`app_template_test()`](#flask.Blueprint.app_template_test "flask.Blueprint.app_template_test")
decorator. Equivalent to [`Flask.add_template_test()`](#flask.Flask.add_template_test "flask.Flask.add_template_test")
.
Changelog
Added in version 0.10.
Parameters:
* **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the test, otherwise the function name will be used.
* **f** ([_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
_\[__\[__...__\]__,_ [_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")\
_\]_)
Return type:
None
add\_url\_rule(_rule_, _endpoint\=None_, _view\_func\=None_, _provide\_automatic\_options\=None_, _\*\*options_)[¶](#flask.Blueprint.add_url_rule "Link to this definition")
Register a URL rule with the blueprint. See [`Flask.add_url_rule()`](#flask.Flask.add_url_rule "flask.Flask.add_url_rule")
for full documentation.
The URL rule is prefixed with the blueprint’s URL prefix. The endpoint name, used with [`url_for()`](#flask.url_for "flask.url_for")
, is prefixed with the blueprint’s name.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **endpoint** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_)
* **view\_func** (_ft.RouteCallable_ _|_ _None_)
* **provide\_automatic\_options** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
_|_ _None_)
* **options** (_t.Any_)
Return type:
None
after\_app\_request(_f_)[¶](#flask.Blueprint.after_app_request "Link to this definition")
Like [`after_request()`](#flask.Blueprint.after_request "flask.Blueprint.after_request")
, but after every request, not only those handled by the blueprint. Equivalent to [`Flask.after_request()`](#flask.Flask.after_request "flask.Flask.after_request")
.
Parameters:
**f** (_T\_after\_request_)
Return type:
_T\_after\_request_
after\_request(_f_)[¶](#flask.Blueprint.after_request "Link to this definition")
Register a function to run after each request to this object.
The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent.
If a function raises an exception, any remaining `after_request` functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use [`teardown_request()`](#flask.Blueprint.teardown_request "flask.Blueprint.teardown_request")
for that.
This is available on both app and blueprint objects. When used on an app, this executes after every request. When used on a blueprint, this executes after every request that the blueprint handles. To register with a blueprint and execute after every request, use [`Blueprint.after_app_request()`](#flask.Blueprint.after_app_request "flask.Blueprint.after_app_request")
.
Parameters:
**f** (_T\_after\_request_)
Return type:
_T\_after\_request_
app\_context\_processor(_f_)[¶](#flask.Blueprint.app_context_processor "Link to this definition")
Like [`context_processor()`](#flask.Blueprint.context_processor "flask.Blueprint.context_processor")
, but for templates rendered by every view, not only by the blueprint. Equivalent to [`Flask.context_processor()`](#flask.Flask.context_processor "flask.Flask.context_processor")
.
Parameters:
**f** (_T\_template\_context\_processor_)
Return type:
_T\_template\_context\_processor_
app\_errorhandler(_code_)[¶](#flask.Blueprint.app_errorhandler "Link to this definition")
Like [`errorhandler()`](#flask.Blueprint.errorhandler "flask.Blueprint.errorhandler")
, but for every request, not only those handled by the blueprint. Equivalent to [`Flask.errorhandler()`](#flask.Flask.errorhandler "flask.Flask.errorhandler")
.
Parameters:
**code** ([_type_](https://docs.python.org/3/library/functions.html#type "(in Python v3.13)")
_\[_[_Exception_](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")\
_\]_ _|_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_error\_handler_\], _T\_error\_handler_\]
app\_template\_filter(_name\=None_)[¶](#flask.Blueprint.app_template_filter "Link to this definition")
Register a template filter, available in any template rendered by the application. Equivalent to [`Flask.template_filter()`](#flask.Flask.template_filter "flask.Flask.template_filter")
.
Parameters:
**name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the filter, otherwise the function name will be used.
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_template\_filter_\], _T\_template\_filter_\]
app\_template\_global(_name\=None_)[¶](#flask.Blueprint.app_template_global "Link to this definition")
Register a template global, available in any template rendered by the application. Equivalent to [`Flask.template_global()`](#flask.Flask.template_global "flask.Flask.template_global")
.
Changelog
Added in version 0.10.
Parameters:
**name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the global, otherwise the function name will be used.
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_template\_global_\], _T\_template\_global_\]
app\_template\_test(_name\=None_)[¶](#flask.Blueprint.app_template_test "Link to this definition")
Register a template test, available in any template rendered by the application. Equivalent to [`Flask.template_test()`](#flask.Flask.template_test "flask.Flask.template_test")
.
Changelog
Added in version 0.10.
Parameters:
**name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_|_ _None_) – the optional name of the test, otherwise the function name will be used.
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_template\_test_\], _T\_template\_test_\]
app\_url\_defaults(_f_)[¶](#flask.Blueprint.app_url_defaults "Link to this definition")
Like [`url_defaults()`](#flask.Blueprint.url_defaults "flask.Blueprint.url_defaults")
, but for every request, not only those handled by the blueprint. Equivalent to [`Flask.url_defaults()`](#flask.Flask.url_defaults "flask.Flask.url_defaults")
.
Parameters:
**f** (_T\_url\_defaults_)
Return type:
_T\_url\_defaults_
app\_url\_value\_preprocessor(_f_)[¶](#flask.Blueprint.app_url_value_preprocessor "Link to this definition")
Like [`url_value_preprocessor()`](#flask.Blueprint.url_value_preprocessor "flask.Blueprint.url_value_preprocessor")
, but for every request, not only those handled by the blueprint. Equivalent to [`Flask.url_value_preprocessor()`](#flask.Flask.url_value_preprocessor "flask.Flask.url_value_preprocessor")
.
Parameters:
**f** (_T\_url\_value\_preprocessor_)
Return type:
_T\_url\_value\_preprocessor_
before\_app\_request(_f_)[¶](#flask.Blueprint.before_app_request "Link to this definition")
Like [`before_request()`](#flask.Blueprint.before_request "flask.Blueprint.before_request")
, but before every request, not only those handled by the blueprint. Equivalent to [`Flask.before_request()`](#flask.Flask.before_request "flask.Flask.before_request")
.
Parameters:
**f** (_T\_before\_request_)
Return type:
_T\_before\_request_
before\_request(_f_)[¶](#flask.Blueprint.before_request "Link to this definition")
Register a function to run before each request.
For example, this can be used to open a database connection, or to load the logged in user from the session.
@app.before\_request
def load\_user():
if "user\_id" in session:
g.user \= db.session.get(session\["user\_id"\])
The function will be called without any arguments. If it returns a non-`None` value, the value is handled as if it was the return value from the view, and further request handling is stopped.
This is available on both app and blueprint objects. When used on an app, this executes before every request. When used on a blueprint, this executes before every request that the blueprint handles. To register with a blueprint and execute before every request, use [`Blueprint.before_app_request()`](#flask.Blueprint.before_app_request "flask.Blueprint.before_app_request")
.
Parameters:
**f** (_T\_before\_request_)
Return type:
_T\_before\_request_
context\_processor(_f_)[¶](#flask.Blueprint.context_processor "Link to this definition")
Registers a template context processor function. These functions run before rendering a template. The keys of the returned dict are added as variables available in the template.
This is available on both app and blueprint objects. When used on an app, this is called for every rendered template. When used on a blueprint, this is called for templates rendered from the blueprint’s views. To register with a blueprint and affect every template, use [`Blueprint.app_context_processor()`](#flask.Blueprint.app_context_processor "flask.Blueprint.app_context_processor")
.
Parameters:
**f** (_T\_template\_context\_processor_)
Return type:
_T\_template\_context\_processor_
delete(_rule_, _\*\*options_)[¶](#flask.Blueprint.delete "Link to this definition")
Shortcut for [`route()`](#flask.Blueprint.route "flask.Blueprint.route")
with `methods=["DELETE"]`.
Changelog
Added in version 2.0.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
endpoint(_endpoint_)[¶](#flask.Blueprint.endpoint "Link to this definition")
Decorate a view function to register it for the given endpoint. Used if a rule is added without a `view_func` with [`add_url_rule()`](#flask.Blueprint.add_url_rule "flask.Blueprint.add_url_rule")
.
app.add\_url\_rule("/ex", endpoint\="example")
@app.endpoint("example")
def example():
...
Parameters:
**endpoint** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – The endpoint name to associate with the view function.
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_F_\], _F_\]
errorhandler(_code\_or\_exception_)[¶](#flask.Blueprint.errorhandler "Link to this definition")
Register a function to handle errors by code or exception class.
A decorator that is used to register a function given an error code. Example:
@app.errorhandler(404)
def page\_not\_found(error):
return 'This page does not exist', 404
You can also register handlers for arbitrary exceptions:
@app.errorhandler(DatabaseError)
def special\_exception\_handler(error):
return 'Database connection failed', 500
This is available on both app and blueprint objects. When used on an app, this can handle errors from every request. When used on a blueprint, this can handle errors from requests that the blueprint handles. To register with a blueprint and affect every request, use [`Blueprint.app_errorhandler()`](#flask.Blueprint.app_errorhandler "flask.Blueprint.app_errorhandler")
.
Changelog
Added in version 0.7: Use [`register_error_handler()`](#flask.Blueprint.register_error_handler "flask.Blueprint.register_error_handler")
instead of modifying [`error_handler_spec`](#flask.Blueprint.error_handler_spec "flask.Blueprint.error_handler_spec")
directly, for application wide error handlers.
Added in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the [`HTTPException`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.HTTPException "(in Werkzeug v3.1.x)")
class.
Parameters:
**code\_or\_exception** ([_type_](https://docs.python.org/3/library/functions.html#type "(in Python v3.13)")
_\[_[_Exception_](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")\
_\]_ _|_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
) – the code as integer for the handler, or an arbitrary exception
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_error\_handler_\], _T\_error\_handler_\]
get(_rule_, _\*\*options_)[¶](#flask.Blueprint.get "Link to this definition")
Shortcut for [`route()`](#flask.Blueprint.route "flask.Blueprint.route")
with `methods=["GET"]`.
Changelog
Added in version 2.0.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
_property_ has\_static\_folder_: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
_[¶](#flask.Blueprint.has_static_folder "Link to this definition")
`True` if [`static_folder`](#flask.Blueprint.static_folder "flask.Blueprint.static_folder")
is set.
Changelog
Added in version 0.5.
_property_ jinja\_loader_: [BaseLoader](https://jinja.palletsprojects.com/en/stable/api/#jinja2.BaseLoader "(in Jinja v3.1.x)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Blueprint.jinja_loader "Link to this definition")
The Jinja loader for this object’s templates. By default this is a class [`jinja2.loaders.FileSystemLoader`](https://jinja.palletsprojects.com/en/stable/api/#jinja2.FileSystemLoader "(in Jinja v3.1.x)")
to [`template_folder`](#flask.Blueprint.template_folder "flask.Blueprint.template_folder")
if it is set.
Changelog
Added in version 0.5.
make\_setup\_state(_app_, _options_, _first\_registration\=False_)[¶](#flask.Blueprint.make_setup_state "Link to this definition")
Creates an instance of [`BlueprintSetupState()`](#flask.blueprints.BlueprintSetupState "flask.blueprints.BlueprintSetupState")
object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state.
Parameters:
* **app** (_App_)
* **options** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
_\[_[_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
_,_ _t.Any__\]_)
* **first\_registration** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
)
Return type:
[BlueprintSetupState](#flask.blueprints.BlueprintSetupState "flask.blueprints.BlueprintSetupState")
patch(_rule_, _\*\*options_)[¶](#flask.Blueprint.patch "Link to this definition")
Shortcut for [`route()`](#flask.Blueprint.route "flask.Blueprint.route")
with `methods=["PATCH"]`.
Changelog
Added in version 2.0.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
post(_rule_, _\*\*options_)[¶](#flask.Blueprint.post "Link to this definition")
Shortcut for [`route()`](#flask.Blueprint.route "flask.Blueprint.route")
with `methods=["POST"]`.
Changelog
Added in version 2.0.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
put(_rule_, _\*\*options_)[¶](#flask.Blueprint.put "Link to this definition")
Shortcut for [`route()`](#flask.Blueprint.route "flask.Blueprint.route")
with `methods=["PUT"]`.
Changelog
Added in version 2.0.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
record(_func_)[¶](#flask.Blueprint.record "Link to this definition")
Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the [`make_setup_state()`](#flask.Blueprint.make_setup_state "flask.Blueprint.make_setup_state")
method.
Parameters:
**func** ([_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
_\[__\[_[_BlueprintSetupState_](#flask.blueprints.BlueprintSetupState "flask.sansio.blueprints.BlueprintSetupState")\
_\]__,_ _None__\]_)
Return type:
None
record\_once(_func_)[¶](#flask.Blueprint.record_once "Link to this definition")
Works like [`record()`](#flask.Blueprint.record "flask.Blueprint.record")
but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called.
Parameters:
**func** ([_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
_\[__\[_[_BlueprintSetupState_](#flask.blueprints.BlueprintSetupState "flask.sansio.blueprints.BlueprintSetupState")\
_\]__,_ _None__\]_)
Return type:
None
register(_app_, _options_)[¶](#flask.Blueprint.register "Link to this definition")
Called by [`Flask.register_blueprint()`](#flask.Flask.register_blueprint "flask.Flask.register_blueprint")
to register all views and callbacks registered on the blueprint with the application. Creates a [`BlueprintSetupState`](#flask.blueprints.BlueprintSetupState "flask.blueprints.BlueprintSetupState")
and calls each [`record()`](#flask.Blueprint.record "flask.Blueprint.record")
callback with it.
Parameters:
* **app** (_App_) – The application this blueprint is being registered with.
* **options** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
_\[_[_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
_,_ _t.Any__\]_) – Keyword arguments forwarded from [`register_blueprint()`](#flask.Flask.register_blueprint "flask.Flask.register_blueprint")
.
Return type:
None
Changelog
Changed in version 2.3: Nested blueprints now correctly apply subdomains.
Changed in version 2.1: Registering the same blueprint with the same name multiple times is an error.
Changed in version 2.0.1: Nested blueprints are registered with their dotted name. This allows different blueprints with the same name to be nested at different locations.
Changed in version 2.0.1: The `name` option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for `url_for`.
register\_blueprint(_blueprint_, _\*\*options_)[¶](#flask.Blueprint.register_blueprint "Link to this definition")
Register a [`Blueprint`](#flask.Blueprint "flask.Blueprint")
on this blueprint. Keyword arguments passed to this method will override the defaults set on the blueprint.
Changelog
Changed in version 2.0.1: The `name` option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for `url_for`.
Added in version 2.0.
Parameters:
* **blueprint** (_Blueprint_)
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
)
Return type:
None
register\_error\_handler(_code\_or\_exception_, _f_)[¶](#flask.Blueprint.register_error_handler "Link to this definition")
Alternative error attach function to the [`errorhandler()`](#flask.Blueprint.errorhandler "flask.Blueprint.errorhandler")
decorator that is more straightforward to use for non decorator usage.
Changelog
Added in version 0.7.
Parameters:
* **code\_or\_exception** ([_type_](https://docs.python.org/3/library/functions.html#type "(in Python v3.13)")
_\[_[_Exception_](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")\
_\]_ _|_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
)
* **f** (_ft.ErrorHandlerCallable_)
Return type:
None
route(_rule_, _\*\*options_)[¶](#flask.Blueprint.route "Link to this definition")
Decorate a view function to register it with the given URL rule and options. Calls [`add_url_rule()`](#flask.Blueprint.add_url_rule "flask.Blueprint.add_url_rule")
, which has more details about the implementation.
@app.route("/")
def index():
return "Hello, World!"
See [URL Route Registrations](#url-route-registrations)
.
The endpoint name for the route defaults to the name of the view function if the `endpoint` parameter isn’t passed.
The `methods` parameter defaults to `["GET"]`. `HEAD` and `OPTIONS` are added automatically.
Parameters:
* **rule** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
) – The URL rule string.
* **options** ([_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
) – Extra options passed to the [`Rule`](https://werkzeug.palletsprojects.com/en/stable/routing/#werkzeug.routing.Rule "(in Werkzeug v3.1.x)")
object.
Return type:
[_Callable_](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.13)")
\[\[_T\_route_\], _T\_route_\]
_property_ static\_folder_: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Blueprint.static_folder "Link to this definition")
The absolute path to the configured static folder. `None` if no static folder is set.
_property_ static\_url\_path_: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Blueprint.static_url_path "Link to this definition")
The URL prefix that the static route will be accessible from.
If it was not configured during init, it is derived from [`static_folder`](#flask.Blueprint.static_folder "flask.Blueprint.static_folder")
.
teardown\_app\_request(_f_)[¶](#flask.Blueprint.teardown_app_request "Link to this definition")
Like [`teardown_request()`](#flask.Blueprint.teardown_request "flask.Blueprint.teardown_request")
, but after every request, not only those handled by the blueprint. Equivalent to [`Flask.teardown_request()`](#flask.Flask.teardown_request "flask.Flask.teardown_request")
.
Parameters:
**f** (_T\_teardown_)
Return type:
_T\_teardown_
teardown\_request(_f_)[¶](#flask.Blueprint.teardown_request "Link to this definition")
Register a function to be called when the request context is popped. Typically this happens at the end of each request, but contexts may be pushed manually as well during testing.
with app.test\_request\_context():
...
When the `with` block exits (or `ctx.pop()` is called), the teardown functions are called just before the request context is made inactive.
When a teardown function was called because of an unhandled exception it will be passed an error object. If an [`errorhandler()`](#flask.Blueprint.errorhandler "flask.Blueprint.errorhandler")
is registered, it will handle the exception and the teardown will not receive it.
Teardown functions must avoid raising exceptions. If they execute code that might fail they must surround that code with a `try`/`except` block and log any errors.
The return values of teardown functions are ignored.
This is available on both app and blueprint objects. When used on an app, this executes after every request. When used on a blueprint, this executes after every request that the blueprint handles. To register with a blueprint and execute after every request, use [`Blueprint.teardown_app_request()`](#flask.Blueprint.teardown_app_request "flask.Blueprint.teardown_app_request")
.
Parameters:
**f** (_T\_teardown_)
Return type:
_T\_teardown_
url\_defaults(_f_)[¶](#flask.Blueprint.url_defaults "Link to this definition")
Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place.
This is available on both app and blueprint objects. When used on an app, this is called for every request. When used on a blueprint, this is called for requests that the blueprint handles. To register with a blueprint and affect every request, use [`Blueprint.app_url_defaults()`](#flask.Blueprint.app_url_defaults "flask.Blueprint.app_url_defaults")
.
Parameters:
**f** (_T\_url\_defaults_)
Return type:
_T\_url\_defaults_
url\_value\_preprocessor(_f_)[¶](#flask.Blueprint.url_value_preprocessor "Link to this definition")
Register a URL value preprocessor function for all view functions in the application. These functions will be called before the [`before_request()`](#flask.Blueprint.before_request "flask.Blueprint.before_request")
functions.
The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in `g` rather than pass it to every view.
The function is passed the endpoint name and values dict. The return value is ignored.
This is available on both app and blueprint objects. When used on an app, this is called for every request. When used on a blueprint, this is called for requests that the blueprint handles. To register with a blueprint and affect every request, use [`Blueprint.app_url_value_preprocessor()`](#flask.Blueprint.app_url_value_preprocessor "flask.Blueprint.app_url_value_preprocessor")
.
Parameters:
**f** (_T\_url\_value\_preprocessor_)
Return type:
_T\_url\_value\_preprocessor_
import\_name[¶](#flask.Blueprint.import_name "Link to this definition")
The name of the package or module that this object belongs to. Do not change this once it is set by the constructor.
template\_folder[¶](#flask.Blueprint.template_folder "Link to this definition")
The path to the templates folder, relative to [`root_path`](#flask.Blueprint.root_path "flask.Blueprint.root_path")
, to add to the template loader. `None` if templates should not be added.
root\_path[¶](#flask.Blueprint.root_path "Link to this definition")
Absolute path to the package on the filesystem. Used to look up resources contained in the package.
view\_functions_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, ft.RouteCallable\]_[¶](#flask.Blueprint.view_functions "Link to this definition")
A dictionary mapping endpoint names to view functions.
To register a view function, use the [`route()`](#flask.Blueprint.route "flask.Blueprint.route")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
error\_handler\_spec_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")\
\[[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")\
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")\
, [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")\
\[[type](https://docs.python.org/3/library/functions.html#type "(in Python v3.13)")\
\[[Exception](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)")\
\], ft.ErrorHandlerCallable\]\]\]_[¶](#flask.Blueprint.error_handler_spec "Link to this definition")
A data structure of registered error handlers, in the format `{scope: {code: {class: handler}}}`. The `scope` key is the name of a blueprint the handlers are active for, or `None` for all requests. The `code` key is the HTTP status code for `HTTPException`, or `None` for other exceptions. The innermost dictionary maps exception classes to handler functions.
To register an error handler, use the [`errorhandler()`](#flask.Blueprint.errorhandler "flask.Blueprint.errorhandler")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
before\_request\_funcs_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.BeforeRequestCallable\]\]_[¶](#flask.Blueprint.before_request_funcs "Link to this definition")
A data structure of functions to call at the beginning of each request, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`before_request()`](#flask.Blueprint.before_request "flask.Blueprint.before_request")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
after\_request\_funcs_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.AfterRequestCallable\[t.Any\]\]\]_[¶](#flask.Blueprint.after_request_funcs "Link to this definition")
A data structure of functions to call at the end of each request, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`after_request()`](#flask.Blueprint.after_request "flask.Blueprint.after_request")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
teardown\_request\_funcs_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.TeardownCallable\]\]_[¶](#flask.Blueprint.teardown_request_funcs "Link to this definition")
A data structure of functions to call at the end of each request even if an exception is raised, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`teardown_request()`](#flask.Blueprint.teardown_request "flask.Blueprint.teardown_request")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
template\_context\_processors_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.TemplateContextProcessorCallable\]\]_[¶](#flask.Blueprint.template_context_processors "Link to this definition")
A data structure of functions to call to pass extra context values when rendering templates, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`context_processor()`](#flask.Blueprint.context_processor "flask.Blueprint.context_processor")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
url\_value\_preprocessors_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.URLValuePreprocessorCallable\]\]_[¶](#flask.Blueprint.url_value_preprocessors "Link to this definition")
A data structure of functions to call to modify the keyword arguments passed to the view function, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`url_value_preprocessor()`](#flask.Blueprint.url_value_preprocessor "flask.Blueprint.url_value_preprocessor")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
url\_default\_functions_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[ft.AppOrBlueprintKey, [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")\
\[ft.URLDefaultCallable\]\]_[¶](#flask.Blueprint.url_default_functions "Link to this definition")
A data structure of functions to call to modify the keyword arguments when generating URLs, in the format `{scope: [functions]}`. The `scope` key is the name of a blueprint the functions are active for, or `None` for all requests.
To register a function, use the [`url_defaults()`](#flask.Blueprint.url_defaults "flask.Blueprint.url_defaults")
decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
Incoming Request Data[¶](#incoming-request-data "Link to this heading")
------------------------------------------------------------------------
_class_ flask.Request(_environ_, _populate\_request\=True_, _shallow\=False_)[¶](#flask.Request "Link to this definition")
The request object used by default in Flask. Remembers the matched endpoint and view arguments.
It is what ends up as [`request`](#flask.request "flask.request")
. If you want to replace the request object used you can subclass this and set [`request_class`](#flask.Flask.request_class "flask.Flask.request_class")
to your subclass.
The request object is a [`Request`](https://werkzeug.palletsprojects.com/en/stable/wrappers/#werkzeug.wrappers.Request "(in Werkzeug v3.1.x)")
subclass and provides all of the attributes Werkzeug defines plus a few Flask specific ones.
Parameters:
* **environ** (_WSGIEnvironment_)
* **populate\_request** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
)
* **shallow** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)")
)
url\_rule_: Rule | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_ _\= None_[¶](#flask.Request.url_rule "Link to this definition")
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`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.MethodNotAllowed "(in Werkzeug v3.1.x)")
) because the request was never internally bound.
Changelog
Added in version 0.6.
view\_args_: [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, t.Any\] | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_ _\= None_[¶](#flask.Request.view_args "Link to this definition")
A dict of view arguments that matched the request. If an exception happened when matching, this will be `None`.
routing\_exception_: HTTPException | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_ _\= None_[¶](#flask.Request.routing_exception "Link to this definition")
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`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.NotFound "(in Werkzeug v3.1.x)")
exception or something similar.
_property_ max\_content\_length_: [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Request.max_content_length "Link to this definition")
The maximum number of bytes that will be read during this request. If this limit is exceeded, a 413 [`RequestEntityTooLarge`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.RequestEntityTooLarge "(in Werkzeug v3.1.x)")
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/#MAX_CONTENT_LENGTH "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.
Changelog
Changed in version 0.6: This is configurable through Flask config.
_property_ max\_form\_memory\_size_: [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Request.max_form_memory_size "Link to this definition")
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`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.RequestEntityTooLarge "(in Werkzeug v3.1.x)")
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/#MAX_FORM_MEMORY_SIZE "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](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Request.max_form_parts "Link to this definition")
The maximum number of fields that may be present in a `multipart/form-data` body. If this limit is exceeded, a 413 [`RequestEntityTooLarge`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.RequestEntityTooLarge "(in Werkzeug v3.1.x)")
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/#MAX_FORM_PARTS "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.
_property_ endpoint_: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Request.endpoint "Link to this definition")
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`](#flask.Request.view_args "flask.Request.view_args")
can be used to reconstruct the same URL or a modified URL.
_property_ blueprint_: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Request.blueprint "Link to this definition")
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](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
\]_[¶](#flask.Request.blueprints "Link to this definition")
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.
Changelog
Added in version 2.0.1.
on\_json\_loading\_failed(_e_)[¶](#flask.Request.on_json_loading_failed "Link to this definition")
Called if [`get_json()`](#flask.Request.get_json "flask.Request.get_json")
fails and isn’t silenced.
If this method returns a value, it is used as the return value for [`get_json()`](#flask.Request.get_json "flask.Request.get_json")
. The default implementation raises [`BadRequest`](https://werkzeug.palletsprojects.com/en/stable/exceptions/#werkzeug.exceptions.BadRequest "(in Werkzeug v3.1.x)")
.
Parameters:
**e** ([_ValueError_](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.13)")
_|_ _None_) – If parsing failed, this is the exception. It will be `None` if the content type wasn’t `application/json`.
Return type:
[_Any_](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")
Changelog
Changed in version 2.3: Raise a 415 error instead of 400.
_property_ accept\_charsets_: [CharsetAccept](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.CharsetAccept "(in Werkzeug v3.1.x)")
_[¶](#flask.Request.accept_charsets "Link to this definition")
List of charsets this client supports as [`CharsetAccept`](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.CharsetAccept "(in Werkzeug v3.1.x)")
object.
_property_ accept\_encodings_: [Accept](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.Accept "(in Werkzeug v3.1.x)")
_[¶](#flask.Request.accept_encodings "Link to this definition")
List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at `accept_charset`.
_property_ accept\_languages_: [LanguageAccept](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.LanguageAccept "(in Werkzeug v3.1.x)")
_[¶](#flask.Request.accept_languages "Link to this definition")
List of languages this client accepts as [`LanguageAccept`](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.LanguageAccept "(in Werkzeug v3.1.x)")
object.
_property_ accept\_mimetypes_: [MIMEAccept](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.MIMEAccept "(in Werkzeug v3.1.x)")
_[¶](#flask.Request.accept_mimetypes "Link to this definition")
List of mimetypes this client supports as [`MIMEAccept`](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.MIMEAccept "(in Werkzeug v3.1.x)")
object.
access\_control\_request\_headers[¶](#flask.Request.access_control_request_headers "Link to this definition")
Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set `access_control_allow_headers` on the response to indicate which headers are allowed.
access\_control\_request\_method[¶](#flask.Request.access_control_request_method "Link to this definition")
Sent with a preflight request to indicate which method will be used for the cross origin request. Set `access_control_allow_methods` on the response to indicate which methods are allowed.
_property_ access\_route_: [list](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.13)")
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
\]_[¶](#flask.Request.access_route "Link to this definition")
If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server.
_classmethod_ application(_f_)[¶](#flask.Request.application "Link to this definition")
Decorate a function as responder that accepts the request as the last argument. This works like the `responder()` decorator but the function is passed the request object as the last argument and the request object will be closed automatically:
@Request.application
def my\_wsgi\_app(request):
return Response('Hello World!')
As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing.
Parameters:
**f** (_t.Callable__\[__\[_[_Request_](#flask.Request "flask.Request")\
_\]__,_ _WSGIApplication__\]_) – the WSGI callable to decorate
Returns:
a new WSGI callable
Return type:
WSGIApplication
_property_ args_: [MultiDict](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.MultiDict "(in Werkzeug v3.1.x)")
\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
\]_[¶](#flask.Request.args "Link to this definition")
The parsed URL parameters (the part in the URL after the question mark).
By default an [`ImmutableMultiDict`](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.ImmutableMultiDict "(in Werkzeug v3.1.x)")
is returned from this function. This can be changed by setting [`parameter_storage_class`](#flask.Request.parameter_storage_class "flask.Request.parameter_storage_class")
to a different type. This might be necessary if the order of the form data is important.
Changelog
Changed in version 2.3: Invalid bytes remain percent encoded.
_property_ authorization_: [Authorization](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.Authorization "(in Werkzeug v3.1.x)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Request.authorization "Link to this definition")
The `Authorization` header parsed into an `Authorization` object. `None` if the header is not present.
Changelog
Changed in version 2.3: `Authorization` is no longer a `dict`. The `token` attribute was added for auth schemes that use a token instead of parameters.
_property_ base\_url_: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")
_[¶](#flask.Request.base_url "Link to this definition")
Like [`url`](#flask.Request.url "flask.Request.url")
but without the query string.
_property_ cache\_control_: [RequestCacheControl](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.RequestCacheControl "(in Werkzeug v3.1.x)")
_[¶](#flask.Request.cache_control "Link to this definition")
A [`RequestCacheControl`](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.RequestCacheControl "(in Werkzeug v3.1.x)")
object for the incoming cache control headers.
close()[¶](#flask.Request.close "Link to this definition")
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it.
Changelog
Added in version 0.9.
Return type:
None
content\_encoding[¶](#flask.Request.content_encoding "Link to this definition")
The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.
Changelog
Added in version 0.9.
_property_ content\_length_: [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)")
| [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)")
_[¶](#flask.Request.content_length "Link to this definition")
The Content-Length entity-header field indicates the size of the entity-body in bytes or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
content\_md5[¶](#flask.Request.content_md5 "Link to this definition")
The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)
Changelog
Added in version 0.9.
content\_type[¶](#flask.Request.content_type "Link to this definition")
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
_property_ cookies_: ImmutableMultiDict\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
\]_[¶](#flask.Request.cookies "Link to this definition")
A [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")
with the contents of all cookies transmitted with the request.
_property_ data_: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.13)")
_[¶](#flask.Request.data "Link to this definition")
The raw data read from [`stream`](#flask.Request.stream "flask.Request.stream")
. Will be empty if the request represents form data.
To get the raw data even if it represents form data, use [`get_data()`](#flask.Request.get_data "flask.Request.get_data")
.
date[¶](#flask.Request.date "Link to this definition")
The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822.
Changelog
Changed in version 2.0: The datetime object is timezone-aware.
dict\_storage\_class[¶](#flask.Request.dict_storage_class "Link to this definition")
alias of `ImmutableMultiDict`
_property_ files_: ImmutableMultiDict\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\
, [FileStorage](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.FileStorage "(in Werkzeug v3.1.x)")\
\]_[¶](#flask.Request.files "Link to this definition")
[`MultiDict`](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.MultiDict "(in Werkzeug v3.1.x)")
object containing all uploaded files. Each key in [`files`](#flask.Request.files "flask.Request.files")
is the name from the ``. Each value in [`files`](#flask.Request.files "flask.Request.files")
is a Werkzeug [`FileStorage`](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.FileStorage "(in Werkzeug v3.1.x)")
object.
It basically behaves like a standard file object you know from Python, with the difference that it also has a [`save()`](https://werkzeug.palletsprojects.com/en/stable/datastructures/#werkzeug.datastructures.FileStorage.save "(in Werkzeug v3.1.x)")
function that can store the file on the filesystem.
Note that [`files`](#flask.Request.files "flask.Request.files")
will only contain data if the request method was POST, PUT or PATCH and the `