API

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

Blueprint Objects

Incoming Request Data

flask.request

To access incoming request data, you can use the global request object. Flask parses incoming request data for you and gives you access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment.

This is a proxy. See Notes On Proxies for more information.

The request object is an instance of a Request.

Response Objects

Sessions

If you have set Flask.secret_key (or configured it from SECRET_KEY) you can use sessions in Flask applications. A session makes it possible to remember information from one request to another. The way Flask does this is by using a signed cookie. The user can look at the session contents, but can’t modify it unless they know the secret key, so make sure to set that to something complex and unguessable.

To access the current session you can use the session object:

class flask.session

The session object works pretty much like an ordinary dict, with the difference that it keeps track of modifications.

This is a proxy. See Notes On Proxies for more information.

The following attributes are interesting:

new

True if the session is new, False otherwise.

modified

True if the session object detected a modification. Be advised that modifications on mutable structures are not picked up automatically, in that situation you have to explicitly set the attribute to True yourself. Here an example:

# this change is not picked up because a mutable object (here
# a list) is changed.
session['objects'].append(42)
# so mark it as modified yourself
session.modified = True
permanent

If set to True the session lives for permanent_session_lifetime seconds. The default is 31 days. If set to False (which is the default) the session will be deleted when the user closes the browser.

Session Interface

New in version 0.8.

The session interface provides a simple way to replace the session implementation that Flask is using.

Notice

The PERMANENT_SESSION_LIFETIME config can be an integer or timedelta. The permanent_session_lifetime attribute is always a timedelta.

Test Client

Test CLI Runner

Application Globals

To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request. In a nutshell: it does the right thing, like it does for request and session.

flask.g

A namespace object that can store data during an application context. This is an instance of Flask.app_ctx_globals_class, which defaults to ctx._AppCtxGlobals.

This is a good place to store resources during a request. For example, a before_request function could load a user object from a session id, then set g.user to be used in the view function.

This is a proxy. See Notes On Proxies for more information.

Changed in version 0.10: Bound to the application context instead of the request context.

Useful Functions and Classes

flask.current_app

A proxy to the application handling the current request. This is useful to access the application without needing to import it, or if it can’t be imported, such as when using the application factory pattern or in blueprints and extensions.

This is only available when an application context is pushed. This happens automatically during requests and CLI commands. It can be controlled manually with app_context().

This is a proxy. See Notes On Proxies for more information.

Message Flashing

JSON Support

Flask uses Python’s built-in json module for handling JSON by default. The JSON implementation can be changed by assigning a different provider to flask.Flask.json_provider_class or flask.Flask.json. The functions provided by flask.json will use methods on app.json if an app context is active.

Jinja’s |tojson filter is configured to use the app’s JSON provider. The filter marks the output with |safe. Use it to render data inside HTML <script> tags.

<script>
    const names = {{ names|tosjon }};
    renderChart(names, {{ axis_data|tojson }});
</script>
flask.json.jsonify(*args, **kwargs)

Serialize the given arguments as JSON, and return a Response object with the application/json mimetype. A dict or list returned from a view will be converted to a JSON response automatically without needing to call this.

This requires an active request or application context, and calls app.json.response().

In debug mode, the output is formatted with indentation to make it easier to read. This may also be controlled by the provider.

Either positional or keyword arguments can be given, not both. If no arguments are given, None is serialized.

Parameters:
  • args (t.Any) – A single value to serialize, or multiple values to treat as a list to serialize.

  • kwargs (t.Any) – Treat as a dict to serialize.

Return type:

Response

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

Changed in version 2.0.2: decimal.Decimal is supported by converting to a string.

Changed in version 0.11: Added support for serializing top-level arrays. This was a security risk in ancient browsers. See JSON Security.

New in version 0.2.

flask.json.dumps(obj, *, app=None, **kwargs)

Serialize data as JSON.

If current_app is available, it will use its app.json.dumps() method, otherwise it will use json.dumps().

Parameters:
  • obj (t.Any) – The data to serialize.

  • kwargs (t.Any) – Arguments passed to the dumps implementation.

  • app (Flask | None) –

