Skip to content
Myr

api.rst

This file

Path

docs/api.rst

760 lines · 22.3 KiB

Last changed by

remove JSONMixinDavid Lordbefore adoptionfdba0d2

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 ``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`.170171    This is a good place to store resources during a request. During172    testing, you can use the :ref:`faking-resources` pattern to173    pre-configure such resources.174175    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:: safe_join222223.. autofunction:: escape224225.. autoclass:: Markup226   :members: escape, unescape, striptags227228Message Flashing229----------------230231.. autofunction:: flash232233.. autofunction:: get_flashed_messages234235236JSON Support237------------238239.. module:: flask.json240241Flask uses the built-in :mod:`json` module for handling JSON. It will242use the current blueprint's or application's JSON encoder and decoder243for easier customization. By default it handles some extra data types:244245-   :class:`datetime.datetime` and :class:`datetime.date` are serialized246    to :rfc:`822` strings. This is the same as the HTTP date format.247-   :class:`uuid.UUID` is serialized to a string.248-   :class:`dataclasses.dataclass` is passed to249    :func:`dataclasses.asdict`.250-   :class:`~markupsafe.Markup` (or any object with a ``__html__``251    method) will call the ``__html__`` method to get a string.252253:func:`~htmlsafe_dumps` is also available as the ``|tojson`` template254filter. The filter marks the output with ``|safe`` so it can be used255inside ``script`` tags.256257.. sourcecode:: html+jinja258259    <script type=text/javascript>260        renderChart({{ axis_data|tojson }});261    </script>262263.. autofunction:: jsonify264265.. autofunction:: dumps266267.. autofunction:: dump268269.. autofunction:: loads270271.. autofunction:: load272273.. autoclass:: JSONEncoder274   :members:275276.. autoclass:: JSONDecoder277   :members:278279.. automodule:: flask.json.tag280281282Template Rendering283------------------284285.. currentmodule:: flask286287.. autofunction:: render_template288289.. autofunction:: render_template_string290291.. autofunction:: get_template_attribute292293Configuration294-------------295296.. autoclass:: Config297   :members:298299300Stream Helpers301--------------302303.. autofunction:: stream_with_context304305Useful Internals306----------------307308.. autoclass:: flask.ctx.RequestContext309   :members:310311.. data:: _request_ctx_stack312313    The internal :class:`~werkzeug.local.LocalStack` that holds314    :class:`~flask.ctx.RequestContext` instances. Typically, the315    :data:`request` and :data:`session` proxies should be accessed316    instead of the stack. It may be useful to access the stack in317    extension code.318319    The following attributes are always present on each layer of the320    stack:321322    `app`323      the active Flask application.324325    `url_adapter`326      the URL adapter that was used to match the request.327328    `request`329      the current request object.330331    `session`332      the active session object.333334    `g`335      an object with all the attributes of the :data:`flask.g` object.336337    `flashes`338      an internal cache for the flashed messages.339340    Example usage::341342        from flask import _request_ctx_stack343344        def get_session():345            ctx = _request_ctx_stack.top346            if ctx is not None:347                return ctx.session348349.. autoclass:: flask.ctx.AppContext350   :members:351352.. data:: _app_ctx_stack353354    The internal :class:`~werkzeug.local.LocalStack` that holds355    :class:`~flask.ctx.AppContext` instances. Typically, the356    :data:`current_app` and :data:`g` proxies should be accessed instead357    of the stack. Extensions can access the contexts on the stack as a358    namespace to store data.359360    .. versionadded:: 0.9361362.. autoclass:: flask.blueprints.BlueprintSetupState363   :members:364365.. _core-signals-list:366367Signals368-------369370.. versionadded:: 0.6371372.. data:: signals.signals_available373374   ``True`` if the signaling system is available.  This is the case375   when `blinker`_ is installed.376377The following signals exist in Flask:378379.. data:: template_rendered380381   This signal is sent when a template was successfully rendered.  The382   signal is invoked with the instance of the template as `template`383   and the context as dictionary (named `context`).384385   Example subscriber::386387        def log_template_renders(sender, template, context, **extra):388            sender.logger.debug('Rendering template "%s" with context %s',389                                template.name or 'string template',390                                context)391392        from flask import template_rendered393        template_rendered.connect(log_template_renders, app)394395.. data:: flask.before_render_template396   :noindex:397398   This signal is sent before template rendering process. The399   signal is invoked with the instance of the template as `template`400   and the context as dictionary (named `context`).401402   Example subscriber::403404        def log_template_renders(sender, template, context, **extra):405            sender.logger.debug('Rendering template "%s" with context %s',406                                template.name or 'string template',407                                context)408409        from flask import before_render_template410        before_render_template.connect(log_template_renders, app)411412.. data:: request_started413414   This signal is sent when the request context is set up, before415   any request processing happens.  Because the request context is already416   bound, the subscriber can access the request with the standard global417   proxies such as :class:`~flask.request`.418419   Example subscriber::420421        def log_request(sender, **extra):422            sender.logger.debug('Request context is set up')423424        from flask import request_started425        request_started.connect(log_request, app)426427.. data:: request_finished428429   This signal is sent right before the response is sent to the client.430   It is passed the response to be sent named `response`.431432   Example subscriber::433434        def log_response(sender, response, **extra):435            sender.logger.debug('Request context is about to close down.  '436                                'Response: %s', response)437438        from flask import request_finished439        request_finished.connect(log_response, app)440441.. data:: got_request_exception442443   This signal is sent when an exception happens during request processing.444   It is sent *before* the standard exception handling kicks in and even445   in debug mode, where no exception handling happens.  The exception446   itself is passed to the subscriber as `exception`.447448   Example subscriber::449450        def log_exception(sender, exception, **extra):451            sender.logger.debug('Got exception during processing: %s', exception)452453        from flask import got_request_exception454        got_request_exception.connect(log_exception, app)455456.. data:: request_tearing_down457458   This signal is sent when the request is tearing down.  This is always459   called, even if an exception is caused.  Currently functions listening460   to this signal are called after the regular teardown handlers, but this461   is not something you can rely on.462463   Example subscriber::464465        def close_db_connection(sender, **extra):466            session.close()467468        from flask import request_tearing_down469        request_tearing_down.connect(close_db_connection, app)470471   As of Flask 0.9, this will also be passed an `exc` keyword argument472   that has a reference to the exception that caused the teardown if473   there was one.474475.. data:: appcontext_tearing_down476477   This signal is sent when the app context is tearing down.  This is always478   called, even if an exception is caused.  Currently functions listening479   to this signal are called after the regular teardown handlers, but this480   is not something you can rely on.481482   Example subscriber::483484        def close_db_connection(sender, **extra):485            session.close()486487        from flask import appcontext_tearing_down488        appcontext_tearing_down.connect(close_db_connection, app)489490   This will also be passed an `exc` keyword argument that has a reference491   to the exception that caused the teardown if there was one.492493.. data:: appcontext_pushed494495   This signal is sent when an application context is pushed.  The sender496   is the application.  This is usually useful for unittests in order to497   temporarily hook in information.  For instance it can be used to498   set a resource early onto the `g` object.499500   Example usage::501502        from contextlib import contextmanager503        from flask import appcontext_pushed504505        @contextmanager506        def user_set(app, user):507            def handler(sender, **kwargs):508                g.user = user509            with appcontext_pushed.connected_to(handler, app):510                yield511512   And in the testcode::513514        def test_user_me(self):515            with user_set(app, 'john'):516                c = app.test_client()517                resp = c.get('/users/me')518                assert resp.data == 'username=john'519520   .. versionadded:: 0.10521522.. data:: appcontext_popped523524   This signal is sent when an application context is popped.  The sender525   is the application.  This usually falls in line with the526   :data:`appcontext_tearing_down` signal.527528   .. versionadded:: 0.10529530531.. data:: message_flashed532533   This signal is sent when the application is flashing a message.  The534   messages is sent as `message` keyword argument and the category as535   `category`.536537   Example subscriber::538539        recorded = []540        def record(sender, message, category, **extra):541            recorded.append((message, category))542543        from flask import message_flashed544        message_flashed.connect(record, app)545546   .. versionadded:: 0.10547548.. class:: signals.Namespace549550   An alias for :class:`blinker.base.Namespace` if blinker is available,551   otherwise a dummy class that creates fake signals.  This class is552   available for Flask extensions that want to provide the same fallback553   system as Flask itself.554555   .. method:: signal(name, doc=None)556557      Creates a new signal for this namespace if blinker is available,558      otherwise returns a fake signal that has a send method that will559      do nothing but will fail with a :exc:`RuntimeError` for all other560      operations, including connecting.561562563.. _blinker: https://pypi.org/project/blinker/564565566Class-Based Views567-----------------568569.. versionadded:: 0.7570571.. currentmodule:: None572573.. autoclass:: flask.views.View574   :members:575576.. autoclass:: flask.views.MethodView577   :members:578579.. _url-route-registrations:580581URL Route Registrations582-----------------------583584Generally there are three ways to define rules for the routing system:5855861.  You can use the :meth:`flask.Flask.route` decorator.5872.  You can use the :meth:`flask.Flask.add_url_rule` function.5883.  You can directly access the underlying Werkzeug routing system589    which is exposed as :attr:`flask.Flask.url_map`.590591Variable parts in the route can be specified with angular brackets592(``/user/<username>``).  By default a variable part in the URL accepts any593string without a slash however a different converter can be specified as594well by using ``<converter:name>``.595596Variable parts are passed to the view function as keyword arguments.597598The following converters are available:599600=========== ===============================================601`string`    accepts any text without a slash (the default)602`int`       accepts integers603`float`     like `int` but for floating point values604`path`      like the default but also accepts slashes605`any`       matches one of the items provided606`uuid`      accepts UUID strings607=========== ===============================================608609Custom converters can be defined using :attr:`flask.Flask.url_map`.610611Here are some examples::612613    @app.route('/')614    def index():615        pass616617    @app.route('/<username>')618    def show_user(username):619        pass620621    @app.route('/post/<int:post_id>')622    def show_post(post_id):623        pass624625An important detail to keep in mind is how Flask deals with trailing626slashes.  The idea is to keep each URL unique so the following rules627apply:6286291. If a rule ends with a slash and is requested without a slash by the630   user, the user is automatically redirected to the same page with a631   trailing slash attached.6322. If a rule does not end with a trailing slash and the user requests the633   page with a trailing slash, a 404 not found is raised.634635This is consistent with how web servers deal with static files.  This636also makes it possible to use relative link targets safely.637638You can also define multiple rules for the same function.  They have to be639unique however.  Defaults can also be specified.  Here for example is a640definition for a URL that accepts an optional page::641642    @app.route('/users/', defaults={'page': 1})643    @app.route('/users/page/<int:page>')644    def show_users(page):645        pass646647This specifies that ``/users/`` will be the URL for page one and648``/users/page/N`` will be the URL for page ``N``.649650If a URL contains a default value, it will be redirected to its simpler651form with a 301 redirect. In the above example, ``/users/page/1`` will652be redirected to ``/users/``. If your route handles ``GET`` and ``POST``653requests, make sure the default route only handles ``GET``, as redirects654can't preserve form data. ::655656   @app.route('/region/', defaults={'id': 1})657   @app.route('/region/<int:id>', methods=['GET', 'POST'])658   def region(id):659      pass660661Here are the parameters that :meth:`~flask.Flask.route` and662:meth:`~flask.Flask.add_url_rule` accept.  The only difference is that663with the route parameter the view function is defined with the decorator664instead of the `view_func` parameter.665666=============== ==========================================================667`rule`          the URL rule as string668`endpoint`      the endpoint for the registered URL rule.  Flask itself669                assumes that the name of the view function is the name670                of the endpoint if not explicitly stated.671`view_func`     the function to call when serving a request to the672                provided endpoint.  If this is not provided one can673                specify the function later by storing it in the674                :attr:`~flask.Flask.view_functions` dictionary with the675                endpoint as key.676`defaults`      A dictionary with defaults for this rule.  See the677                example above for how defaults work.678`subdomain`     specifies the rule for the subdomain in case subdomain679                matching is in use.  If not specified the default680                subdomain is assumed.681`**options`     the options to be forwarded to the underlying682                :class:`~werkzeug.routing.Rule` object.  A change to683                Werkzeug is handling of method options.  methods is a list684                of methods this rule should be limited to (``GET``, ``POST``685                etc.).  By default a rule just listens for ``GET`` (and686                implicitly ``HEAD``).  Starting with Flask 0.6, ``OPTIONS`` is687                implicitly added and handled by the standard request688                handling.  They have to be specified as keyword arguments.689=============== ==========================================================690691692View Function Options693---------------------694695For internal usage the view functions can have some attributes attached to696customize behavior the view function would normally not have control over.697The following attributes can be provided optionally to either override698some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:699700-   `__name__`: The name of a function is by default used as endpoint.  If701    endpoint is provided explicitly this value is used.  Additionally this702    will be prefixed with the name of the blueprint by default which703    cannot be customized from the function itself.704705-   `methods`: If methods are not provided when the URL rule is added,706    Flask will look on the view function object itself if a `methods`707    attribute exists.  If it does, it will pull the information for the708    methods from there.709710-   `provide_automatic_options`: if this attribute is set Flask will711    either force enable or disable the automatic implementation of the712    HTTP ``OPTIONS`` response.  This can be useful when working with713    decorators that want to customize the ``OPTIONS`` response on a per-view714    basis.715716-   `required_methods`: if this attribute is set, Flask will always add717    these methods when registering a URL rule even if the methods were718    explicitly overridden in the ``route()`` call.719720Full example::721722    def index():723        if request.method == 'OPTIONS':724            # custom options handling here725            ...726        return 'Hello World!'727    index.provide_automatic_options = False728    index.methods = ['GET', 'OPTIONS']729730    app.add_url_rule('/', index)731732.. versionadded:: 0.8733   The `provide_automatic_options` functionality was added.734735Command Line Interface736----------------------737738.. currentmodule:: flask.cli739740.. autoclass:: FlaskGroup741   :members:742743.. autoclass:: AppGroup744   :members:745746.. autoclass:: ScriptInfo747   :members:748749.. autofunction:: load_dotenv750751.. autofunction:: with_appcontext752753.. autofunction:: pass_script_info754755   Marks a function so that an instance of :class:`ScriptInfo` is passed756   as first argument to the click callback.757758.. autodata:: run_command759760.. autodata:: shell_command