Skip to content
Myr

api.rst

This file

Path

docs/api.rst

833 lines · 24.7 KiB

Last changed by

Merge branch '1.0.x'David Lordbefore adoption1351d0a

History of this file

Take it

1.. _api:23API4===56.. module:: flask78This part of the documentation covers all the interfaces of Flask.  For9parts where Flask depends on external libraries, we document the most10important right here and provide links to the canonical documentation.111213Application Object14------------------1516.. autoclass:: Flask17   :members:18   :inherited-members:192021Blueprint Objects22-----------------2324.. autoclass:: Blueprint25   :members:26   :inherited-members:2728Incoming Request Data29---------------------3031.. autoclass:: Request32   :members:33   :inherited-members:3435   .. attribute:: environ3637      The underlying WSGI environment.3839   .. attribute:: path40   .. attribute:: full_path41   .. attribute:: script_root42   .. attribute:: url43   .. attribute:: base_url44   .. attribute:: url_root4546      Provides different ways to look at the current :rfc:`3987`.47      Imagine your application is listening on the following application48      root::4950          http://www.example.com/myapplication5152      And a user requests the following URI::5354          http://www.example.com/myapplication/%CF%80/page.html?x=y5556      In this case the values of the above mentioned attributes would be57      the following:5859      ============= ======================================================60      `path`        ``u'/π/page.html'``61      `full_path`   ``u'/π/page.html?x=y'``62      `script_root` ``u'/myapplication'``63      `base_url`    ``u'http://www.example.com/myapplication/π/page.html'``64      `url`         ``u'http://www.example.com/myapplication/π/page.html?x=y'``65      `url_root`    ``u'http://www.example.com/myapplication/'``66      ============= ======================================================676869.. attribute:: request7071   To access incoming request data, you can use the global `request`72   object.  Flask parses incoming request data for you and gives you73   access to it through that global object.  Internally Flask makes74   sure that you always get the correct data for the active thread if you75   are in a multithreaded environment.7677   This is a proxy.  See :ref:`notes-on-proxies` for more information.7879   The request object is an instance of a :class:`~werkzeug.wrappers.Request`80   subclass and provides all of the attributes Werkzeug defines.  This81   just shows a quick overview of the most important ones.828384Response Objects85----------------8687.. autoclass:: flask.Response88   :members: set_cookie, max_cookie_size, data, mimetype, is_json, get_json8990   .. attribute:: headers9192      A :class:`~werkzeug.datastructures.Headers` object representing the response headers.9394   .. attribute:: status9596      A string with a response status.9798   .. attribute:: status_code99100      The response status as integer.101102103Sessions104--------105106If you have set :attr:`Flask.secret_key` (or configured it from107:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes108it possible to remember information from one request to another. The way Flask109does this is by using a signed cookie. The user can look at the session110contents, but can't modify it unless they know the secret key, so make sure to111set that to something complex and unguessable.112113To access the current session you can use the :class:`session` object:114115.. class:: session116117   The session object works pretty much like an ordinary dict, with the118   difference that it keeps track of modifications.119120   This is a proxy.  See :ref:`notes-on-proxies` for more information.121122   The following attributes are interesting:123124   .. attribute:: new125126      ``True`` if the session is new, ``False`` otherwise.127128   .. attribute:: modified129130      ``True`` if the session object detected a modification.  Be advised131      that modifications on mutable structures are not picked up132      automatically, in that situation you have to explicitly set the133      attribute to ``True`` yourself.  Here an example::134135          # this change is not picked up because a mutable object (here136          # a list) is changed.137          session['objects'].append(42)138          # so mark it as modified yourself139          session.modified = True140141   .. attribute:: permanent142143      If set to ``True`` the session lives for144      :attr:`~flask.Flask.permanent_session_lifetime` seconds.  The145      default is 31 days.  If set to ``False`` (which is the default) the146      session will be deleted when the user closes the browser.147148149Session Interface150-----------------151152.. versionadded:: 0.8153154The session interface provides a simple way to replace the session155implementation that Flask is using.156157.. currentmodule:: flask.sessions158159.. autoclass:: SessionInterface160   :members:161162.. autoclass:: SecureCookieSessionInterface163   :members:164165.. autoclass:: SecureCookieSession166   :members:167168.. autoclass:: NullSession169   :members:170171.. autoclass:: SessionMixin172   :members:173174.. admonition:: Notice175176   The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer177   starting with Flask 0.8.  Either catch this down yourself or use178   the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the179   app which converts the result to an integer automatically.180181182Test Client183-----------184185.. currentmodule:: flask.testing186187.. autoclass:: FlaskClient188   :members:189190191Test CLI Runner192---------------193194.. currentmodule:: flask.testing195196.. autoclass:: FlaskCliRunner197    :members:198199200Application Globals201-------------------202203.. currentmodule:: flask204205To share data that is valid for one request only from one function to206another, a global variable is not good enough because it would break in207threaded environments.  Flask provides you with a special object that208ensures it is only valid for the active request and that will return209different values for each request.  In a nutshell: it does the right210thing, like it does for :class:`request` and :class:`session`.211212.. data:: g213214    A namespace object that can store data during an215    :doc:`application context </appcontext>`. This is an instance of216    :attr:`Flask.app_ctx_globals_class`, which defaults to217    :class:`ctx._AppCtxGlobals`.218219    This is a good place to store resources during a request. During220    testing, you can use the :ref:`faking-resources` pattern to221    pre-configure such resources.222223    This is a proxy. See :ref:`notes-on-proxies` for more information.224225    .. versionchanged:: 0.10226        Bound to the application context instead of the request context.227228.. autoclass:: flask.ctx._AppCtxGlobals229    :members:230231232Useful Functions and Classes233----------------------------234235.. data:: current_app236237    A proxy to the application handling the current request. This is238    useful to access the application without needing to import it, or if239    it can't be imported, such as when using the application factory240    pattern or in blueprints and extensions.241242    This is only available when an243    :doc:`application context </appcontext>` is pushed. This happens244    automatically during requests and CLI commands. It can be controlled245    manually with :meth:`~flask.Flask.app_context`.246247    This is a proxy. See :ref:`notes-on-proxies` for more information.248249.. autofunction:: has_request_context250251.. autofunction:: copy_current_request_context252253.. autofunction:: has_app_context254255.. autofunction:: url_for256257.. autofunction:: abort258259.. autofunction:: redirect260261.. autofunction:: make_response262263.. autofunction:: after_this_request264265.. autofunction:: send_file266267.. autofunction:: send_from_directory268269.. autofunction:: safe_join270271.. autofunction:: escape272273.. autoclass:: Markup274   :members: escape, unescape, striptags275276Message Flashing277----------------278279.. autofunction:: flash280281.. autofunction:: get_flashed_messages282283JSON Support284------------285286.. module:: flask.json287288Flask uses ``simplejson`` for the JSON implementation.  Since simplejson289is provided by both the standard library as well as extension, Flask will290try simplejson first and then fall back to the stdlib json module.  On top291of that it will delegate access to the current application's JSON encoders292and decoders for easier customization.293294So for starters instead of doing::295296    try:297        import simplejson as json298    except ImportError:299        import json300301You can instead just do this::302303    from flask import json304305For usage examples, read the :mod:`json` documentation in the standard306library.  The following extensions are by default applied to the stdlib's307JSON module:3083091.  ``datetime`` objects are serialized as :rfc:`822` strings.3102.  Any object with an ``__html__`` method (like :class:`~flask.Markup`)311    will have that method called and then the return value is serialized312    as string.313314The :func:`~htmlsafe_dumps` function of this json module is also available315as a filter called ``|tojson`` in Jinja2.  Note that in versions of Flask prior316to Flask 0.10, you must disable escaping with ``|safe`` if you intend to use317``|tojson`` output inside ``script`` tags. In Flask 0.10 and above, this318happens automatically (but it's harmless to include ``|safe`` anyway).319320.. sourcecode:: html+jinja321322    <script type=text/javascript>323        doSomethingWith({{ user.username|tojson|safe }});324    </script>325326.. admonition:: Auto-Sort JSON Keys327328    The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be329    set to false to stop Flask from auto-sorting keys.  By default sorting330    is enabled and outside of the app context sorting is turned on.331332    Notice that disabling key sorting can cause issues when using content333    based HTTP caches and Python's hash randomization feature.334335.. autofunction:: jsonify336337.. autofunction:: dumps338339.. autofunction:: dump340341.. autofunction:: loads342343.. autofunction:: load344345.. autoclass:: JSONEncoder346   :members:347348.. autoclass:: JSONDecoder349   :members:350351.. automodule:: flask.json.tag352353Template Rendering354------------------355356.. currentmodule:: flask357358.. autofunction:: render_template359360.. autofunction:: render_template_string361362.. autofunction:: get_template_attribute363364Configuration365-------------366367.. autoclass:: Config368   :members:369370371Stream Helpers372--------------373374.. autofunction:: stream_with_context375376Useful Internals377----------------378379.. autoclass:: flask.ctx.RequestContext380   :members:381382.. data:: _request_ctx_stack383384    The internal :class:`~werkzeug.local.LocalStack` that holds385    :class:`~flask.ctx.RequestContext` instances. Typically, the386    :data:`request` and :data:`session` proxies should be accessed387    instead of the stack. It may be useful to access the stack in388    extension code.389390    The following attributes are always present on each layer of the391    stack:392393    `app`394      the active Flask application.395396    `url_adapter`397      the URL adapter that was used to match the request.398399    `request`400      the current request object.401402    `session`403      the active session object.404405    `g`406      an object with all the attributes of the :data:`flask.g` object.407408    `flashes`409      an internal cache for the flashed messages.410411    Example usage::412413        from flask import _request_ctx_stack414415        def get_session():416            ctx = _request_ctx_stack.top417            if ctx is not None:418                return ctx.session419420.. autoclass:: flask.ctx.AppContext421   :members:422423.. data:: _app_ctx_stack424425    The internal :class:`~werkzeug.local.LocalStack` that holds426    :class:`~flask.ctx.AppContext` instances. Typically, the427    :data:`current_app` and :data:`g` proxies should be accessed instead428    of the stack. Extensions can access the contexts on the stack as a429    namespace to store data.430431    .. versionadded:: 0.9432433.. autoclass:: flask.blueprints.BlueprintSetupState434   :members:435436.. _core-signals-list:437438Signals439-------440441.. versionadded:: 0.6442443.. data:: signals.signals_available444445   ``True`` if the signaling system is available.  This is the case446   when `blinker`_ is installed.447448The following signals exist in Flask:449450.. data:: template_rendered451452   This signal is sent when a template was successfully rendered.  The453   signal is invoked with the instance of the template as `template`454   and the context as dictionary (named `context`).455456   Example subscriber::457458        def log_template_renders(sender, template, context, **extra):459            sender.logger.debug('Rendering template "%s" with context %s',460                                template.name or 'string template',461                                context)462463        from flask import template_rendered464        template_rendered.connect(log_template_renders, app)465466.. data:: flask.before_render_template467   :noindex:468469   This signal is sent before template rendering process. The470   signal is invoked with the instance of the template as `template`471   and the context as dictionary (named `context`).472473   Example subscriber::474475        def log_template_renders(sender, template, context, **extra):476            sender.logger.debug('Rendering template "%s" with context %s',477                                template.name or 'string template',478                                context)479480        from flask import before_render_template481        before_render_template.connect(log_template_renders, app)482483.. data:: request_started484485   This signal is sent when the request context is set up, before486   any request processing happens.  Because the request context is already487   bound, the subscriber can access the request with the standard global488   proxies such as :class:`~flask.request`.489490   Example subscriber::491492        def log_request(sender, **extra):493            sender.logger.debug('Request context is set up')494495        from flask import request_started496        request_started.connect(log_request, app)497498.. data:: request_finished499500   This signal is sent right before the response is sent to the client.501   It is passed the response to be sent named `response`.502503   Example subscriber::504505        def log_response(sender, response, **extra):506            sender.logger.debug('Request context is about to close down.  '507                                'Response: %s', response)508509        from flask import request_finished510        request_finished.connect(log_response, app)511512.. data:: got_request_exception513514   This signal is sent when an exception happens during request processing.515   It is sent *before* the standard exception handling kicks in and even516   in debug mode, where no exception handling happens.  The exception517   itself is passed to the subscriber as `exception`.518519   Example subscriber::520521        def log_exception(sender, exception, **extra):522            sender.logger.debug('Got exception during processing: %s', exception)523524        from flask import got_request_exception525        got_request_exception.connect(log_exception, app)526527.. data:: request_tearing_down528529   This signal is sent when the request is tearing down.  This is always530   called, even if an exception is caused.  Currently functions listening531   to this signal are called after the regular teardown handlers, but this532   is not something you can rely on.533534   Example subscriber::535536        def close_db_connection(sender, **extra):537            session.close()538539        from flask import request_tearing_down540        request_tearing_down.connect(close_db_connection, app)541542   As of Flask 0.9, this will also be passed an `exc` keyword argument543   that has a reference to the exception that caused the teardown if544   there was one.545546.. data:: appcontext_tearing_down547548   This signal is sent when the app context is tearing down.  This is always549   called, even if an exception is caused.  Currently functions listening550   to this signal are called after the regular teardown handlers, but this551   is not something you can rely on.552553   Example subscriber::554555        def close_db_connection(sender, **extra):556            session.close()557558        from flask import appcontext_tearing_down559        appcontext_tearing_down.connect(close_db_connection, app)560561   This will also be passed an `exc` keyword argument that has a reference562   to the exception that caused the teardown if there was one.563564.. data:: appcontext_pushed565566   This signal is sent when an application context is pushed.  The sender567   is the application.  This is usually useful for unittests in order to568   temporarily hook in information.  For instance it can be used to569   set a resource early onto the `g` object.570571   Example usage::572573        from contextlib import contextmanager574        from flask import appcontext_pushed575576        @contextmanager577        def user_set(app, user):578            def handler(sender, **kwargs):579                g.user = user580            with appcontext_pushed.connected_to(handler, app):581                yield582583   And in the testcode::584585        def test_user_me(self):586            with user_set(app, 'john'):587                c = app.test_client()588                resp = c.get('/users/me')589                assert resp.data == 'username=john'590591   .. versionadded:: 0.10592593.. data:: appcontext_popped594595   This signal is sent when an application context is popped.  The sender596   is the application.  This usually falls in line with the597   :data:`appcontext_tearing_down` signal.598599   .. versionadded:: 0.10600601602.. data:: message_flashed603604   This signal is sent when the application is flashing a message.  The605   messages is sent as `message` keyword argument and the category as606   `category`.607608   Example subscriber::609610        recorded = []611        def record(sender, message, category, **extra):612            recorded.append((message, category))613614        from flask import message_flashed615        message_flashed.connect(record, app)616617   .. versionadded:: 0.10618619.. class:: signals.Namespace620621   An alias for :class:`blinker.base.Namespace` if blinker is available,622   otherwise a dummy class that creates fake signals.  This class is623   available for Flask extensions that want to provide the same fallback624   system as Flask itself.625626   .. method:: signal(name, doc=None)627628      Creates a new signal for this namespace if blinker is available,629      otherwise returns a fake signal that has a send method that will630      do nothing but will fail with a :exc:`RuntimeError` for all other631      operations, including connecting.632633634.. _blinker: https://pypi.org/project/blinker/635636.. _class-based-views:637638Class-Based Views639-----------------640641.. versionadded:: 0.7642643.. currentmodule:: None644645.. autoclass:: flask.views.View646   :members:647648.. autoclass:: flask.views.MethodView649   :members:650651.. _url-route-registrations:652653URL Route Registrations654-----------------------655656Generally there are three ways to define rules for the routing system:6576581.  You can use the :meth:`flask.Flask.route` decorator.6592.  You can use the :meth:`flask.Flask.add_url_rule` function.6603.  You can directly access the underlying Werkzeug routing system661    which is exposed as :attr:`flask.Flask.url_map`.662663Variable parts in the route can be specified with angular brackets664(``/user/<username>``).  By default a variable part in the URL accepts any665string without a slash however a different converter can be specified as666well by using ``<converter:name>``.667668Variable parts are passed to the view function as keyword arguments.669670The following converters are available:671672=========== ===============================================673`string`    accepts any text without a slash (the default)674`int`       accepts integers675`float`     like `int` but for floating point values676`path`      like the default but also accepts slashes677`any`       matches one of the items provided678`uuid`      accepts UUID strings679=========== ===============================================680681Custom converters can be defined using :attr:`flask.Flask.url_map`.682683Here are some examples::684685    @app.route('/')686    def index():687        pass688689    @app.route('/<username>')690    def show_user(username):691        pass692693    @app.route('/post/<int:post_id>')694    def show_post(post_id):695        pass696697An important detail to keep in mind is how Flask deals with trailing698slashes.  The idea is to keep each URL unique so the following rules699apply:7007011. If a rule ends with a slash and is requested without a slash by the702   user, the user is automatically redirected to the same page with a703   trailing slash attached.7042. If a rule does not end with a trailing slash and the user requests the705   page with a trailing slash, a 404 not found is raised.706707This is consistent with how web servers deal with static files.  This708also makes it possible to use relative link targets safely.709710You can also define multiple rules for the same function.  They have to be711unique however.  Defaults can also be specified.  Here for example is a712definition for a URL that accepts an optional page::713714    @app.route('/users/', defaults={'page': 1})715    @app.route('/users/page/<int:page>')716    def show_users(page):717        pass718719This specifies that ``/users/`` will be the URL for page one and720``/users/page/N`` will be the URL for page ``N``.721722If a URL contains a default value, it will be redirected to its simpler723form with a 301 redirect. In the above example, ``/users/page/1`` will724be redirected to ``/users/``. If your route handles ``GET`` and ``POST``725requests, make sure the default route only handles ``GET``, as redirects726can't preserve form data. ::727728   @app.route('/region/', defaults={'id': 1})729   @app.route('/region/<int:id>', methods=['GET', 'POST'])730   def region(id):731      pass732733Here are the parameters that :meth:`~flask.Flask.route` and734:meth:`~flask.Flask.add_url_rule` accept.  The only difference is that735with the route parameter the view function is defined with the decorator736instead of the `view_func` parameter.737738=============== ==========================================================739`rule`          the URL rule as string740`endpoint`      the endpoint for the registered URL rule.  Flask itself741                assumes that the name of the view function is the name742                of the endpoint if not explicitly stated.743`view_func`     the function to call when serving a request to the744                provided endpoint.  If this is not provided one can745                specify the function later by storing it in the746                :attr:`~flask.Flask.view_functions` dictionary with the747                endpoint as key.748`defaults`      A dictionary with defaults for this rule.  See the749                example above for how defaults work.750`subdomain`     specifies the rule for the subdomain in case subdomain751                matching is in use.  If not specified the default752                subdomain is assumed.753`**options`     the options to be forwarded to the underlying754                :class:`~werkzeug.routing.Rule` object.  A change to755                Werkzeug is handling of method options.  methods is a list756                of methods this rule should be limited to (``GET``, ``POST``757                etc.).  By default a rule just listens for ``GET`` (and758                implicitly ``HEAD``).  Starting with Flask 0.6, ``OPTIONS`` is759                implicitly added and handled by the standard request760                handling.  They have to be specified as keyword arguments.761=============== ==========================================================762763.. _view-func-options:764765View Function Options766---------------------767768For internal usage the view functions can have some attributes attached to769customize behavior the view function would normally not have control over.770The following attributes can be provided optionally to either override771some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:772773-   `__name__`: The name of a function is by default used as endpoint.  If774    endpoint is provided explicitly this value is used.  Additionally this775    will be prefixed with the name of the blueprint by default which776    cannot be customized from the function itself.777778-   `methods`: If methods are not provided when the URL rule is added,779    Flask will look on the view function object itself if a `methods`780    attribute exists.  If it does, it will pull the information for the781    methods from there.782783-   `provide_automatic_options`: if this attribute is set Flask will784    either force enable or disable the automatic implementation of the785    HTTP ``OPTIONS`` response.  This can be useful when working with786    decorators that want to customize the ``OPTIONS`` response on a per-view787    basis.788789-   `required_methods`: if this attribute is set, Flask will always add790    these methods when registering a URL rule even if the methods were791    explicitly overridden in the ``route()`` call.792793Full example::794795    def index():796        if request.method == 'OPTIONS':797            # custom options handling here798            ...799        return 'Hello World!'800    index.provide_automatic_options = False801    index.methods = ['GET', 'OPTIONS']802803    app.add_url_rule('/', index)804805.. versionadded:: 0.8806   The `provide_automatic_options` functionality was added.807808Command Line Interface809----------------------810811.. currentmodule:: flask.cli812813.. autoclass:: FlaskGroup814   :members:815816.. autoclass:: AppGroup817   :members:818819.. autoclass:: ScriptInfo820   :members:821822.. autofunction:: load_dotenv823824.. autofunction:: with_appcontext825826.. autofunction:: pass_script_info827828   Marks a function so that an instance of :class:`ScriptInfo` is passed829   as first argument to the click callback.830831.. autodata:: run_command832833.. autodata:: shell_command