Return type:

str

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

Changed in version 2.2: The app parameter will be removed in Flask 2.3.

Changed in version 2.0.2: decimal.Decimal is supported by converting to a string.

Changed in version 2.0: encoding will be removed in Flask 2.1.

Changed in version 1.0.3: app can be passed directly, rather than requiring an app context for configuration.

flask.json.dump(obj, fp, *, app=None, **kwargs)

Serialize data as JSON and write to a file.

If current_app is available, it will use its app.json.dump() method, otherwise it will use json.dump().

Parameters:
  • obj (t.Any) – The data to serialize.

  • fp (t.IO[str]) – A file opened for writing text. Should use the UTF-8 encoding to be valid JSON.

  • kwargs (t.Any) – Arguments passed to the dump implementation.

  • app (Flask | None) –

Return type:

None

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

Changed in version 2.2: The app parameter will be removed in Flask 2.3.

Changed in version 2.0: Writing to a binary file, and the encoding argument, will be removed in Flask 2.1.

flask.json.loads(s, *, app=None, **kwargs)

Deserialize data as JSON.

If current_app is available, it will use its app.json.loads() method, otherwise it will use json.loads().

Parameters:
  • s (str | bytes) – Text or UTF-8 bytes.

  • kwargs (t.Any) – Arguments passed to the loads implementation.

  • app (Flask | None) –

Return type:

t.Any

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

Changed in version 2.2: The app parameter will be removed in Flask 2.3.

Changed in version 2.0: encoding will be removed in Flask 2.1. The data must be a string or UTF-8 bytes.

Changed in version 1.0.3: app can be passed directly, rather than requiring an app context for configuration.

flask.json.load(fp, *, app=None, **kwargs)

Deserialize data as JSON read from a file.

If current_app is available, it will use its app.json.load() method, otherwise it will use json.load().

Parameters:
  • fp (t.IO[t.AnyStr]) – A file opened for reading text or UTF-8 bytes.

  • kwargs (t.Any) – Arguments passed to the load implementation.

  • app (Flask | None) –

Return type:

t.Any

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

Changed in version 2.2: The app parameter will be removed in Flask 2.3.

Changed in version 2.0: encoding will be removed in Flask 2.1. The file must be text mode, or binary mode with UTF-8 bytes.

class flask.json.provider.JSONProvider(app)

A standard set of JSON operations for an application. Subclasses of this can be used to customize JSON behavior or use different JSON libraries.

To implement a provider for a specific library, subclass this base class and implement at least dumps() and loads(). All other methods have default implementations.

To use a different provider, either subclass Flask and set json_provider_class to a provider class, or set app.json to an instance of the class.

Parameters:

app (Flask) – An application instance. This will be stored as a weakref.proxy on the _app attribute.

New in version 2.2.

dumps(obj, **kwargs)

Serialize data as JSON.

Parameters:
  • obj (Any) – The data to serialize.

  • kwargs (Any) – May be passed to the underlying JSON library.

Return type:

str

dump(obj, fp, **kwargs)

Serialize data as JSON and write to a file.

Parameters:
  • obj (Any) – The data to serialize.

  • fp (IO[str]) – A file opened for writing text. Should use the UTF-8 encoding to be valid JSON.

  • kwargs (Any) – May be passed to the underlying JSON library.

Return type:

None

loads(s, **kwargs)

Deserialize data as JSON.

Parameters:
  • s (str | bytes) – Text or UTF-8 bytes.

  • kwargs (Any) – May be passed to the underlying JSON library.

Return type:

Any

load(fp, **kwargs)

Deserialize data as JSON read from a file.

Parameters:
  • fp (IO) – A file opened for reading text or UTF-8 bytes.

  • kwargs (Any) – May be passed to the underlying JSON library.

Return type:

Any

response(*args, **kwargs)

Serialize the given arguments as JSON, and return a Response object with the application/json mimetype.

The jsonify() function calls this method for the current application.

Either positional or keyword arguments can be given, not both. If no arguments are given, None is serialized.

