Skip to content
Myr

api.rst

This file

Path

docs/api.rst

722 lines · 21.3 KiB

Last changed by

Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6

History of this file

Take it

1API2===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_module3334.. 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.Response51    :members:52    :inherited-members:53    :exclude-members: json_module5455Sessions56--------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 :data:`PERMANENT_SESSION_LIFETIME` config can be an integer or ``timedelta``.129    The :attr:`~flask.Flask.permanent_session_lifetime` attribute is always a130    ``timedelta``.131132133Test Client134-----------135136.. currentmodule:: flask.testing137138.. autoclass:: FlaskClient139   :members:140141142Test CLI Runner143---------------144145.. currentmodule:: flask.testing146147.. autoclass:: FlaskCliRunner148    :members:149150151Application Globals152-------------------153154.. currentmodule:: flask155156To share data that is valid for one request only from one function to157another, a global variable is not good enough because it would break in158threaded environments. Flask provides you with a special object that159ensures it is only valid for the active request and that will return160different values for each request. In a nutshell: it does the right161thing, like it does for :class:`request` and :class:`session`.162163.. data:: g164165    A namespace object that can store data during an166    :doc:`application context </appcontext>`. This is an instance of167    :attr:`Flask.app_ctx_globals_class`, which defaults to168    :class:`ctx._AppCtxGlobals`.169170    This is a good place to store resources during a request. For171    example, a ``before_request`` function could load a user object from172    a session id, then set ``g.user`` to be used in the view function.173174    This is a proxy. See :ref:`notes-on-proxies` for more information.175176    .. versionchanged:: 0.10177        Bound to the application context instead of the request context.178179.. autoclass:: flask.ctx._AppCtxGlobals180    :members:181182183Useful Functions and Classes184----------------------------185186.. data:: current_app187188    A proxy to the application handling the current request. This is189    useful to access the application without needing to import it, or if190    it can't be imported, such as when using the application factory191    pattern or in blueprints and extensions.192193    This is only available when an194    :doc:`application context </appcontext>` is pushed. This happens195    automatically during requests and CLI commands. It can be controlled196    manually with :meth:`~flask.Flask.app_context`.197198    This is a proxy. See :ref:`notes-on-proxies` for more information.199200.. autofunction:: has_request_context201202.. autofunction:: copy_current_request_context203204.. autofunction:: has_app_context205206.. autofunction:: url_for207208.. autofunction:: abort209210.. autofunction:: redirect211212.. autofunction:: make_response213214.. autofunction:: after_this_request215216.. autofunction:: send_file217218.. autofunction:: send_from_directory219220221Message Flashing222----------------223224.. autofunction:: flash225226.. autofunction:: get_flashed_messages227228229JSON Support230------------231232.. module:: flask.json233234Flask uses Python's built-in :mod:`json` module for handling JSON by235default. The JSON implementation can be changed by assigning a different236provider to :attr:`flask.Flask.json_provider_class` or237:attr:`flask.Flask.json`. The functions provided by ``flask.json`` will238use methods on ``app.json`` if an app context is active.239240Jinja's ``|tojson`` filter is configured to use the app's JSON provider.241The filter marks the output with ``|safe``. Use it to render data inside242HTML ``<script>`` tags.243244.. sourcecode:: html+jinja245246    <script>247        const names = {{ names|tojson }};248        renderChart(names, {{ axis_data|tojson }});249    </script>250251.. autofunction:: jsonify252253.. autofunction:: dumps254255.. autofunction:: dump256257.. autofunction:: loads258259.. autofunction:: load260261.. autoclass:: flask.json.provider.JSONProvider262    :members:263    :member-order: bysource264265.. autoclass:: flask.json.provider.DefaultJSONProvider266    :members:267    :member-order: bysource268269.. automodule:: flask.json.tag270271272Template Rendering273------------------274275.. currentmodule:: flask276277.. autofunction:: render_template278279.. autofunction:: render_template_string280281.. autofunction:: stream_template282283.. autofunction:: stream_template_string284285.. autofunction:: get_template_attribute286287Configuration288-------------289290.. autoclass:: Config291   :members:292293294Stream Helpers295--------------296297.. autofunction:: stream_with_context298299Useful Internals300----------------301302.. autoclass:: flask.ctx.RequestContext303   :members:304305.. data:: flask.globals.request_ctx306307    The current :class:`~flask.ctx.RequestContext`. If a request context308    is not active, accessing attributes on this proxy will raise a309    ``RuntimeError``.310311    This is an internal object that is essential to how Flask handles312    requests. Accessing this should not be needed in most cases. Most313    likely you want :data:`request` and :data:`session` instead.314315.. autoclass:: flask.ctx.AppContext316   :members:317318.. data:: flask.globals.app_ctx319320    The current :class:`~flask.ctx.AppContext`. If an app context is not321    active, accessing attributes on this proxy will raise a322    ``RuntimeError``.323324    This is an internal object that is essential to how Flask handles325    requests. Accessing this should not be needed in most cases. Most326    likely you want :data:`current_app` and :data:`g` instead.327328.. autoclass:: flask.blueprints.BlueprintSetupState329   :members:330331.. _core-signals-list:332333Signals334-------335336Signals are provided by the `Blinker`_ library. See :doc:`signals` for an introduction.337338.. _blinker: https://blinker.readthedocs.io/339340.. data:: template_rendered341342   This signal is sent when a template was successfully rendered. The343   signal is invoked with the instance of the template as `template`344   and the context as dictionary (named `context`).345346   Example subscriber::347348        def log_template_renders(sender, template, context, **extra):349            sender.logger.debug('Rendering template "%s" with context %s',350                                template.name or 'string template',351                                context)352353        from flask import template_rendered354        template_rendered.connect(log_template_renders, app)355356.. data:: flask.before_render_template357   :noindex:358359   This signal is sent before template rendering process. The360   signal is invoked with the instance of the template as `template`361   and the context as dictionary (named `context`).362363   Example subscriber::364365        def log_template_renders(sender, template, context, **extra):366            sender.logger.debug('Rendering template "%s" with context %s',367                                template.name or 'string template',368                                context)369370        from flask import before_render_template371        before_render_template.connect(log_template_renders, app)372373.. data:: request_started374375   This signal is sent when the request context is set up, before376   any request processing happens. Because the request context is already377   bound, the subscriber can access the request with the standard global378   proxies such as :class:`~flask.request`.379380   Example subscriber::381382        def log_request(sender, **extra):383            sender.logger.debug('Request context is set up')384385        from flask import request_started386        request_started.connect(log_request, app)387388.. data:: request_finished389390   This signal is sent right before the response is sent to the client.391   It is passed the response to be sent named `response`.392393   Example subscriber::394395        def log_response(sender, response, **extra):396            sender.logger.debug('Request context is about to close down. '397                                'Response: %s', response)398399        from flask import request_finished400        request_finished.connect(log_response, app)401402.. data:: got_request_exception403404    This signal is sent when an unhandled exception happens during405    request processing, including when debugging. The exception is406    passed to the subscriber as ``exception``.407408    This signal is not sent for409    :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that410    have error handlers registered, unless the exception was raised from411    an error handler.412413    This example shows how to do some extra logging if a theoretical414    ``SecurityException`` was raised:415416    .. code-block:: python417418        from flask import got_request_exception419420        def log_security_exception(sender, exception, **extra):421            if not isinstance(exception, SecurityException):422                return423424            security_logger.exception(425                f"SecurityException at {request.url!r}",426                exc_info=exception,427            )428429        got_request_exception.connect(log_security_exception, app)430431.. data:: request_tearing_down432433   This signal is sent when the request is tearing down. This is always434   called, even if an exception is caused. Currently functions listening435   to this signal are called after the regular teardown handlers, but this436   is not something you can rely on.437438   Example subscriber::439440        def close_db_connection(sender, **extra):441            session.close()442443        from flask import request_tearing_down444        request_tearing_down.connect(close_db_connection, app)445446   As of Flask 0.9, this will also be passed an `exc` keyword argument447   that has a reference to the exception that caused the teardown if448   there was one.449450.. data:: appcontext_tearing_down451452   This signal is sent when the app context is tearing down. This is always453   called, even if an exception is caused. Currently functions listening454   to this signal are called after the regular teardown handlers, but this455   is not something you can rely on.456457   Example subscriber::458459        def close_db_connection(sender, **extra):460            session.close()461462        from flask import appcontext_tearing_down463        appcontext_tearing_down.connect(close_db_connection, app)464465   This will also be passed an `exc` keyword argument that has a reference466   to the exception that caused the teardown if there was one.467468.. data:: appcontext_pushed469470   This signal is sent when an application context is pushed. The sender471   is the application. This is usually useful for unittests in order to472   temporarily hook in information. For instance it can be used to473   set a resource early onto the `g` object.474475   Example usage::476477        from contextlib import contextmanager478        from flask import appcontext_pushed479480        @contextmanager481        def user_set(app, user):482            def handler(sender, **kwargs):483                g.user = user484            with appcontext_pushed.connected_to(handler, app):485                yield486487   And in the testcode::488489        def test_user_me(self):490            with user_set(app, 'john'):491                c = app.test_client()492                resp = c.get('/users/me')493                assert resp.data == 'username=john'494495   .. versionadded:: 0.10496497.. data:: appcontext_popped498499   This signal is sent when an application context is popped. The sender500   is the application. This usually falls in line with the501   :data:`appcontext_tearing_down` signal.502503   .. versionadded:: 0.10504505.. data:: message_flashed506507   This signal is sent when the application is flashing a message. The508   messages is sent as `message` keyword argument and the category as509   `category`.510511   Example subscriber::512513        recorded = []514        def record(sender, message, category, **extra):515            recorded.append((message, category))516517        from flask import message_flashed518        message_flashed.connect(record, app)519520   .. versionadded:: 0.10521522.. data:: signals.signals_available523524    .. deprecated:: 2.3525        Will be removed in Flask 2.4. Signals are always available526527528Class-Based Views529-----------------530531.. versionadded:: 0.7532533.. currentmodule:: None534535.. autoclass:: flask.views.View536   :members:537538.. autoclass:: flask.views.MethodView539   :members:540541.. _url-route-registrations:542543URL Route Registrations544-----------------------545546Generally there are three ways to define rules for the routing system:5475481.  You can use the :meth:`flask.Flask.route` decorator.5492.  You can use the :meth:`flask.Flask.add_url_rule` function.5503.  You can directly access the underlying Werkzeug routing system551    which is exposed as :attr:`flask.Flask.url_map`.552553Variable parts in the route can be specified with angular brackets554(``/user/<username>``). By default a variable part in the URL accepts any555string without a slash however a different converter can be specified as556well by using ``<converter:name>``.557558Variable parts are passed to the view function as keyword arguments.559560The following converters are available:561562=========== ===============================================563`string`    accepts any text without a slash (the default)564`int`       accepts integers565`float`     like `int` but for floating point values566`path`      like the default but also accepts slashes567`any`       matches one of the items provided568`uuid`      accepts UUID strings569=========== ===============================================570571Custom converters can be defined using :attr:`flask.Flask.url_map`.572573Here are some examples::574575    @app.route('/')576    def index():577        pass578579    @app.route('/<username>')580    def show_user(username):581        pass582583    @app.route('/post/<int:post_id>')584    def show_post(post_id):585        pass586587An important detail to keep in mind is how Flask deals with trailing588slashes. The idea is to keep each URL unique so the following rules589apply:5905911. If a rule ends with a slash and is requested without a slash by the592   user, the user is automatically redirected to the same page with a593   trailing slash attached.5942. If a rule does not end with a trailing slash and the user requests the595   page with a trailing slash, a 404 not found is raised.596597This is consistent with how web servers deal with static files. This598also makes it possible to use relative link targets safely.599600You can also define multiple rules for the same function. They have to be601unique however. Defaults can also be specified. Here for example is a602definition for a URL that accepts an optional page::603604    @app.route('/users/', defaults={'page': 1})605    @app.route('/users/page/<int:page>')606    def show_users(page):607        pass608609This specifies that ``/users/`` will be the URL for page one and610``/users/page/N`` will be the URL for page ``N``.611612If a URL contains a default value, it will be redirected to its simpler613form with a 301 redirect. In the above example, ``/users/page/1`` will614be redirected to ``/users/``. If your route handles ``GET`` and ``POST``615requests, make sure the default route only handles ``GET``, as redirects616can't preserve form data. ::617618   @app.route('/region/', defaults={'id': 1})619   @app.route('/region/<int:id>', methods=['GET', 'POST'])620   def region(id):621      pass622623Here are the parameters that :meth:`~flask.Flask.route` and624:meth:`~flask.Flask.add_url_rule` accept. The only difference is that625with the route parameter the view function is defined with the decorator626instead of the `view_func` parameter.627628=============== ==========================================================629`rule`          the URL rule as string630`endpoint`      the endpoint for the registered URL rule. Flask itself631                assumes that the name of the view function is the name632                of the endpoint if not explicitly stated.633`view_func`     the function to call when serving a request to the634                provided endpoint. If this is not provided one can635                specify the function later by storing it in the636                :attr:`~flask.Flask.view_functions` dictionary with the637                endpoint as key.638`defaults`      A dictionary with defaults for this rule. See the639                example above for how defaults work.640`subdomain`     specifies the rule for the subdomain in case subdomain641                matching is in use. If not specified the default642                subdomain is assumed.643`**options`     the options to be forwarded to the underlying644                :class:`~werkzeug.routing.Rule` object. A change to645                Werkzeug is handling of method options. methods is a list646                of methods this rule should be limited to (``GET``, ``POST``647                etc.). By default a rule just listens for ``GET`` (and648                implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is649                implicitly added and handled by the standard request650                handling. They have to be specified as keyword arguments.651=============== ==========================================================652653654View Function Options655---------------------656657For internal usage the view functions can have some attributes attached to658customize behavior the view function would normally not have control over.659The following attributes can be provided optionally to either override660some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:661662-   `__name__`: The name of a function is by default used as endpoint. If663    endpoint is provided explicitly this value is used. Additionally this664    will be prefixed with the name of the blueprint by default which665    cannot be customized from the function itself.666667-   `methods`: If methods are not provided when the URL rule is added,668    Flask will look on the view function object itself if a `methods`669    attribute exists. If it does, it will pull the information for the670    methods from there.671672-   `provide_automatic_options`: if this attribute is set Flask will673    either force enable or disable the automatic implementation of the674    HTTP ``OPTIONS`` response. This can be useful when working with675    decorators that want to customize the ``OPTIONS`` response on a per-view676    basis.677678-   `required_methods`: if this attribute is set, Flask will always add679    these methods when registering a URL rule even if the methods were680    explicitly overridden in the ``route()`` call.681682Full example::683684    def index():685        if request.method == 'OPTIONS':686            # custom options handling here687            ...688        return 'Hello World!'689    index.provide_automatic_options = False690    index.methods = ['GET', 'OPTIONS']691692    app.add_url_rule('/', index)693694.. versionadded:: 0.8695   The `provide_automatic_options` functionality was added.696697Command Line Interface698----------------------699700.. currentmodule:: flask.cli701702.. autoclass:: FlaskGroup703   :members:704705.. autoclass:: AppGroup706   :members:707708.. autoclass:: ScriptInfo709   :members:710711.. autofunction:: load_dotenv712713.. autofunction:: with_appcontext714715.. autofunction:: pass_script_info716717   Marks a function so that an instance of :class:`ScriptInfo` is passed718   as first argument to the click callback.719720.. autodata:: run_command721722.. autodata:: shell_command