Skip to content
Myr

api.rst

This file

Path

docs/api.rst

771 lines · 22.5 KiB

Last changed by

Merge pull request #3673 from stat1c-void/pr-api.rst-request-link-20200702David Lordbefore adoption47e165d

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: set_cookie, max_cookie_size, data, mimetype, is_json, get_json5253   .. attribute:: headers5455      A :class:`~werkzeug.datastructures.Headers` object representing the response headers.5657   .. attribute:: status5859      A string with a response status.6061   .. attribute:: status_code6263      The response status as integer.646566Sessions67--------6869If you have set :attr:`Flask.secret_key` (or configured it from70:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes71it possible to remember information from one request to another. The way Flask72does this is by using a signed cookie. The user can look at the session73contents, but can't modify it unless they know the secret key, so make sure to74set that to something complex and unguessable.7576To access the current session you can use the :class:`session` object:7778.. class:: session7980   The session object works pretty much like an ordinary dict, with the81   difference that it keeps track of modifications.8283   This is a proxy.  See :ref:`notes-on-proxies` for more information.8485   The following attributes are interesting:8687   .. attribute:: new8889      ``True`` if the session is new, ``False`` otherwise.9091   .. attribute:: modified9293      ``True`` if the session object detected a modification.  Be advised94      that modifications on mutable structures are not picked up95      automatically, in that situation you have to explicitly set the96      attribute to ``True`` yourself.  Here an example::9798          # this change is not picked up because a mutable object (here99          # a list) is changed.100          session['objects'].append(42)101          # so mark it as modified yourself102          session.modified = True103104   .. attribute:: permanent105106      If set to ``True`` the session lives for107      :attr:`~flask.Flask.permanent_session_lifetime` seconds.  The108      default is 31 days.  If set to ``False`` (which is the default) the109      session will be deleted when the user closes the browser.110111112Session Interface113-----------------114115.. versionadded:: 0.8116117The session interface provides a simple way to replace the session118implementation that Flask is using.119120.. currentmodule:: flask.sessions121122.. autoclass:: SessionInterface123   :members:124125.. autoclass:: SecureCookieSessionInterface126   :members:127128.. autoclass:: SecureCookieSession129   :members:130131.. autoclass:: NullSession132   :members:133134.. autoclass:: SessionMixin135   :members:136137.. admonition:: Notice138139   The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer140   starting with Flask 0.8.  Either catch this down yourself or use141   the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the142   app which converts the result to an integer automatically.143144145Test Client146-----------147148.. currentmodule:: flask.testing149150.. autoclass:: FlaskClient151   :members:152153154Test CLI Runner155---------------156157.. currentmodule:: flask.testing158159.. autoclass:: FlaskCliRunner160    :members:161162163Application Globals164-------------------165166.. currentmodule:: flask167168To share data that is valid for one request only from one function to169another, a global variable is not good enough because it would break in170threaded environments.  Flask provides you with a special object that171ensures it is only valid for the active request and that will return172different values for each request.  In a nutshell: it does the right173thing, like it does for :class:`request` and :class:`session`.174175.. data:: g176177    A namespace object that can store data during an178    :doc:`application context </appcontext>`. This is an instance of179    :attr:`Flask.app_ctx_globals_class`, which defaults to180    :class:`ctx._AppCtxGlobals`.181182    This is a good place to store resources during a request. During183    testing, you can use the :ref:`faking-resources` pattern to184    pre-configure such resources.185186    This is a proxy. See :ref:`notes-on-proxies` for more information.187188    .. versionchanged:: 0.10189        Bound to the application context instead of the request context.190191.. autoclass:: flask.ctx._AppCtxGlobals192    :members:193194195Useful Functions and Classes196----------------------------197198.. data:: current_app199200    A proxy to the application handling the current request. This is201    useful to access the application without needing to import it, or if202    it can't be imported, such as when using the application factory203    pattern or in blueprints and extensions.204205    This is only available when an206    :doc:`application context </appcontext>` is pushed. This happens207    automatically during requests and CLI commands. It can be controlled208    manually with :meth:`~flask.Flask.app_context`.209210    This is a proxy. See :ref:`notes-on-proxies` for more information.211212.. autofunction:: has_request_context213214.. autofunction:: copy_current_request_context215216.. autofunction:: has_app_context217218.. autofunction:: url_for219220.. autofunction:: abort221222.. autofunction:: redirect223224.. autofunction:: make_response225226.. autofunction:: after_this_request227228.. autofunction:: send_file229230.. autofunction:: send_from_directory231232.. autofunction:: safe_join233234.. autofunction:: escape235236.. autoclass:: Markup237   :members: escape, unescape, striptags238239Message Flashing240----------------241242.. autofunction:: flash243244.. autofunction:: get_flashed_messages245246247JSON Support248------------249250.. module:: flask.json251252Flask uses the built-in :mod:`json` module for handling JSON. It will253use the current blueprint's or application's JSON encoder and decoder254for easier customization. By default it handles some extra data types:255256-   :class:`datetime.datetime` and :class:`datetime.date` are serialized257    to :rfc:`822` strings. This is the same as the HTTP date format.258-   :class:`uuid.UUID` is serialized to a string.259-   :class:`dataclasses.dataclass` is passed to260    :func:`dataclasses.asdict`.261-   :class:`~markupsafe.Markup` (or any object with a ``__html__``262    method) will call the ``__html__`` method to get a string.263264:func:`~htmlsafe_dumps` is also available as the ``|tojson`` template265filter. The filter marks the output with ``|safe`` so it can be used266inside ``script`` tags.267268.. sourcecode:: html+jinja269270    <script type=text/javascript>271        renderChart({{ axis_data|tojson }});272    </script>273274.. autofunction:: jsonify275276.. autofunction:: dumps277278.. autofunction:: dump279280.. autofunction:: loads281282.. autofunction:: load283284.. autoclass:: JSONEncoder285   :members:286287.. autoclass:: JSONDecoder288   :members:289290.. automodule:: flask.json.tag291292293Template Rendering294------------------295296.. currentmodule:: flask297298.. autofunction:: render_template299300.. autofunction:: render_template_string301302.. autofunction:: get_template_attribute303304Configuration305-------------306307.. autoclass:: Config308   :members:309310311Stream Helpers312--------------313314.. autofunction:: stream_with_context315316Useful Internals317----------------318319.. autoclass:: flask.ctx.RequestContext320   :members:321322.. data:: _request_ctx_stack323324    The internal :class:`~werkzeug.local.LocalStack` that holds325    :class:`~flask.ctx.RequestContext` instances. Typically, the326    :data:`request` and :data:`session` proxies should be accessed327    instead of the stack. It may be useful to access the stack in328    extension code.329330    The following attributes are always present on each layer of the331    stack:332333    `app`334      the active Flask application.335336    `url_adapter`337      the URL adapter that was used to match the request.338339    `request`340      the current request object.341342    `session`343      the active session object.344345    `g`346      an object with all the attributes of the :data:`flask.g` object.347348    `flashes`349      an internal cache for the flashed messages.350351    Example usage::352353        from flask import _request_ctx_stack354355        def get_session():356            ctx = _request_ctx_stack.top357            if ctx is not None:358                return ctx.session359360.. autoclass:: flask.ctx.AppContext361   :members:362363.. data:: _app_ctx_stack364365    The internal :class:`~werkzeug.local.LocalStack` that holds366    :class:`~flask.ctx.AppContext` instances. Typically, the367    :data:`current_app` and :data:`g` proxies should be accessed instead368    of the stack. Extensions can access the contexts on the stack as a369    namespace to store data.370371    .. versionadded:: 0.9372373.. autoclass:: flask.blueprints.BlueprintSetupState374   :members:375376.. _core-signals-list:377378Signals379-------380381.. versionadded:: 0.6382383.. data:: signals.signals_available384385   ``True`` if the signaling system is available.  This is the case386   when `blinker`_ is installed.387388The following signals exist in Flask:389390.. data:: template_rendered391392   This signal is sent when a template was successfully rendered.  The393   signal is invoked with the instance of the template as `template`394   and the context as dictionary (named `context`).395396   Example subscriber::397398        def log_template_renders(sender, template, context, **extra):399            sender.logger.debug('Rendering template "%s" with context %s',400                                template.name or 'string template',401                                context)402403        from flask import template_rendered404        template_rendered.connect(log_template_renders, app)405406.. data:: flask.before_render_template407   :noindex:408409   This signal is sent before template rendering process. The410   signal is invoked with the instance of the template as `template`411   and the context as dictionary (named `context`).412413   Example subscriber::414415        def log_template_renders(sender, template, context, **extra):416            sender.logger.debug('Rendering template "%s" with context %s',417                                template.name or 'string template',418                                context)419420        from flask import before_render_template421        before_render_template.connect(log_template_renders, app)422423.. data:: request_started424425   This signal is sent when the request context is set up, before426   any request processing happens.  Because the request context is already427   bound, the subscriber can access the request with the standard global428   proxies such as :class:`~flask.request`.429430   Example subscriber::431432        def log_request(sender, **extra):433            sender.logger.debug('Request context is set up')434435        from flask import request_started436        request_started.connect(log_request, app)437438.. data:: request_finished439440   This signal is sent right before the response is sent to the client.441   It is passed the response to be sent named `response`.442443   Example subscriber::444445        def log_response(sender, response, **extra):446            sender.logger.debug('Request context is about to close down.  '447                                'Response: %s', response)448449        from flask import request_finished450        request_finished.connect(log_response, app)451452.. data:: got_request_exception453454   This signal is sent when an exception happens during request processing.455   It is sent *before* the standard exception handling kicks in and even456   in debug mode, where no exception handling happens.  The exception457   itself is passed to the subscriber as `exception`.458459   Example subscriber::460461        def log_exception(sender, exception, **extra):462            sender.logger.debug('Got exception during processing: %s', exception)463464        from flask import got_request_exception465        got_request_exception.connect(log_exception, app)466467.. data:: request_tearing_down468469   This signal is sent when the request is tearing down.  This is always470   called, even if an exception is caused.  Currently functions listening471   to this signal are called after the regular teardown handlers, but this472   is not something you can rely on.473474   Example subscriber::475476        def close_db_connection(sender, **extra):477            session.close()478479        from flask import request_tearing_down480        request_tearing_down.connect(close_db_connection, app)481482   As of Flask 0.9, this will also be passed an `exc` keyword argument483   that has a reference to the exception that caused the teardown if484   there was one.485486.. data:: appcontext_tearing_down487488   This signal is sent when the app context is tearing down.  This is always489   called, even if an exception is caused.  Currently functions listening490   to this signal are called after the regular teardown handlers, but this491   is not something you can rely on.492493   Example subscriber::494495        def close_db_connection(sender, **extra):496            session.close()497498        from flask import appcontext_tearing_down499        appcontext_tearing_down.connect(close_db_connection, app)500501   This will also be passed an `exc` keyword argument that has a reference502   to the exception that caused the teardown if there was one.503504.. data:: appcontext_pushed505506   This signal is sent when an application context is pushed.  The sender507   is the application.  This is usually useful for unittests in order to508   temporarily hook in information.  For instance it can be used to509   set a resource early onto the `g` object.510511   Example usage::512513        from contextlib import contextmanager514        from flask import appcontext_pushed515516        @contextmanager517        def user_set(app, user):518            def handler(sender, **kwargs):519                g.user = user520            with appcontext_pushed.connected_to(handler, app):521                yield522523   And in the testcode::524525        def test_user_me(self):526            with user_set(app, 'john'):527                c = app.test_client()528                resp = c.get('/users/me')529                assert resp.data == 'username=john'530531   .. versionadded:: 0.10532533.. data:: appcontext_popped534535   This signal is sent when an application context is popped.  The sender536   is the application.  This usually falls in line with the537   :data:`appcontext_tearing_down` signal.538539   .. versionadded:: 0.10540541542.. data:: message_flashed543544   This signal is sent when the application is flashing a message.  The545   messages is sent as `message` keyword argument and the category as546   `category`.547548   Example subscriber::549550        recorded = []551        def record(sender, message, category, **extra):552            recorded.append((message, category))553554        from flask import message_flashed555        message_flashed.connect(record, app)556557   .. versionadded:: 0.10558559.. class:: signals.Namespace560561   An alias for :class:`blinker.base.Namespace` if blinker is available,562   otherwise a dummy class that creates fake signals.  This class is563   available for Flask extensions that want to provide the same fallback564   system as Flask itself.565566   .. method:: signal(name, doc=None)567568      Creates a new signal for this namespace if blinker is available,569      otherwise returns a fake signal that has a send method that will570      do nothing but will fail with a :exc:`RuntimeError` for all other571      operations, including connecting.572573574.. _blinker: https://pypi.org/project/blinker/575576577Class-Based Views578-----------------579580.. versionadded:: 0.7581582.. currentmodule:: None583584.. autoclass:: flask.views.View585   :members:586587.. autoclass:: flask.views.MethodView588   :members:589590.. _url-route-registrations:591592URL Route Registrations593-----------------------594595Generally there are three ways to define rules for the routing system:5965971.  You can use the :meth:`flask.Flask.route` decorator.5982.  You can use the :meth:`flask.Flask.add_url_rule` function.5993.  You can directly access the underlying Werkzeug routing system600    which is exposed as :attr:`flask.Flask.url_map`.601602Variable parts in the route can be specified with angular brackets603(``/user/<username>``).  By default a variable part in the URL accepts any604string without a slash however a different converter can be specified as605well by using ``<converter:name>``.606607Variable parts are passed to the view function as keyword arguments.608609The following converters are available:610611=========== ===============================================612`string`    accepts any text without a slash (the default)613`int`       accepts integers614`float`     like `int` but for floating point values615`path`      like the default but also accepts slashes616`any`       matches one of the items provided617`uuid`      accepts UUID strings618=========== ===============================================619620Custom converters can be defined using :attr:`flask.Flask.url_map`.621622Here are some examples::623624    @app.route('/')625    def index():626        pass627628    @app.route('/<username>')629    def show_user(username):630        pass631632    @app.route('/post/<int:post_id>')633    def show_post(post_id):634        pass635636An important detail to keep in mind is how Flask deals with trailing637slashes.  The idea is to keep each URL unique so the following rules638apply:6396401. If a rule ends with a slash and is requested without a slash by the641   user, the user is automatically redirected to the same page with a642   trailing slash attached.6432. If a rule does not end with a trailing slash and the user requests the644   page with a trailing slash, a 404 not found is raised.645646This is consistent with how web servers deal with static files.  This647also makes it possible to use relative link targets safely.648649You can also define multiple rules for the same function.  They have to be650unique however.  Defaults can also be specified.  Here for example is a651definition for a URL that accepts an optional page::652653    @app.route('/users/', defaults={'page': 1})654    @app.route('/users/page/<int:page>')655    def show_users(page):656        pass657658This specifies that ``/users/`` will be the URL for page one and659``/users/page/N`` will be the URL for page ``N``.660661If a URL contains a default value, it will be redirected to its simpler662form with a 301 redirect. In the above example, ``/users/page/1`` will663be redirected to ``/users/``. If your route handles ``GET`` and ``POST``664requests, make sure the default route only handles ``GET``, as redirects665can't preserve form data. ::666667   @app.route('/region/', defaults={'id': 1})668   @app.route('/region/<int:id>', methods=['GET', 'POST'])669   def region(id):670      pass671672Here are the parameters that :meth:`~flask.Flask.route` and673:meth:`~flask.Flask.add_url_rule` accept.  The only difference is that674with the route parameter the view function is defined with the decorator675instead of the `view_func` parameter.676677=============== ==========================================================678`rule`          the URL rule as string679`endpoint`      the endpoint for the registered URL rule.  Flask itself680                assumes that the name of the view function is the name681                of the endpoint if not explicitly stated.682`view_func`     the function to call when serving a request to the683                provided endpoint.  If this is not provided one can684                specify the function later by storing it in the685                :attr:`~flask.Flask.view_functions` dictionary with the686                endpoint as key.687`defaults`      A dictionary with defaults for this rule.  See the688                example above for how defaults work.689`subdomain`     specifies the rule for the subdomain in case subdomain690                matching is in use.  If not specified the default691                subdomain is assumed.692`**options`     the options to be forwarded to the underlying693                :class:`~werkzeug.routing.Rule` object.  A change to694                Werkzeug is handling of method options.  methods is a list695                of methods this rule should be limited to (``GET``, ``POST``696                etc.).  By default a rule just listens for ``GET`` (and697                implicitly ``HEAD``).  Starting with Flask 0.6, ``OPTIONS`` is698                implicitly added and handled by the standard request699                handling.  They have to be specified as keyword arguments.700=============== ==========================================================701702703View Function Options704---------------------705706For internal usage the view functions can have some attributes attached to707customize behavior the view function would normally not have control over.708The following attributes can be provided optionally to either override709some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:710711-   `__name__`: The name of a function is by default used as endpoint.  If712    endpoint is provided explicitly this value is used.  Additionally this713    will be prefixed with the name of the blueprint by default which714    cannot be customized from the function itself.715716-   `methods`: If methods are not provided when the URL rule is added,717    Flask will look on the view function object itself if a `methods`718    attribute exists.  If it does, it will pull the information for the719    methods from there.720721-   `provide_automatic_options`: if this attribute is set Flask will722    either force enable or disable the automatic implementation of the723    HTTP ``OPTIONS`` response.  This can be useful when working with724    decorators that want to customize the ``OPTIONS`` response on a per-view725    basis.726727-   `required_methods`: if this attribute is set, Flask will always add728    these methods when registering a URL rule even if the methods were729    explicitly overridden in the ``route()`` call.730731Full example::732733    def index():734        if request.method == 'OPTIONS':735            # custom options handling here736            ...737        return 'Hello World!'738    index.provide_automatic_options = False739    index.methods = ['GET', 'OPTIONS']740741    app.add_url_rule('/', index)742743.. versionadded:: 0.8744   The `provide_automatic_options` functionality was added.745746Command Line Interface747----------------------748749.. currentmodule:: flask.cli750751.. autoclass:: FlaskGroup752   :members:753754.. autoclass:: AppGroup755   :members:756757.. autoclass:: ScriptInfo758   :members:759760.. autofunction:: load_dotenv761762.. autofunction:: with_appcontext763764.. autofunction:: pass_script_info765766   Marks a function so that an instance of :class:`ScriptInfo` is passed767   as first argument to the click callback.768769.. autodata:: run_command770771.. autodata:: shell_command