Skip to content
Myr

api.rst

This file

Path

docs/api.rst

749 lines · 22.3 KiB

Last changed by

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

History of this file

Take it

The walk stopped after 200 commits: lines older than 7a444c5 point at it.

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

lines 1–29why, 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:: Request

Merge pull request #3894 from pallets/update-werkzeugDavid Lordbefore adoption9f7ac04

lines 30–32why, one step back
30 :members:
31 :inherited-members:32 :exclude-members: json_module

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

lines 33–50why, one step back
33
34.. attribute:: request3536 To access incoming request data, you can use the global `request`37 object. Flask parses incoming request data for you and gives you38 access to it through that global object. Internally Flask makes39 sure that you always get the correct data for the active thread if you40 are in a multithreaded environment.4142 This is a proxy. See :ref:`notes-on-proxies` for more information.4344 The request object is an instance of a :class:`~flask.Request`.454647Response Objects48----------------4950.. autoclass:: flask.Response

Merge pull request #3894 from pallets/update-werkzeugDavid Lordbefore adoption9f7ac04

lines 51–53why, one step back
51 :members:
52 :inherited-members:53 :exclude-members: json_module

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

lines 54–170why, one step back
54
55Sessions56--------5758If you have set :attr:`Flask.secret_key` (or configured it from59:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes60it possible to remember information from one request to another. The way Flask61does this is by using a signed cookie. The user can look at the session62contents, but can't modify it unless they know the secret key, so make sure to63set that to something complex and unguessable.6465To access the current session you can use the :class:`session` object:6667.. class:: session6869 The session object works pretty much like an ordinary dict, with the70 difference that it keeps track of modifications.7172 This is a proxy. See :ref:`notes-on-proxies` for more information.7374 The following attributes are interesting:7576 .. attribute:: new7778 ``True`` if the session is new, ``False`` otherwise.7980 .. attribute:: modified8182 ``True`` if the session object detected a modification. Be advised83 that modifications on mutable structures are not picked up84 automatically, in that situation you have to explicitly set the85 attribute to ``True`` yourself. Here an example::8687 # this change is not picked up because a mutable object (here88 # a list) is changed.89 session['objects'].append(42)90 # so mark it as modified yourself91 session.modified = True9293 .. attribute:: permanent9495 If set to ``True`` the session lives for96 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The97 default is 31 days. If set to ``False`` (which is the default) the98 session will be deleted when the user closes the browser.99100101Session Interface102-----------------103104.. versionadded:: 0.8105106The session interface provides a simple way to replace the session107implementation that Flask is using.108109.. currentmodule:: flask.sessions110111.. autoclass:: SessionInterface112 :members:113114.. autoclass:: SecureCookieSessionInterface115 :members:116117.. autoclass:: SecureCookieSession118 :members:119120.. autoclass:: NullSession121 :members:122123.. autoclass:: SessionMixin124 :members:125126.. admonition:: Notice127128 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer129 starting with Flask 0.8. Either catch this down yourself or use130 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the131 app which converts the result to an integer automatically.132133134Test Client135-----------136137.. currentmodule:: flask.testing138139.. autoclass:: FlaskClient140 :members:141142143Test CLI Runner144---------------145146.. currentmodule:: flask.testing147148.. autoclass:: FlaskCliRunner149 :members:150151152Application Globals153-------------------154155.. currentmodule:: flask156157To share data that is valid for one request only from one function to158another, a global variable is not good enough because it would break in159threaded environments. Flask provides you with a special object that160ensures it is only valid for the active request and that will return161different values for each request. In a nutshell: it does the right162thing, like it does for :class:`request` and :class:`session`.163164.. data:: g165166 A namespace object that can store data during an167 :doc:`application context </appcontext>`. This is an instance of168 :attr:`Flask.app_ctx_globals_class`, which defaults to169 :class:`ctx._AppCtxGlobals`.170

Merge branch '2.0.x'David Lordbefore adoptionb6a8ccd

lines 171–173why, one step back
171 This is a good place to store resources during a request. For
172 example, a ``before_request`` function could load a user object from173 a session id, then set ``g.user`` to be used in the view function.

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

lines 174–250why, one step back
174
175 This is a proxy. See :ref:`notes-on-proxies` for more information.176177 .. versionchanged:: 0.10178 Bound to the application context instead of the request context.179180.. autoclass:: flask.ctx._AppCtxGlobals181 :members:182183184Useful Functions and Classes185----------------------------186187.. data:: current_app188189 A proxy to the application handling the current request. This is190 useful to access the application without needing to import it, or if191 it can't be imported, such as when using the application factory192 pattern or in blueprints and extensions.193194 This is only available when an195 :doc:`application context </appcontext>` is pushed. This happens196 automatically during requests and CLI commands. It can be controlled197 manually with :meth:`~flask.Flask.app_context`.198199 This is a proxy. See :ref:`notes-on-proxies` for more information.200201.. autofunction:: has_request_context202203.. autofunction:: copy_current_request_context204205.. autofunction:: has_app_context206207.. autofunction:: url_for208209.. autofunction:: abort210211.. autofunction:: redirect212213.. autofunction:: make_response214215.. autofunction:: after_this_request216217.. autofunction:: send_file218219.. autofunction:: send_from_directory220221.. autofunction:: escape222223.. autoclass:: Markup224 :members: escape, unescape, striptags225226Message Flashing227----------------228229.. autofunction:: flash230231.. autofunction:: get_flashed_messages232233234JSON Support235------------236237.. module:: flask.json238239Flask uses the built-in :mod:`json` module for handling JSON. It will240use the current blueprint's or application's JSON encoder and decoder241for easier customization. By default it handles some extra data types:242243- :class:`datetime.datetime` and :class:`datetime.date` are serialized244 to :rfc:`822` strings. This is the same as the HTTP date format.245- :class:`uuid.UUID` is serialized to a string.246- :class:`dataclasses.dataclass` is passed to247 :func:`dataclasses.asdict`.248- :class:`~markupsafe.Markup` (or any object with a ``__html__``249 method) will call the ``__html__`` method to get a string.250

Merge pull request #3895 from pallets/jinja-tojsonDavid Lordbefore adoption192f4ae

lines 251–253why, one step back
251Jinja's ``|tojson`` filter is configured to use Flask's :func:`dumps`
252function. The filter marks the output with ``|safe`` automatically. Use253the filter to render data inside ``<script>`` tags.

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

lines 254–256why, one step back
254
255.. sourcecode:: html+jinja256

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9

line 257why, one step back
257 <script>

Merge pull request #3895 from pallets/jinja-tojsonDavid Lordbefore adoption192f4ae

lines 258–259why, one step back
258 const names = {{ names|tosjon }};
259 renderChart(names, {{ axis_data|tojson }});

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

lines 260–289why, one step back
260 </script>
261262.. autofunction:: jsonify263264.. autofunction:: dumps265266.. autofunction:: dump267268.. autofunction:: loads269270.. autofunction:: load271272.. autoclass:: JSONEncoder273 :members:274275.. autoclass:: JSONDecoder276 :members:277278.. automodule:: flask.json.tag279280281Template Rendering282------------------283284.. currentmodule:: flask285286.. autofunction:: render_template287288.. autofunction:: render_template_string289

Merge pull request #4629 from pgjones/generateDavid Lordbefore adoptionab36542

lines 290–293why, one step back
290.. autofunction:: stream_template
291292.. autofunction:: stream_template_string293

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

lines 294–313why, one step back
294.. autofunction:: get_template_attribute
295296Configuration297-------------298299.. autoclass:: Config300 :members:301302303Stream Helpers304--------------305306.. autofunction:: stream_with_context307308Useful Internals309----------------310311.. autoclass:: flask.ctx.RequestContext312 :members:313

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

line 314why, one step back
314.. data:: flask.globals.request_ctx

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

line 315why, one step back
315

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 316–318why, one step back
316 The current :class:`~flask.ctx.RequestContext`. If a request context
317 is not active, accessing attributes on this proxy will raise a318 ``RuntimeError``.

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

line 319why, one step back
319

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 320–322why, one step back
320 This is an internal object that is essential to how Flask handles
321 requests. Accessing this should not be needed in most cases. Most322 likely you want :data:`request` and :data:`session` instead.

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

lines 323–326why, one step back
323
324.. autoclass:: flask.ctx.AppContext325 :members:326

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

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

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

line 328why, one step back
328

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 329–331why, one step back
329 The current :class:`~flask.ctx.AppContext`. If an app context is not
330 active, accessing attributes on this proxy will raise a331 ``RuntimeError``.

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

line 332why, one step back
332

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

lines 333–335why, one step back
333 This is an internal object that is essential to how Flask handles
334 requests. Accessing this should not be needed in most cases. Most335 likely you want :data:`current_app` and :data:`g` instead.

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

lines 336–417why, one step back
336
337.. autoclass:: flask.blueprints.BlueprintSetupState338 :members:339340.. _core-signals-list:341342Signals343-------344345.. versionadded:: 0.6346347.. data:: signals.signals_available348349 ``True`` if the signaling system is available. This is the case350 when `blinker`_ is installed.351352The following signals exist in Flask:353354.. data:: template_rendered355356 This signal is sent when a template was successfully rendered. The357 signal is invoked with the instance of the template as `template`358 and the context as dictionary (named `context`).359360 Example subscriber::361362 def log_template_renders(sender, template, context, **extra):363 sender.logger.debug('Rendering template "%s" with context %s',364 template.name or 'string template',365 context)366367 from flask import template_rendered368 template_rendered.connect(log_template_renders, app)369370.. data:: flask.before_render_template371 :noindex:372373 This signal is sent before template rendering process. The374 signal is invoked with the instance of the template as `template`375 and the context as dictionary (named `context`).376377 Example subscriber::378379 def log_template_renders(sender, template, context, **extra):380 sender.logger.debug('Rendering template "%s" with context %s',381 template.name or 'string template',382 context)383384 from flask import before_render_template385 before_render_template.connect(log_template_renders, app)386387.. data:: request_started388389 This signal is sent when the request context is set up, before390 any request processing happens. Because the request context is already391 bound, the subscriber can access the request with the standard global392 proxies such as :class:`~flask.request`.393394 Example subscriber::395396 def log_request(sender, **extra):397 sender.logger.debug('Request context is set up')398399 from flask import request_started400 request_started.connect(log_request, app)401402.. data:: request_finished403404 This signal is sent right before the response is sent to the client.405 It is passed the response to be sent named `response`.406407 Example subscriber::408409 def log_response(sender, response, **extra):410 sender.logger.debug('Request context is about to close down. '411 'Response: %s', response)412413 from flask import request_finished414 request_finished.connect(log_response, app)415416.. data:: got_request_exception417

Merge pull request #3883 from tonydelanuez/clarify-got-request-exceptionDavid Lordbefore adoption15f0fc2

lines 418–420why, one step back
418 This signal is sent when an unhandled exception happens during
419 request processing, including when debugging. The exception is420 passed to the subscriber as ``exception``.

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

line 421why, one step back
421

Merge pull request #3883 from tonydelanuez/clarify-got-request-exceptionDavid Lordbefore adoption15f0fc2

lines 422–425why, one step back
422 This signal is not sent for
423 :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that424 have error handlers registered, unless the exception was raised from425 an error handler.

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

line 426why, one step back
426

Merge pull request #3883 from tonydelanuez/clarify-got-request-exceptionDavid Lordbefore adoption15f0fc2

lines 427–428why, one step back
427 This example shows how to do some extra logging if a theoretical
428 ``SecurityException`` was raised:

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

line 429why, one step back
429

Merge pull request #3883 from tonydelanuez/clarify-got-request-exceptionDavid Lordbefore adoption15f0fc2

lines 430–431why, one step back
430 .. code-block:: python
431

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

line 432why, one step back
432 from flask import got_request_exception

Merge pull request #3883 from tonydelanuez/clarify-got-request-exceptionDavid Lordbefore adoption15f0fc2

lines 433–443why, one step back
433
434 def log_security_exception(sender, exception, **extra):435 if not isinstance(exception, SecurityException):436 return437438 security_logger.exception(439 f"SecurityException at {request.url!r}",440 exc_info=exception,441 )442443 got_request_exception.connect(log_security_exception, app)

update tests for new werkzeug client (#3827)David Lordbefore adoption7a444c5

lines 444–749why, one step back
444
445.. data:: request_tearing_down446447 This signal is sent when the request is tearing down. This is always448 called, even if an exception is caused. Currently functions listening449 to this signal are called after the regular teardown handlers, but this450 is not something you can rely on.451452 Example subscriber::453454 def close_db_connection(sender, **extra):455 session.close()456457 from flask import request_tearing_down458 request_tearing_down.connect(close_db_connection, app)459460 As of Flask 0.9, this will also be passed an `exc` keyword argument461 that has a reference to the exception that caused the teardown if462 there was one.463464.. data:: appcontext_tearing_down465466 This signal is sent when the app context is tearing down. This is always467 called, even if an exception is caused. Currently functions listening468 to this signal are called after the regular teardown handlers, but this469 is not something you can rely on.470471 Example subscriber::472473 def close_db_connection(sender, **extra):474 session.close()475476 from flask import appcontext_tearing_down477 appcontext_tearing_down.connect(close_db_connection, app)478479 This will also be passed an `exc` keyword argument that has a reference480 to the exception that caused the teardown if there was one.481482.. data:: appcontext_pushed483484 This signal is sent when an application context is pushed. The sender485 is the application. This is usually useful for unittests in order to486 temporarily hook in information. For instance it can be used to487 set a resource early onto the `g` object.488489 Example usage::490491 from contextlib import contextmanager492 from flask import appcontext_pushed493494 @contextmanager495 def user_set(app, user):496 def handler(sender, **kwargs):497 g.user = user498 with appcontext_pushed.connected_to(handler, app):499 yield500501 And in the testcode::502503 def test_user_me(self):504 with user_set(app, 'john'):505 c = app.test_client()506 resp = c.get('/users/me')507 assert resp.data == 'username=john'508509 .. versionadded:: 0.10510511.. data:: appcontext_popped512513 This signal is sent when an application context is popped. The sender514 is the application. This usually falls in line with the515 :data:`appcontext_tearing_down` signal.516517 .. versionadded:: 0.10518519520.. data:: message_flashed521522 This signal is sent when the application is flashing a message. The523 messages is sent as `message` keyword argument and the category as524 `category`.525526 Example subscriber::527528 recorded = []529 def record(sender, message, category, **extra):530 recorded.append((message, category))531532 from flask import message_flashed533 message_flashed.connect(record, app)534535 .. versionadded:: 0.10536537.. class:: signals.Namespace538539 An alias for :class:`blinker.base.Namespace` if blinker is available,540 otherwise a dummy class that creates fake signals. This class is541 available for Flask extensions that want to provide the same fallback542 system as Flask itself.543544 .. method:: signal(name, doc=None)545546 Creates a new signal for this namespace if blinker is available,547 otherwise returns a fake signal that has a send method that will548 do nothing but will fail with a :exc:`RuntimeError` for all other549 operations, including connecting.550551552.. _blinker: https://pypi.org/project/blinker/553554555Class-Based Views556-----------------557558.. versionadded:: 0.7559560.. currentmodule:: None561562.. autoclass:: flask.views.View563 :members:564565.. autoclass:: flask.views.MethodView566 :members:567568.. _url-route-registrations:569570URL Route Registrations571-----------------------572573Generally there are three ways to define rules for the routing system:5745751. You can use the :meth:`flask.Flask.route` decorator.5762. You can use the :meth:`flask.Flask.add_url_rule` function.5773. You can directly access the underlying Werkzeug routing system578 which is exposed as :attr:`flask.Flask.url_map`.579580Variable parts in the route can be specified with angular brackets581(``/user/<username>``). By default a variable part in the URL accepts any582string without a slash however a different converter can be specified as583well by using ``<converter:name>``.584585Variable parts are passed to the view function as keyword arguments.586587The following converters are available:588589=========== ===============================================590`string` accepts any text without a slash (the default)591`int` accepts integers592`float` like `int` but for floating point values593`path` like the default but also accepts slashes594`any` matches one of the items provided595`uuid` accepts UUID strings596=========== ===============================================597598Custom converters can be defined using :attr:`flask.Flask.url_map`.599600Here are some examples::601602 @app.route('/')603 def index():604 pass605606 @app.route('/<username>')607 def show_user(username):608 pass609610 @app.route('/post/<int:post_id>')611 def show_post(post_id):612 pass613614An important detail to keep in mind is how Flask deals with trailing615slashes. The idea is to keep each URL unique so the following rules616apply:6176181. If a rule ends with a slash and is requested without a slash by the619 user, the user is automatically redirected to the same page with a620 trailing slash attached.6212. If a rule does not end with a trailing slash and the user requests the622 page with a trailing slash, a 404 not found is raised.623624This is consistent with how web servers deal with static files. This625also makes it possible to use relative link targets safely.626627You can also define multiple rules for the same function. They have to be628unique however. Defaults can also be specified. Here for example is a629definition for a URL that accepts an optional page::630631 @app.route('/users/', defaults={'page': 1})632 @app.route('/users/page/<int:page>')633 def show_users(page):634 pass635636This specifies that ``/users/`` will be the URL for page one and637``/users/page/N`` will be the URL for page ``N``.638639If a URL contains a default value, it will be redirected to its simpler640form with a 301 redirect. In the above example, ``/users/page/1`` will641be redirected to ``/users/``. If your route handles ``GET`` and ``POST``642requests, make sure the default route only handles ``GET``, as redirects643can't preserve form data. ::644645 @app.route('/region/', defaults={'id': 1})646 @app.route('/region/<int:id>', methods=['GET', 'POST'])647 def region(id):648 pass649650Here are the parameters that :meth:`~flask.Flask.route` and651:meth:`~flask.Flask.add_url_rule` accept. The only difference is that652with the route parameter the view function is defined with the decorator653instead of the `view_func` parameter.654655=============== ==========================================================656`rule` the URL rule as string657`endpoint` the endpoint for the registered URL rule. Flask itself658 assumes that the name of the view function is the name659 of the endpoint if not explicitly stated.660`view_func` the function to call when serving a request to the661 provided endpoint. If this is not provided one can662 specify the function later by storing it in the663 :attr:`~flask.Flask.view_functions` dictionary with the664 endpoint as key.665`defaults` A dictionary with defaults for this rule. See the666 example above for how defaults work.667`subdomain` specifies the rule for the subdomain in case subdomain668 matching is in use. If not specified the default669 subdomain is assumed.670`**options` the options to be forwarded to the underlying671 :class:`~werkzeug.routing.Rule` object. A change to672 Werkzeug is handling of method options. methods is a list673 of methods this rule should be limited to (``GET``, ``POST``674 etc.). By default a rule just listens for ``GET`` (and675 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is676 implicitly added and handled by the standard request677 handling. They have to be specified as keyword arguments.678=============== ==========================================================679680681View Function Options682---------------------683684For internal usage the view functions can have some attributes attached to685customize behavior the view function would normally not have control over.686The following attributes can be provided optionally to either override687some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:688689- `__name__`: The name of a function is by default used as endpoint. If690 endpoint is provided explicitly this value is used. Additionally this691 will be prefixed with the name of the blueprint by default which692 cannot be customized from the function itself.693694- `methods`: If methods are not provided when the URL rule is added,695 Flask will look on the view function object itself if a `methods`696 attribute exists. If it does, it will pull the information for the697 methods from there.698699- `provide_automatic_options`: if this attribute is set Flask will700 either force enable or disable the automatic implementation of the701 HTTP ``OPTIONS`` response. This can be useful when working with702 decorators that want to customize the ``OPTIONS`` response on a per-view703 basis.704705- `required_methods`: if this attribute is set, Flask will always add706 these methods when registering a URL rule even if the methods were707 explicitly overridden in the ``route()`` call.708709Full example::710711 def index():712 if request.method == 'OPTIONS':713 # custom options handling here714 ...715 return 'Hello World!'716 index.provide_automatic_options = False717 index.methods = ['GET', 'OPTIONS']718719 app.add_url_rule('/', index)720721.. versionadded:: 0.8722 The `provide_automatic_options` functionality was added.723724Command Line Interface725----------------------726727.. currentmodule:: flask.cli728729.. autoclass:: FlaskGroup730 :members:731732.. autoclass:: AppGroup733 :members:734735.. autoclass:: ScriptInfo736 :members:737738.. autofunction:: load_dotenv739740.. autofunction:: with_appcontext741742.. autofunction:: pass_script_info743744 Marks a function so that an instance of :class:`ScriptInfo` is passed745 as first argument to the click callback.746747.. autodata:: run_command748749.. autodata:: shell_command