Parameters:
  • args (t.Any) – A single value to serialize, or multiple values to treat as a list to serialize.

  • kwargs (t.Any) – Treat as a dict to serialize.

Return type:

Response

class flask.json.provider.DefaultJSONProvider(app)

Provide JSON operations using Python’s built-in json library. Serializes the following additional data types:

  • datetime.datetime and datetime.date are serialized to RFC 822 strings. This is the same as the HTTP date format.

  • uuid.UUID is serialized to a string.

  • dataclasses.dataclass is passed to dataclasses.asdict().

  • Markup (or any object with a __html__ method) will call the __html__ method to get a string.

Parameters:

app (Flask) –

static default(o)

Apply this function to any object that json.dumps() does not know how to serialize. It should return a valid JSON type or raise a TypeError.

Parameters:

o (Any) –

Return type:

Any

ensure_ascii = True

Replace non-ASCII characters with escape sequences. This may be more compatible with some clients, but can be disabled for better performance and size.

sort_keys = True

Sort the keys in any serialized dicts. This may be useful for some caching situations, but can be disabled for better performance. When enabled, keys must all be strings, they are not converted before sorting.

compact: bool | None = None

If True, or None out of debug mode, the response() output will not add indentation, newlines, or spaces. If False, or None in debug mode, it will use a non-compact representation.

mimetype = 'application/json'

The mimetype set in response().

dumps(obj, **kwargs)

Serialize data as JSON to a string.

Keyword arguments are passed to json.dumps(). Sets some parameter defaults from the default, ensure_ascii, and sort_keys attributes.

Parameters:
  • obj (Any) – The data to serialize.

  • kwargs (Any) – Passed to json.dumps().

Return type:

str

loads(s, **kwargs)

Deserialize data as JSON from a string or bytes.

Parameters:
  • s (str | bytes) – Text or UTF-8 bytes.

  • kwargs (Any) – Passed to json.loads().

Return type:

Any

response(*args, **kwargs)

Serialize the given arguments as JSON, and return a Response object with it. The response mimetype will be “application/json” and can be changed with mimetype.

If compact is False or debug mode is enabled, the output will be formatted to be easier to read.

Either positional or keyword arguments can be given, not both. If no arguments are given, None is serialized.

Parameters:
  • args (t.Any) – A single value to serialize, or multiple values to treat as a list to serialize.

  • kwargs (t.Any) – Treat as a dict to serialize.

Return type:

Response

class flask.json.JSONEncoder(**kwargs)

The default JSON encoder. Handles extra types compared to the built-in json.JSONEncoder.

  • datetime.datetime and datetime.date are serialized to RFC 822 strings. This is the same as the HTTP date format.

  • decimal.Decimal is serialized to a string.

  • uuid.UUID is serialized to a string.

  • dataclasses.dataclass is passed to dataclasses.asdict().

  • Markup (or any object with a __html__ method) will call the __html__ method to get a string.

Assign a subclass of this to flask.Flask.json_encoder or flask.Blueprint.json_encoder to override the default.

Deprecated since version 2.2: Will be removed in Flask 2.3. Use app.json instead.

default(o)

Convert o to a JSON serializable type. See json.JSONEncoder.default(). Python does not support overriding how basic types like str or list are serialized, they are handled before this method.

Parameters:

o (Any) –

Return type:

Any

class flask.json.JSONDecoder(**kwargs)

The default JSON decoder.

This does not change any behavior from the built-in json.JSONDecoder.

Assign a subclass of this to flask.Flask.json_decoder or flask.Blueprint.json_decoder to override the default.

Deprecated since version 2.2: Will be removed in Flask 2.3. Use app.json instead.

Tagged JSON

A compact representation for lossless serialization of non-standard JSON types. SecureCookieSessionInterface uses this to serialize the session data, but it may be useful in other places. It can be extended to support other types.

class flask.json.tag.TaggedJSONSerializer

Serializer that uses a tag system to compactly represent objects that are not JSON types. Passed as the intermediate serializer to itsdangerous.Serializer.

