Skip to content
Myr

api.rst

This file

Path

docs/api.rst

708 lines · 20.7 KiB

Last changed by

redirect defaults to 303 (#5898)David Lordbefore adoption809d5a8

History of this file

Take it

The walk stopped after 200 commits: lines older than 73739a2 point at it.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1–33why, one step back
1API
2===34.. module:: flask56This part of the documentation covers all the interfaces of Flask. For7parts where Flask depends on external libraries, we document the most8important right here and provide links to the canonical documentation.91011Application Object12------------------1314.. autoclass:: Flask15 :members:16 :inherited-members:171819Blueprint Objects20-----------------2122.. autoclass:: Blueprint23 :members:24 :inherited-members:2526Incoming Request Data27---------------------2829.. autoclass:: Request30 :members:31 :inherited-members:32 :exclude-members: json_module33

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 34why, one step back
34.. data:: request

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 35why, one step back
35

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 36–37why, one step back
36 A proxy to the request data for the current request, an instance of
37 :class:`.Request`.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 38why, one step back
38

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 39–40why, one step back
39 This is only available when a :doc:`request context </appcontext>` is
40 active.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 41why, one step back
41

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 42why, one step back
42 This is a proxy. See :ref:`context-visibility` for more information.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 43–62why, one step back
43
4445Response Objects46----------------4748.. autoclass:: flask.Response49 :members:50 :inherited-members:51 :exclude-members: json_module5253Sessions54--------5556If you have set :attr:`Flask.secret_key` (or configured it from57:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes58it possible to remember information from one request to another. The way Flask59does this is by using a signed cookie. The user can look at the session60contents, but can't modify it unless they know the secret key, so make sure to61set that to something complex and unguessable.62

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 63why, one step back
63To access the current session you can use the :data:`.session` proxy.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 64why, one step back
64

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 65why, one step back
65.. data:: session

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 66why, one step back
66

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 67–68why, one step back
67 A proxy to the session data for the current request, an instance of
68 :class:`.SessionMixin`.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 69why, one step back
69

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 70–71why, one step back
70 This is only available when a :doc:`request context </appcontext>` is
71 active.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 72why, one step back
72

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 73why, one step back
73 This is a proxy. See :ref:`context-visibility` for more information.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 74why, one step back
74

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 75–77why, one step back
75 The session object works like a dict but tracks assignment and access to its
76 keys. It cannot track modifications to mutable values, you need to set77 :attr:`~.SessionMixin.modified` manually when modifying a list, dict, etc.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 78why, one step back
78

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 79why, one step back
79 .. code-block:: python

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 80why, one step back
80

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 81–82why, one step back
81 # appending to a list is not detected
82 session["numbers"].append(42)

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 83–85why, one step back
83 # so mark it as modified yourself
84 session.modified = True85

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 86–89why, one step back
86 The session is persisted across requests using a cookie. By default the
87 users's browser will clear the cookie when it is closed. Set88 :attr:`~.SessionMixin.permanent` to ``True`` to persist the cookie for89 :data:`PERMANENT_SESSION_LIFETIME`.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 90–151why, one step back
90
9192Session Interface93-----------------9495.. versionadded:: 0.89697The session interface provides a simple way to replace the session98implementation that Flask is using.99100.. currentmodule:: flask.sessions101102.. autoclass:: SessionInterface103 :members:104105.. autoclass:: SecureCookieSessionInterface106 :members:107108.. autoclass:: SecureCookieSession109 :members:110111.. autoclass:: NullSession112 :members:113114.. autoclass:: SessionMixin115 :members:116117.. admonition:: Notice118119 The :data:`PERMANENT_SESSION_LIFETIME` config can be an integer or ``timedelta``.120 The :attr:`~flask.Flask.permanent_session_lifetime` attribute is always a121 ``timedelta``.122123124Test Client125-----------126127.. currentmodule:: flask.testing128129.. autoclass:: FlaskClient130 :members:131132133Test CLI Runner134---------------135136.. currentmodule:: flask.testing137138.. autoclass:: FlaskCliRunner139 :members:140141142Application Globals143-------------------144145.. currentmodule:: flask146147To share data that is valid for one request only from one function to148another, a global variable is not good enough because it would break in149threaded environments. Flask provides you with a special object that150ensures it is only valid for the active request and that will return151different values for each request. In a nutshell: it does the right

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 152why, one step back
152thing, like it does for :data:`.request` and :data:`.session`.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 153–155why, one step back
153
154.. data:: g155

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 156–158why, one step back
156 A proxy to a namespace object used to store data during a single request or
157 app context. An instance of :attr:`.Flask.app_ctx_globals_class`, which158 defaults to :class:`._AppCtxGlobals`.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 159why, one step back
159

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 160–162why, one step back
160 This is a good place to store resources during a request. For example, a
161 :meth:`~.Flask.before_request` function could load a user object from a162 session id, then set ``g.user`` to be used in the view function.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 163why, one step back
163

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 164why, one step back
164 This is only available when an :doc:`app context </appcontext>` is active.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 165why, one step back
165

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 166–167why, one step back
166 This is a proxy. See :ref:`context-visibility` for more information.
167

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 168–179why, one step back
168 .. versionchanged:: 0.10
169 Bound to the application context instead of the request context.170171.. autoclass:: flask.ctx._AppCtxGlobals172 :members:173174175Useful Functions and Classes176----------------------------177178.. data:: current_app179

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 180–181why, one step back
180 A proxy to the :class:`.Flask` application handling the current request or
181 other activity.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 182why, one step back
182

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 183–185why, one step back
183 This is useful to access the application without needing to import it, or if
184 it can't be imported, such as when using the application factory pattern or185 in blueprints and extensions.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 186why, one step back
186

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 187why, one step back
187 This is only available when an :doc:`app context </appcontext>` is active.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 188why, one step back
188

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 189–190why, one step back
189 This is a proxy. See :ref:`context-visibility` for more information.
190

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 191–292why, one step back
191.. autofunction:: has_request_context
192193.. autofunction:: copy_current_request_context194195.. autofunction:: has_app_context196197.. autofunction:: url_for198199.. autofunction:: abort200201.. autofunction:: redirect202203.. autofunction:: make_response204205.. autofunction:: after_this_request206207.. autofunction:: send_file208209.. autofunction:: send_from_directory210211212Message Flashing213----------------214215.. autofunction:: flash216217.. autofunction:: get_flashed_messages218219220JSON Support221------------222223.. module:: flask.json224225Flask uses Python's built-in :mod:`json` module for handling JSON by226default. The JSON implementation can be changed by assigning a different227provider to :attr:`flask.Flask.json_provider_class` or228:attr:`flask.Flask.json`. The functions provided by ``flask.json`` will229use methods on ``app.json`` if an app context is active.230231Jinja's ``|tojson`` filter is configured to use the app's JSON provider.232The filter marks the output with ``|safe``. Use it to render data inside233HTML ``<script>`` tags.234235.. sourcecode:: html+jinja236237 <script>238 const names = {{ names|tojson }};239 renderChart(names, {{ axis_data|tojson }});240 </script>241242.. autofunction:: jsonify243244.. autofunction:: dumps245246.. autofunction:: dump247248.. autofunction:: loads249250.. autofunction:: load251252.. autoclass:: flask.json.provider.JSONProvider253 :members:254 :member-order: bysource255256.. autoclass:: flask.json.provider.DefaultJSONProvider257 :members:258 :member-order: bysource259260.. automodule:: flask.json.tag261262263Template Rendering264------------------265266.. currentmodule:: flask267268.. autofunction:: render_template269270.. autofunction:: render_template_string271272.. autofunction:: stream_template273274.. autofunction:: stream_template_string275276.. autofunction:: get_template_attribute277278Configuration279-------------280281.. autoclass:: Config282 :members:283284285Stream Helpers286--------------287288.. autofunction:: stream_with_context289290Useful Internals291----------------292

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 293why, one step back
293.. autoclass:: flask.ctx.AppContext

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 294–295why, one step back
294 :members:
295

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 296why, one step back
296.. data:: flask.globals.app_ctx

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 297why, one step back
297

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 298why, one step back
298 A proxy to the active :class:`.AppContext`.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 299why, one step back
299

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 300–302why, one step back
300 This is an internal object that is essential to how Flask handles requests.
301 Accessing this should not be needed in most cases. Most likely you want302 :data:`.current_app`, :data:`.g`, :data:`.request`, and :data:`.session` instead.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 303why, one step back
303

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 304–305why, one step back
304 This is only available when a :doc:`request context </appcontext>` is
305 active.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 306why, one step back
306

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 307why, one step back
307 This is a proxy. See :ref:`context-visibility` for more information.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 308why, one step back
308

merge app and request context (#5812)David Lordbefore adoptionadf3636

line 309why, one step back
309.. class:: flask.ctx.RequestContext

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 310why, one step back
310

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 311–317why, one step back
311 .. deprecated:: 3.2
312 Merged with :class:`AppContext`. This alias will be removed in Flask 4.0.313314.. data:: flask.globals.request_ctx315316 .. deprecated:: 3.2317 Merged with :data:`.app_ctx`. This alias will be removed in Flask 4.0.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 318–598why, one step back
318
319.. autoclass:: flask.blueprints.BlueprintSetupState320 :members:321322.. _core-signals-list:323324Signals325-------326327Signals are provided by the `Blinker`_ library. See :doc:`signals` for an introduction.328329.. _blinker: https://blinker.readthedocs.io/330331.. data:: template_rendered332333 This signal is sent when a template was successfully rendered. The334 signal is invoked with the instance of the template as `template`335 and the context as dictionary (named `context`).336337 Example subscriber::338339 def log_template_renders(sender, template, context, **extra):340 sender.logger.debug('Rendering template "%s" with context %s',341 template.name or 'string template',342 context)343344 from flask import template_rendered345 template_rendered.connect(log_template_renders, app)346347.. data:: flask.before_render_template348 :noindex:349350 This signal is sent before template rendering process. The351 signal is invoked with the instance of the template as `template`352 and the context as dictionary (named `context`).353354 Example subscriber::355356 def log_template_renders(sender, template, context, **extra):357 sender.logger.debug('Rendering template "%s" with context %s',358 template.name or 'string template',359 context)360361 from flask import before_render_template362 before_render_template.connect(log_template_renders, app)363364.. data:: request_started365366 This signal is sent when the request context is set up, before367 any request processing happens. Because the request context is already368 bound, the subscriber can access the request with the standard global369 proxies such as :class:`~flask.request`.370371 Example subscriber::372373 def log_request(sender, **extra):374 sender.logger.debug('Request context is set up')375376 from flask import request_started377 request_started.connect(log_request, app)378379.. data:: request_finished380381 This signal is sent right before the response is sent to the client.382 It is passed the response to be sent named `response`.383384 Example subscriber::385386 def log_response(sender, response, **extra):387 sender.logger.debug('Request context is about to close down. '388 'Response: %s', response)389390 from flask import request_finished391 request_finished.connect(log_response, app)392393.. data:: got_request_exception394395 This signal is sent when an unhandled exception happens during396 request processing, including when debugging. The exception is397 passed to the subscriber as ``exception``.398399 This signal is not sent for400 :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that401 have error handlers registered, unless the exception was raised from402 an error handler.403404 This example shows how to do some extra logging if a theoretical405 ``SecurityException`` was raised:406407 .. code-block:: python408409 from flask import got_request_exception410411 def log_security_exception(sender, exception, **extra):412 if not isinstance(exception, SecurityException):413 return414415 security_logger.exception(416 f"SecurityException at {request.url!r}",417 exc_info=exception,418 )419420 got_request_exception.connect(log_security_exception, app)421422.. data:: request_tearing_down423424 This signal is sent when the request is tearing down. This is always425 called, even if an exception is caused. Currently functions listening426 to this signal are called after the regular teardown handlers, but this427 is not something you can rely on.428429 Example subscriber::430431 def close_db_connection(sender, **extra):432 session.close()433434 from flask import request_tearing_down435 request_tearing_down.connect(close_db_connection, app)436437 As of Flask 0.9, this will also be passed an `exc` keyword argument438 that has a reference to the exception that caused the teardown if439 there was one.440441.. data:: appcontext_tearing_down442443 This signal is sent when the app context is tearing down. This is always444 called, even if an exception is caused. Currently functions listening445 to this signal are called after the regular teardown handlers, but this446 is not something you can rely on.447448 Example subscriber::449450 def close_db_connection(sender, **extra):451 session.close()452453 from flask import appcontext_tearing_down454 appcontext_tearing_down.connect(close_db_connection, app)455456 This will also be passed an `exc` keyword argument that has a reference457 to the exception that caused the teardown if there was one.458459.. data:: appcontext_pushed460461 This signal is sent when an application context is pushed. The sender462 is the application. This is usually useful for unittests in order to463 temporarily hook in information. For instance it can be used to464 set a resource early onto the `g` object.465466 Example usage::467468 from contextlib import contextmanager469 from flask import appcontext_pushed470471 @contextmanager472 def user_set(app, user):473 def handler(sender, **kwargs):474 g.user = user475 with appcontext_pushed.connected_to(handler, app):476 yield477478 And in the testcode::479480 def test_user_me(self):481 with user_set(app, 'john'):482 c = app.test_client()483 resp = c.get('/users/me')484 assert resp.data == 'username=john'485486 .. versionadded:: 0.10487488.. data:: appcontext_popped489490 This signal is sent when an application context is popped. The sender491 is the application. This usually falls in line with the492 :data:`appcontext_tearing_down` signal.493494 .. versionadded:: 0.10495496.. data:: message_flashed497498 This signal is sent when the application is flashing a message. The499 messages is sent as `message` keyword argument and the category as500 `category`.501502 Example subscriber::503504 recorded = []505 def record(sender, message, category, **extra):506 recorded.append((message, category))507508 from flask import message_flashed509 message_flashed.connect(record, app)510511 .. versionadded:: 0.10512513514Class-Based Views515-----------------516517.. versionadded:: 0.7518519.. currentmodule:: None520521.. autoclass:: flask.views.View522 :members:523524.. autoclass:: flask.views.MethodView525 :members:526527.. _url-route-registrations:528529URL Route Registrations530-----------------------531532Generally there are three ways to define rules for the routing system:5335341. You can use the :meth:`flask.Flask.route` decorator.5352. You can use the :meth:`flask.Flask.add_url_rule` function.5363. You can directly access the underlying Werkzeug routing system537 which is exposed as :attr:`flask.Flask.url_map`.538539Variable parts in the route can be specified with angular brackets540(``/user/<username>``). By default a variable part in the URL accepts any541string without a slash however a different converter can be specified as542well by using ``<converter:name>``.543544Variable parts are passed to the view function as keyword arguments.545546The following converters are available:547548=========== ===============================================549`string` accepts any text without a slash (the default)550`int` accepts integers551`float` like `int` but for floating point values552`path` like the default but also accepts slashes553`any` matches one of the items provided554`uuid` accepts UUID strings555=========== ===============================================556557Custom converters can be defined using :attr:`flask.Flask.url_map`.558559Here are some examples::560561 @app.route('/')562 def index():563 pass564565 @app.route('/<username>')566 def show_user(username):567 pass568569 @app.route('/post/<int:post_id>')570 def show_post(post_id):571 pass572573An important detail to keep in mind is how Flask deals with trailing574slashes. The idea is to keep each URL unique so the following rules575apply:5765771. If a rule ends with a slash and is requested without a slash by the578 user, the user is automatically redirected to the same page with a579 trailing slash attached.5802. If a rule does not end with a trailing slash and the user requests the581 page with a trailing slash, a 404 not found is raised.582583This is consistent with how web servers deal with static files. This584also makes it possible to use relative link targets safely.585586You can also define multiple rules for the same function. They have to be587unique however. Defaults can also be specified. Here for example is a588definition for a URL that accepts an optional page::589590 @app.route('/users/', defaults={'page': 1})591 @app.route('/users/page/<int:page>')592 def show_users(page):593 pass594595This specifies that ``/users/`` will be the URL for page one and596``/users/page/N`` will be the URL for page ``N``.597598If a URL contains a default value, it will be redirected to its simpler

redirect defaults to 303 (#5898)David Lordbefore adoption809d5a8

line 599why, one step back
599form with a 308 redirect. In the above example, ``/users/page/1`` will

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 600–708why, one step back
600be redirected to ``/users/``. If your route handles ``GET`` and ``POST``
601requests, make sure the default route only handles ``GET``, as redirects602can't preserve form data. ::603604 @app.route('/region/', defaults={'id': 1})605 @app.route('/region/<int:id>', methods=['GET', 'POST'])606 def region(id):607 pass608609Here are the parameters that :meth:`~flask.Flask.route` and610:meth:`~flask.Flask.add_url_rule` accept. The only difference is that611with the route parameter the view function is defined with the decorator612instead of the `view_func` parameter.613614=============== ==========================================================615`rule` the URL rule as string616`endpoint` the endpoint for the registered URL rule. Flask itself617 assumes that the name of the view function is the name618 of the endpoint if not explicitly stated.619`view_func` the function to call when serving a request to the620 provided endpoint. If this is not provided one can621 specify the function later by storing it in the622 :attr:`~flask.Flask.view_functions` dictionary with the623 endpoint as key.624`defaults` A dictionary with defaults for this rule. See the625 example above for how defaults work.626`subdomain` specifies the rule for the subdomain in case subdomain627 matching is in use. If not specified the default628 subdomain is assumed.629`**options` the options to be forwarded to the underlying630 :class:`~werkzeug.routing.Rule` object. A change to631 Werkzeug is handling of method options. methods is a list632 of methods this rule should be limited to (``GET``, ``POST``633 etc.). By default a rule just listens for ``GET`` (and634 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is635 implicitly added and handled by the standard request636 handling. They have to be specified as keyword arguments.637=============== ==========================================================638639640View Function Options641---------------------642643For internal usage the view functions can have some attributes attached to644customize behavior the view function would normally not have control over.645The following attributes can be provided optionally to either override646some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:647648- `__name__`: The name of a function is by default used as endpoint. If649 endpoint is provided explicitly this value is used. Additionally this650 will be prefixed with the name of the blueprint by default which651 cannot be customized from the function itself.652653- `methods`: If methods are not provided when the URL rule is added,654 Flask will look on the view function object itself if a `methods`655 attribute exists. If it does, it will pull the information for the656 methods from there.657658- `provide_automatic_options`: if this attribute is set Flask will659 either force enable or disable the automatic implementation of the660 HTTP ``OPTIONS`` response. This can be useful when working with661 decorators that want to customize the ``OPTIONS`` response on a per-view662 basis.663664- `required_methods`: if this attribute is set, Flask will always add665 these methods when registering a URL rule even if the methods were666 explicitly overridden in the ``route()`` call.667668Full example::669670 def index():671 if request.method == 'OPTIONS':672 # custom options handling here673 ...674 return 'Hello World!'675 index.provide_automatic_options = False676 index.methods = ['GET', 'OPTIONS']677678 app.add_url_rule('/', index)679680.. versionadded:: 0.8681 The `provide_automatic_options` functionality was added.682683Command Line Interface684----------------------685686.. currentmodule:: flask.cli687688.. autoclass:: FlaskGroup689 :members:690691.. autoclass:: AppGroup692 :members:693694.. autoclass:: ScriptInfo695 :members:696697.. autofunction:: load_dotenv698699.. autofunction:: with_appcontext700701.. autofunction:: pass_script_info702703 Marks a function so that an instance of :class:`ScriptInfo` is passed704 as first argument to the click callback.705706.. autodata:: run_command707708.. autodata:: shell_command