Skip to content
Myr

api.rst

This file

Path

docs/api.rst

773 lines · 22.7 KiB

Last changed by

update docs requirementsDavid Lordbefore adoption7e3b8ab

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:`~werkzeug.wrappers.Request`45   subclass and provides all of the attributes Werkzeug defines.  This46   just shows a quick overview of the most important ones.474849Response Objects50----------------5152.. autoclass:: flask.Response53   :members: set_cookie, max_cookie_size, data, mimetype, is_json, get_json5455   .. attribute:: headers5657      A :class:`~werkzeug.datastructures.Headers` object representing the response headers.5859   .. attribute:: status6061      A string with a response status.6263   .. attribute:: status_code6465      The response status as integer.666768Sessions69--------7071If you have set :attr:`Flask.secret_key` (or configured it from72:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes73it possible to remember information from one request to another. The way Flask74does this is by using a signed cookie. The user can look at the session75contents, but can't modify it unless they know the secret key, so make sure to76set that to something complex and unguessable.7778To access the current session you can use the :class:`session` object:7980.. class:: session8182   The session object works pretty much like an ordinary dict, with the83   difference that it keeps track of modifications.8485   This is a proxy.  See :ref:`notes-on-proxies` for more information.8687   The following attributes are interesting:8889   .. attribute:: new9091      ``True`` if the session is new, ``False`` otherwise.9293   .. attribute:: modified9495      ``True`` if the session object detected a modification.  Be advised96      that modifications on mutable structures are not picked up97      automatically, in that situation you have to explicitly set the98      attribute to ``True`` yourself.  Here an example::99100          # this change is not picked up because a mutable object (here101          # a list) is changed.102          session['objects'].append(42)103          # so mark it as modified yourself104          session.modified = True105106   .. attribute:: permanent107108      If set to ``True`` the session lives for109      :attr:`~flask.Flask.permanent_session_lifetime` seconds.  The110      default is 31 days.  If set to ``False`` (which is the default) the111      session will be deleted when the user closes the browser.112113114Session Interface115-----------------116117.. versionadded:: 0.8118119The session interface provides a simple way to replace the session120implementation that Flask is using.121122.. currentmodule:: flask.sessions123124.. autoclass:: SessionInterface125   :members:126127.. autoclass:: SecureCookieSessionInterface128   :members:129130.. autoclass:: SecureCookieSession131   :members:132133.. autoclass:: NullSession134   :members:135136.. autoclass:: SessionMixin137   :members:138139.. admonition:: Notice140141   The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer142   starting with Flask 0.8.  Either catch this down yourself or use143   the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the144   app which converts the result to an integer automatically.145146147Test Client148-----------149150.. currentmodule:: flask.testing151152.. autoclass:: FlaskClient153   :members:154155156Test CLI Runner157---------------158159.. currentmodule:: flask.testing160161.. autoclass:: FlaskCliRunner162    :members:163164165Application Globals166-------------------167168.. currentmodule:: flask169170To share data that is valid for one request only from one function to171another, a global variable is not good enough because it would break in172threaded environments.  Flask provides you with a special object that173ensures it is only valid for the active request and that will return174different values for each request.  In a nutshell: it does the right175thing, like it does for :class:`request` and :class:`session`.176177.. data:: g178179    A namespace object that can store data during an180    :doc:`application context </appcontext>`. This is an instance of181    :attr:`Flask.app_ctx_globals_class`, which defaults to182    :class:`ctx._AppCtxGlobals`.183184    This is a good place to store resources during a request. During185    testing, you can use the :ref:`faking-resources` pattern to186    pre-configure such resources.187188    This is a proxy. See :ref:`notes-on-proxies` for more information.189190    .. versionchanged:: 0.10191        Bound to the application context instead of the request context.192193.. autoclass:: flask.ctx._AppCtxGlobals194    :members:195196197Useful Functions and Classes198----------------------------199200.. data:: current_app201202    A proxy to the application handling the current request. This is203    useful to access the application without needing to import it, or if204    it can't be imported, such as when using the application factory205    pattern or in blueprints and extensions.206207    This is only available when an208    :doc:`application context </appcontext>` is pushed. This happens209    automatically during requests and CLI commands. It can be controlled210    manually with :meth:`~flask.Flask.app_context`.211212    This is a proxy. See :ref:`notes-on-proxies` for more information.213214.. autofunction:: has_request_context215216.. autofunction:: copy_current_request_context217218.. autofunction:: has_app_context219220.. autofunction:: url_for221222.. autofunction:: abort223224.. autofunction:: redirect225226.. autofunction:: make_response227228.. autofunction:: after_this_request229230.. autofunction:: send_file231232.. autofunction:: send_from_directory233234.. autofunction:: safe_join235236.. autofunction:: escape237238.. autoclass:: Markup239   :members: escape, unescape, striptags240241Message Flashing242----------------243244.. autofunction:: flash245246.. autofunction:: get_flashed_messages247248249JSON Support250------------251252.. module:: flask.json253254Flask uses the built-in :mod:`json` module for handling JSON. It will255use the current blueprint's or application's JSON encoder and decoder256for easier customization. By default it handles some extra data types:257258-   :class:`datetime.datetime` and :class:`datetime.date` are serialized259    to :rfc:`822` strings. This is the same as the HTTP date format.260-   :class:`uuid.UUID` is serialized to a string.261-   :class:`dataclasses.dataclass` is passed to262    :func:`dataclasses.asdict`.263-   :class:`~markupsafe.Markup` (or any object with a ``__html__``264    method) will call the ``__html__`` method to get a string.265266:func:`~htmlsafe_dumps` is also available as the ``|tojson`` template267filter. The filter marks the output with ``|safe`` so it can be used268inside ``script`` tags.269270.. sourcecode:: html+jinja271272    <script type=text/javascript>273        renderChart({{ axis_data|tojson }});274    </script>275276.. autofunction:: jsonify277278.. autofunction:: dumps279280.. autofunction:: dump281282.. autofunction:: loads283284.. autofunction:: load285286.. autoclass:: JSONEncoder287   :members:288289.. autoclass:: JSONDecoder290   :members:291292.. automodule:: flask.json.tag293294295Template Rendering296------------------297298.. currentmodule:: flask299300.. autofunction:: render_template301302.. autofunction:: render_template_string303304.. autofunction:: get_template_attribute305306Configuration307-------------308309.. autoclass:: Config310   :members:311312313Stream Helpers314--------------315316.. autofunction:: stream_with_context317318Useful Internals319----------------320321.. autoclass:: flask.ctx.RequestContext322   :members:323324.. data:: _request_ctx_stack325326    The internal :class:`~werkzeug.local.LocalStack` that holds327    :class:`~flask.ctx.RequestContext` instances. Typically, the328    :data:`request` and :data:`session` proxies should be accessed329    instead of the stack. It may be useful to access the stack in330    extension code.331332    The following attributes are always present on each layer of the333    stack:334335    `app`336      the active Flask application.337338    `url_adapter`339      the URL adapter that was used to match the request.340341    `request`342      the current request object.343344    `session`345      the active session object.346347    `g`348      an object with all the attributes of the :data:`flask.g` object.349350    `flashes`351      an internal cache for the flashed messages.352353    Example usage::354355        from flask import _request_ctx_stack356357        def get_session():358            ctx = _request_ctx_stack.top359            if ctx is not None:360                return ctx.session361362.. autoclass:: flask.ctx.AppContext363   :members:364365.. data:: _app_ctx_stack366367    The internal :class:`~werkzeug.local.LocalStack` that holds368    :class:`~flask.ctx.AppContext` instances. Typically, the369    :data:`current_app` and :data:`g` proxies should be accessed instead370    of the stack. Extensions can access the contexts on the stack as a371    namespace to store data.372373    .. versionadded:: 0.9374375.. autoclass:: flask.blueprints.BlueprintSetupState376   :members:377378.. _core-signals-list:379380Signals381-------382383.. versionadded:: 0.6384385.. data:: signals.signals_available386387   ``True`` if the signaling system is available.  This is the case388   when `blinker`_ is installed.389390The following signals exist in Flask:391392.. data:: template_rendered393394   This signal is sent when a template was successfully rendered.  The395   signal is invoked with the instance of the template as `template`396   and the context as dictionary (named `context`).397398   Example subscriber::399400        def log_template_renders(sender, template, context, **extra):401            sender.logger.debug('Rendering template "%s" with context %s',402                                template.name or 'string template',403                                context)404405        from flask import template_rendered406        template_rendered.connect(log_template_renders, app)407408.. data:: flask.before_render_template409   :noindex:410411   This signal is sent before template rendering process. The412   signal is invoked with the instance of the template as `template`413   and the context as dictionary (named `context`).414415   Example subscriber::416417        def log_template_renders(sender, template, context, **extra):418            sender.logger.debug('Rendering template "%s" with context %s',419                                template.name or 'string template',420                                context)421422        from flask import before_render_template423        before_render_template.connect(log_template_renders, app)424425.. data:: request_started426427   This signal is sent when the request context is set up, before428   any request processing happens.  Because the request context is already429   bound, the subscriber can access the request with the standard global430   proxies such as :class:`~flask.request`.431432   Example subscriber::433434        def log_request(sender, **extra):435            sender.logger.debug('Request context is set up')436437        from flask import request_started438        request_started.connect(log_request, app)439440.. data:: request_finished441442   This signal is sent right before the response is sent to the client.443   It is passed the response to be sent named `response`.444445   Example subscriber::446447        def log_response(sender, response, **extra):448            sender.logger.debug('Request context is about to close down.  '449                                'Response: %s', response)450451        from flask import request_finished452        request_finished.connect(log_response, app)453454.. data:: got_request_exception455456   This signal is sent when an exception happens during request processing.457   It is sent *before* the standard exception handling kicks in and even458   in debug mode, where no exception handling happens.  The exception459   itself is passed to the subscriber as `exception`.460461   Example subscriber::462463        def log_exception(sender, exception, **extra):464            sender.logger.debug('Got exception during processing: %s', exception)465466        from flask import got_request_exception467        got_request_exception.connect(log_exception, app)468469.. data:: request_tearing_down470471   This signal is sent when the request is tearing down.  This is always472   called, even if an exception is caused.  Currently functions listening473   to this signal are called after the regular teardown handlers, but this474   is not something you can rely on.475476   Example subscriber::477478        def close_db_connection(sender, **extra):479            session.close()480481        from flask import request_tearing_down482        request_tearing_down.connect(close_db_connection, app)483484   As of Flask 0.9, this will also be passed an `exc` keyword argument485   that has a reference to the exception that caused the teardown if486   there was one.487488.. data:: appcontext_tearing_down489490   This signal is sent when the app context is tearing down.  This is always491   called, even if an exception is caused.  Currently functions listening492   to this signal are called after the regular teardown handlers, but this493   is not something you can rely on.494495   Example subscriber::496497        def close_db_connection(sender, **extra):498            session.close()499500        from flask import appcontext_tearing_down501        appcontext_tearing_down.connect(close_db_connection, app)502503   This will also be passed an `exc` keyword argument that has a reference504   to the exception that caused the teardown if there was one.505506.. data:: appcontext_pushed507508   This signal is sent when an application context is pushed.  The sender509   is the application.  This is usually useful for unittests in order to510   temporarily hook in information.  For instance it can be used to511   set a resource early onto the `g` object.512513   Example usage::514515        from contextlib import contextmanager516        from flask import appcontext_pushed517518        @contextmanager519        def user_set(app, user):520            def handler(sender, **kwargs):521                g.user = user522            with appcontext_pushed.connected_to(handler, app):523                yield524525   And in the testcode::526527        def test_user_me(self):528            with user_set(app, 'john'):529                c = app.test_client()530                resp = c.get('/users/me')531                assert resp.data == 'username=john'532533   .. versionadded:: 0.10534535.. data:: appcontext_popped536537   This signal is sent when an application context is popped.  The sender538   is the application.  This usually falls in line with the539   :data:`appcontext_tearing_down` signal.540541   .. versionadded:: 0.10542543544.. data:: message_flashed545546   This signal is sent when the application is flashing a message.  The547   messages is sent as `message` keyword argument and the category as548   `category`.549550   Example subscriber::551552        recorded = []553        def record(sender, message, category, **extra):554            recorded.append((message, category))555556        from flask import message_flashed557        message_flashed.connect(record, app)558559   .. versionadded:: 0.10560561.. class:: signals.Namespace562563   An alias for :class:`blinker.base.Namespace` if blinker is available,564   otherwise a dummy class that creates fake signals.  This class is565   available for Flask extensions that want to provide the same fallback566   system as Flask itself.567568   .. method:: signal(name, doc=None)569570      Creates a new signal for this namespace if blinker is available,571      otherwise returns a fake signal that has a send method that will572      do nothing but will fail with a :exc:`RuntimeError` for all other573      operations, including connecting.574575576.. _blinker: https://pypi.org/project/blinker/577578579Class-Based Views580-----------------581582.. versionadded:: 0.7583584.. currentmodule:: None585586.. autoclass:: flask.views.View587   :members:588589.. autoclass:: flask.views.MethodView590   :members:591592.. _url-route-registrations:593594URL Route Registrations595-----------------------596597Generally there are three ways to define rules for the routing system:5985991.  You can use the :meth:`flask.Flask.route` decorator.6002.  You can use the :meth:`flask.Flask.add_url_rule` function.6013.  You can directly access the underlying Werkzeug routing system602    which is exposed as :attr:`flask.Flask.url_map`.603604Variable parts in the route can be specified with angular brackets605(``/user/<username>``).  By default a variable part in the URL accepts any606string without a slash however a different converter can be specified as607well by using ``<converter:name>``.608609Variable parts are passed to the view function as keyword arguments.610611The following converters are available:612613=========== ===============================================614`string`    accepts any text without a slash (the default)615`int`       accepts integers616`float`     like `int` but for floating point values617`path`      like the default but also accepts slashes618`any`       matches one of the items provided619`uuid`      accepts UUID strings620=========== ===============================================621622Custom converters can be defined using :attr:`flask.Flask.url_map`.623624Here are some examples::625626    @app.route('/')627    def index():628        pass629630    @app.route('/<username>')631    def show_user(username):632        pass633634    @app.route('/post/<int:post_id>')635    def show_post(post_id):636        pass637638An important detail to keep in mind is how Flask deals with trailing639slashes.  The idea is to keep each URL unique so the following rules640apply:6416421. If a rule ends with a slash and is requested without a slash by the643   user, the user is automatically redirected to the same page with a644   trailing slash attached.6452. If a rule does not end with a trailing slash and the user requests the646   page with a trailing slash, a 404 not found is raised.647648This is consistent with how web servers deal with static files.  This649also makes it possible to use relative link targets safely.650651You can also define multiple rules for the same function.  They have to be652unique however.  Defaults can also be specified.  Here for example is a653definition for a URL that accepts an optional page::654655    @app.route('/users/', defaults={'page': 1})656    @app.route('/users/page/<int:page>')657    def show_users(page):658        pass659660This specifies that ``/users/`` will be the URL for page one and661``/users/page/N`` will be the URL for page ``N``.662663If a URL contains a default value, it will be redirected to its simpler664form with a 301 redirect. In the above example, ``/users/page/1`` will665be redirected to ``/users/``. If your route handles ``GET`` and ``POST``666requests, make sure the default route only handles ``GET``, as redirects667can't preserve form data. ::668669   @app.route('/region/', defaults={'id': 1})670   @app.route('/region/<int:id>', methods=['GET', 'POST'])671   def region(id):672      pass673674Here are the parameters that :meth:`~flask.Flask.route` and675:meth:`~flask.Flask.add_url_rule` accept.  The only difference is that676with the route parameter the view function is defined with the decorator677instead of the `view_func` parameter.678679=============== ==========================================================680`rule`          the URL rule as string681`endpoint`      the endpoint for the registered URL rule.  Flask itself682                assumes that the name of the view function is the name683                of the endpoint if not explicitly stated.684`view_func`     the function to call when serving a request to the685                provided endpoint.  If this is not provided one can686                specify the function later by storing it in the687                :attr:`~flask.Flask.view_functions` dictionary with the688                endpoint as key.689`defaults`      A dictionary with defaults for this rule.  See the690                example above for how defaults work.691`subdomain`     specifies the rule for the subdomain in case subdomain692                matching is in use.  If not specified the default693                subdomain is assumed.694`**options`     the options to be forwarded to the underlying695                :class:`~werkzeug.routing.Rule` object.  A change to696                Werkzeug is handling of method options.  methods is a list697                of methods this rule should be limited to (``GET``, ``POST``698                etc.).  By default a rule just listens for ``GET`` (and699                implicitly ``HEAD``).  Starting with Flask 0.6, ``OPTIONS`` is700                implicitly added and handled by the standard request701                handling.  They have to be specified as keyword arguments.702=============== ==========================================================703704705View Function Options706---------------------707708For internal usage the view functions can have some attributes attached to709customize behavior the view function would normally not have control over.710The following attributes can be provided optionally to either override711some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:712713-   `__name__`: The name of a function is by default used as endpoint.  If714    endpoint is provided explicitly this value is used.  Additionally this715    will be prefixed with the name of the blueprint by default which716    cannot be customized from the function itself.717718-   `methods`: If methods are not provided when the URL rule is added,719    Flask will look on the view function object itself if a `methods`720    attribute exists.  If it does, it will pull the information for the721    methods from there.722723-   `provide_automatic_options`: if this attribute is set Flask will724    either force enable or disable the automatic implementation of the725    HTTP ``OPTIONS`` response.  This can be useful when working with726    decorators that want to customize the ``OPTIONS`` response on a per-view727    basis.728729-   `required_methods`: if this attribute is set, Flask will always add730    these methods when registering a URL rule even if the methods were731    explicitly overridden in the ``route()`` call.732733Full example::734735    def index():736        if request.method == 'OPTIONS':737            # custom options handling here738            ...739        return 'Hello World!'740    index.provide_automatic_options = False741    index.methods = ['GET', 'OPTIONS']742743    app.add_url_rule('/', index)744745.. versionadded:: 0.8746   The `provide_automatic_options` functionality was added.747748Command Line Interface749----------------------750751.. currentmodule:: flask.cli752753.. autoclass:: FlaskGroup754   :members:755756.. autoclass:: AppGroup757   :members:758759.. autoclass:: ScriptInfo760   :members:761762.. autofunction:: load_dotenv763764.. autofunction:: with_appcontext765766.. autofunction:: pass_script_info767768   Marks a function so that an instance of :class:`ScriptInfo` is passed769   as first argument to the click callback.770771.. autodata:: run_command772773.. autodata:: shell_command