The following extra types are supported:

  • dict

  • tuple

  • bytes

  • Markup

  • UUID

  • datetime

default_tags = [<class 'flask.json.tag.TagDict'>, <class 'flask.json.tag.PassDict'>, <class 'flask.json.tag.TagTuple'>, <class 'flask.json.tag.PassList'>, <class 'flask.json.tag.TagBytes'>, <class 'flask.json.tag.TagMarkup'>, <class 'flask.json.tag.TagUUID'>, <class 'flask.json.tag.TagDateTime'>]

Tag classes to bind when creating the serializer. Other tags can be added later using register().

dumps(value)

Tag the value and dump it to a compact JSON string.

Parameters:

value (Any) –

Return type:

str

loads(value)

Load data from a JSON string and deserialized any tagged objects.

Parameters:

value (str) –

Return type:

Any

register(tag_class, force=False, index=None)

Register a new tag with this serializer.

Parameters:
  • tag_class (Type[JSONTag]) – tag class to register. Will be instantiated with this serializer instance.

  • force (bool) – overwrite an existing tag. If false (default), a KeyError is raised.

  • index (Optional[int]) – index to insert the new tag in the tag order. Useful when the new tag is a special case of an existing tag. If None (default), the tag is appended to the end of the order.

Raises:

KeyError – if the tag key is already registered and force is not true.

Return type:

None

tag(value)

Convert a value to a tagged representation if necessary.

Parameters:

value (Any) –

Return type:

Dict[str, Any]

untag(value)

Convert a tagged representation back to the original type.

Parameters:

value (Dict[str, Any]) –

Return type:

Any

class flask.json.tag.JSONTag(serializer)

Base class for defining type tags for TaggedJSONSerializer.

Parameters:

serializer (TaggedJSONSerializer) –

check(value)

Check if the given value should be tagged by this tag.

Parameters:

value (Any) –

Return type:

bool

key: Optional[str] = None

The tag to mark the serialized object with. If None, this tag is only used as an intermediate step during tagging.

tag(value)

Convert the value to a valid JSON type and add the tag structure around it.

Parameters:

value (Any) –

Return type:

Any

to_json(value)

Convert the Python object to an object that is a valid JSON type. The tag will be added later.

Parameters:

value (Any) –

Return type:

Any

to_python(value)

Convert the JSON representation back to the correct type. The tag will already be removed.

Parameters:

value (Any) –

Return type:

Any

Let’s see an example that adds support for OrderedDict. Dicts don’t have an order in JSON, so to handle this we will dump the items as a list of [key, value] pairs. Subclass JSONTag and give it the new key ' od' to identify the type. The session serializer processes dicts first, so insert the new tag at the front of the order since OrderedDict must be processed before dict.

from flask.json.tag import JSONTag

class TagOrderedDict(JSONTag):
    __slots__ = ('serializer',)
    key = ' od'

    def check(self, value):
        return isinstance(value, OrderedDict)

    def to_json(self, value):
        return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]

    def to_python(self, value):
        return OrderedDict(value)

app.session_interface.serializer.register(TagOrderedDict, index=0)

Template Rendering

Configuration

Stream Helpers

Useful Internals

flask.globals.request_ctx

The current RequestContext. If a request context is not active, accessing attributes on this proxy will raise a RuntimeError.

This is an internal object that is essential to how Flask handles requests. Accessing this should not be needed in most cases. Most likely you want request and session instead.

flask.globals.app_ctx

The current AppContext. If an app context is not active, accessing attributes on this proxy will raise a RuntimeError.

This is an internal object that is essential to how Flask handles requests. Accessing this should not be needed in most cases. Most likely you want current_app and g instead.

Signals

New in version 0.6.

signals.signals_available

True if the signaling system is available. This is the case when blinker is installed.

The following signals exist in Flask:

flask.template_rendered

This signal is sent when a template was successfully rendered. The signal is invoked with the instance of the template as template and the context as dictionary (named context).

Example subscriber:

def log_template_renders(sender, template, context, **extra):
    sender.logger.debug('Rendering template "%s" with context %s',
                        template.name or 'string template',
                        context)

from flask import template_rendered
template_rendered.connect(log_template_renders, app)
flask.before_render_template

This signal is sent before template rendering process. The signal is invoked with the instance of the template as template and the context as dictionary (named context).

Example subscriber:

def log_template_renders(sender, template, context, **extra):
    sender.logger.debug('Rendering template "%s" with context %s',
                        template.name or 'string template',
                        context)

from flask import before_render_template
before_render_template.connect(log_template_renders, app)
flask.request_started

This signal is sent when the request context is set up, before any request processing happens. Because the request context is already bound, the subscriber can access the request with the standard global proxies such as request.

Example subscriber:

def log_request(sender, **extra):
    sender.logger.debug('Request context is set up')

from flask import request_started
request_started.connect(log_request, app)
flask.request_finished

This signal is sent right before the response is sent to the client. It is passed the response to be sent named response.

Example subscriber:

def log_response(sender, response, **extra):
    sender.logger.debug('Request context is about to close down.  '
                        'Response: %s', response)

from flask import request_finished
request_finished.connect(log_response, app)
flask.got_request_exception

This signal is sent when an unhandled exception happens during request processing, including when debugging. The exception is passed to the subscriber as exception.

This signal is not sent for HTTPException, or other exceptions that have error handlers registered, unless the exception was raised from an error handler.

This example shows how to do some extra logging if a theoretical SecurityException was raised:

from flask import got_request_exception

def log_security_exception(sender, exception, **extra):
    if not isinstance(exception, SecurityException):
        return

    security_logger.exception(
        f"SecurityException at {request.url!r}",
        exc_info=exception,
    )

got_request_exception.connect(log_security_exception, app)
flask.request_tearing_down

This signal is sent when the request is tearing down. This is always called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on.

Example subscriber:

def close_db_connection(sender, **extra):
    session.close()

from flask import request_tearing_down
request_tearing_down.connect(close_db_connection, app)

As of Flask 0.9, this will also be passed an exc keyword argument that has a reference to the exception that caused the teardown if there was one.

flask.appcontext_tearing_down

This signal is sent when the app context is tearing down. This is always called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on.

Example subscriber:

def close_db_connection(sender, **extra):
    session.close()

from flask import appcontext_tearing_down
appcontext_tearing_down.connect(close_db_connection, app)

This will also be passed an exc keyword argument that has a reference to the exception that caused the teardown if there was one.

flask.appcontext_pushed

This signal is sent when an application context is pushed. The sender is the application. This is usually useful for unittests in order to temporarily hook in information. For instance it can be used to set a resource early onto the g object.

Example usage:

from contextlib import contextmanager
from flask import appcontext_pushed

@contextmanager
def user_set(app, user):
    def handler(sender, **kwargs):
        g.user = user
    with appcontext_pushed.connected_to(handler, app):
        yield

And in the testcode:

def test_user_me(self):
    with user_set(app, 'john'):
        c = app.test_client()
        resp = c.get('/users/me')
        assert resp.data == 'username=john'

New in version 0.10.

flask.appcontext_popped

This signal is sent when an application context is popped. The sender is the application. This usually falls in line with the appcontext_tearing_down signal.

New in version 0.10.

flask.message_flashed

This signal is sent when the application is flashing a message. The messages is sent as message keyword argument and the category as category.

Example subscriber:

recorded = []
def record(sender, message, category, **extra):
    recorded.append((message, category))

from flask import message_flashed
message_flashed.connect(record, app)

New in version 0.10.

class signals.Namespace

An alias for blinker.base.Namespace if blinker is available, otherwise a dummy class that creates fake signals. This class is available for Flask extensions that want to provide the same fallback system as Flask itself.

signal(name, doc=None)

Creates a new signal for this namespace if blinker is available, otherwise returns a fake signal that has a send method that will do nothing but will fail with a RuntimeError for all other operations, including connecting.

Class-Based Views

New in version 0.7.

URL Route Registrations

Generally there are three ways to define rules for the routing system:

  1. You can use the flask.Flask.route() decorator.

  2. You can use the flask.Flask.add_url_rule() function.

  3. You can directly access the underlying Werkzeug routing system which is exposed as flask.Flask.url_map.

Variable parts in the route can be specified with angular brackets (/user/<username>). By default a variable part in the URL accepts any string without a slash however a different converter can be specified as well by using <converter:name>.

Variable parts are passed to the view function as keyword arguments.

The following converters are available:

string

accepts any text without a slash (the default)

int

accepts integers

float

like int but for floating point values

path

like the default but also accepts slashes

any

matches one of the items provided

uuid

accepts UUID strings

Custom converters can be defined using flask.Flask.url_map.

Here are some examples:

@app.route('/')
def index():
    pass

@app.route('/<username>')
def show_user(username):
    pass

@app.route('/post/<int:post_id>')
def show_post(post_id):
    pass

An important detail to keep in mind is how Flask deals with trailing slashes. The idea is to keep each URL unique so the following rules apply:

  1. If a rule ends with a slash and is requested without a slash by the user, the user is automatically redirected to the same page with a trailing slash attached.

  2. If a rule does not end with a trailing slash and the user requests the page with a trailing slash, a 404 not found is raised.

This is consistent with how web servers deal with static files. This also makes it possible to use relative link targets safely.

You can also define multiple rules for the same function. They have to be unique however. Defaults can also be specified. Here for example is a definition for a URL that accepts an optional page:

@app.route('/users/', defaults={'page': 1})
@app.route('/users/page/<int:page>')
def show_users(page):
    pass

This specifies that /users/ will be the URL for page one and /users/page/N will be the URL for page N.

If a URL contains a default value, it will be redirected to its simpler form with a 301 redirect. In the above example, /users/page/1 will be redirected to /users/. If your route handles GET and POST requests, make sure the default route only handles GET, as redirects can’t preserve form data.

@app.route('/region/', defaults={'id': 1})
@app.route('/region/<int:id>', methods=['GET', 'POST'])
def region(id):
   pass

Here are the parameters that route() and add_url_rule() accept. The only difference is that with the route parameter the view function is defined with the decorator instead of the view_func parameter.

rule

the URL rule as string

endpoint

the endpoint for the registered URL rule. Flask itself assumes that the name of the view function is the name of the endpoint if not explicitly stated.

view_func

the function to call when serving a request to the provided endpoint. If this is not provided one can specify the function later by storing it in the view_functions dictionary with the endpoint as key.

defaults

A dictionary with defaults for this rule. See the example above for how defaults work.

subdomain

specifies the rule for the subdomain in case subdomain matching is in use. If not specified the default subdomain is assumed.

**options

the options to be forwarded to the underlying Rule object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET, POST etc.). By default a rule just listens for GET (and implicitly HEAD). Starting with Flask 0.6, OPTIONS is implicitly added and handled by the standard request handling. They have to be specified as keyword arguments.

View Function Options

For internal usage the view functions can have some attributes attached to customize behavior the view function would normally not have control over. The following attributes can be provided optionally to either override some defaults to add_url_rule() or general behavior:

  • __name__: The name of a function is by default used as endpoint. If endpoint is provided explicitly this value is used. Additionally this will be prefixed with the name of the blueprint by default which cannot be customized from the function itself.

  • methods: If methods are not provided when the URL rule is added, Flask will look on the view function object itself if a methods attribute exists. If it does, it will pull the information for the methods from there.

  • provide_automatic_options: if this attribute is set Flask will either force enable or disable the automatic implementation of the HTTP OPTIONS response. This can be useful when working with decorators that want to customize the OPTIONS response on a per-view basis.

  • required_methods: if this attribute is set, Flask will always add these methods when registering a URL rule even if the methods were explicitly overridden in the route() call.

Full example:

def index():
    if request.method == 'OPTIONS':
        # custom options handling here
        ...
    return 'Hello World!'
index.provide_automatic_options = False
index.methods = ['GET', 'OPTIONS']

app.add_url_rule('/', index)

New in version 0.8: The provide_automatic_options functionality was added.

Command Line Interface