Skip to content
Myr

api.rst

This file

Path

docs/api.rst

835 lines · 24.9 KiB

Last changed by

Inherit Werkzeug docs (#2135)Markus Unterwaditzerbefore adoption49386ee

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 `IRI47      <http://tools.ietf.org/html/rfc3987>`_.  Imagine your application is48      listening on the following application 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.. class:: 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, data, mimetype8990   .. 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 the :attr:`Flask.secret_key` set you can use sessions in Flask107applications.  A session basically makes it possible to remember108information from one request to another.  The way Flask does this is by109using a signed cookie.  So the user can look at the session contents, but110not modify it unless they know the secret key, so make sure to set that111to 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 on 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.. autodata:: session_json_serializer175176   This object provides dumping and loading methods similar to simplejson177   but it also tags certain builtin Python objects that commonly appear in178   sessions.  Currently the following extended values are supported in179   the JSON it dumps:180181   -    :class:`~markupsafe.Markup` objects182   -    :class:`~uuid.UUID` objects183   -    :class:`~datetime.datetime` objects184   -   :class:`tuple`\s185186.. admonition:: Notice187188   The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer189   starting with Flask 0.8.  Either catch this down yourself or use190   the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the191   app which converts the result to an integer automatically.192193194Test Client195-----------196197.. currentmodule:: flask.testing198199.. autoclass:: FlaskClient200   :members:201202203Application Globals204-------------------205206.. currentmodule:: flask207208To share data that is valid for one request only from one function to209another, a global variable is not good enough because it would break in210threaded environments.  Flask provides you with a special object that211ensures it is only valid for the active request and that will return212different values for each request.  In a nutshell: it does the right213thing, like it does for :class:`request` and :class:`session`.214215.. data:: g216217   Just store on this whatever you want.  For example a database218   connection or the user that is currently logged in.219220   Starting with Flask 0.10 this is stored on the application context and221   no longer on the request context which means it becomes available if222   only the application context is bound and not yet a request.  This223   is especially useful when combined with the :ref:`faking-resources`224   pattern for testing.225226   Additionally as of 0.10 you can use the :meth:`get` method to227   get an attribute or ``None`` (or the second argument) if it's not set.228   These two usages are now equivalent::229230        user = getattr(flask.g, 'user', None)231        user = flask.g.get('user', None)232233   It's now also possible to use the ``in`` operator on it to see if an234   attribute is defined and it yields all keys on iteration.235236   As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same237   way you would use them on a dictionary.238239   This is a proxy.  See :ref:`notes-on-proxies` for more information.240241242Useful Functions and Classes243----------------------------244245.. data:: current_app246247   Points to the application handling the request.  This is useful for248   extensions that want to support multiple applications running side249   by side.  This is powered by the application context and not by the250   request context, so you can change the value of this proxy by251   using the :meth:`~flask.Flask.app_context` method.252253   This is a proxy.  See :ref:`notes-on-proxies` for more information.254255.. autofunction:: has_request_context256257.. autofunction:: copy_current_request_context258259.. autofunction:: has_app_context260261.. autofunction:: url_for262263.. autofunction:: abort264265.. autofunction:: redirect266267.. autofunction:: make_response268269.. autofunction:: after_this_request270271.. autofunction:: send_file272273.. autofunction:: send_from_directory274275.. autofunction:: safe_join276277.. autofunction:: escape278279.. autoclass:: Markup280   :members: escape, unescape, striptags281282Message Flashing283----------------284285.. autofunction:: flash286287.. autofunction:: get_flashed_messages288289JSON Support290------------291292.. module:: flask.json293294Flask uses ``simplejson`` for the JSON implementation.  Since simplejson295is provided by both the standard library as well as extension, Flask will296try simplejson first and then fall back to the stdlib json module.  On top297of that it will delegate access to the current application's JSON encoders298and decoders for easier customization.299300So for starters instead of doing::301302    try:303        import simplejson as json304    except ImportError:305        import json306307You can instead just do this::308309    from flask import json310311For usage examples, read the :mod:`json` documentation in the standard312library.  The following extensions are by default applied to the stdlib's313JSON module:3143151.  ``datetime`` objects are serialized as :rfc:`822` strings.3162.  Any object with an ``__html__`` method (like :class:`~flask.Markup`)317    will have that method called and then the return value is serialized318    as string.319320The :func:`~htmlsafe_dumps` function of this json module is also available321as filter called ``|tojson`` in Jinja2.  Note that inside ``script``322tags no escaping must take place, so make sure to disable escaping323with ``|safe`` if you intend to use it inside ``script`` tags unless324you are using Flask 0.10 which implies that:325326.. sourcecode:: html+jinja327328    <script type=text/javascript>329        doSomethingWith({{ user.username|tojson|safe }});330    </script>331332.. admonition:: Auto-Sort JSON Keys333334    The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be335    set to false to stop Flask from auto-sorting keys.  By default sorting336    is enabled and outside of the app context sorting is turned on.337338    Notice that disabling key sorting can cause issues when using content339    based HTTP caches and Python's hash randomization feature.340341.. autofunction:: jsonify342343.. autofunction:: dumps344345.. autofunction:: dump346347.. autofunction:: loads348349.. autofunction:: load350351.. autoclass:: JSONEncoder352   :members:353354.. autoclass:: JSONDecoder355   :members:356357Template Rendering358------------------359360.. currentmodule:: flask361362.. autofunction:: render_template363364.. autofunction:: render_template_string365366.. autofunction:: get_template_attribute367368Configuration369-------------370371.. autoclass:: Config372   :members:373374Extensions375----------376377.. data:: flask.ext378379   This module acts as redirect import module to Flask extensions.  It was380   added in 0.8 as the canonical way to import Flask extensions and makes381   it possible for us to have more flexibility in how we distribute382   extensions.383384   If you want to use an extension named “Flask-Foo” you would import it385   from :data:`~flask.ext` as follows::386387        from flask.ext import foo388389   .. versionadded:: 0.8390391Stream Helpers392--------------393394.. autofunction:: stream_with_context395396Useful Internals397----------------398399.. autoclass:: flask.ctx.RequestContext400   :members:401402.. data:: _request_ctx_stack403404   The internal :class:`~werkzeug.local.LocalStack` that is used to implement405   all the context local objects used in Flask.  This is a documented406   instance and can be used by extensions and application code but the407   use is discouraged in general.408409   The following attributes are always present on each layer of the410   stack:411412   `app`413      the active Flask application.414415   `url_adapter`416      the URL adapter that was used to match the request.417418   `request`419      the current request object.420421   `session`422      the active session object.423424   `g`425      an object with all the attributes of the :data:`flask.g` object.426427   `flashes`428      an internal cache for the flashed messages.429430   Example usage::431432      from flask import _request_ctx_stack433434      def get_session():435          ctx = _request_ctx_stack.top436          if ctx is not None:437              return ctx.session438439.. autoclass:: flask.ctx.AppContext440   :members:441442.. data:: _app_ctx_stack443444   Works similar to the request context but only binds the application.445   This is mainly there for extensions to store data.446447   .. versionadded:: 0.9448449.. autoclass:: flask.blueprints.BlueprintSetupState450   :members:451452.. _core-signals-list:453454Signals455-------456457.. versionadded:: 0.6458459.. data:: signals.signals_available460461   ``True`` if the signaling system is available.  This is the case462   when `blinker`_ is installed.463464The following signals exist in Flask:465466.. data:: template_rendered467468   This signal is sent when a template was successfully rendered.  The469   signal is invoked with the instance of the template as `template`470   and the context as dictionary (named `context`).471472   Example subscriber::473474        def log_template_renders(sender, template, context, **extra):475            sender.logger.debug('Rendering template "%s" with context %s',476                                template.name or 'string template',477                                context)478479        from flask import template_rendered480        template_rendered.connect(log_template_renders, app)481482.. data:: flask.before_render_template483   :noindex:484485   This signal is sent before template rendering process. The486   signal is invoked with the instance of the template as `template`487   and the context as dictionary (named `context`).488489   Example subscriber::490491        def log_template_renders(sender, template, context, **extra):492            sender.logger.debug('Rendering template "%s" with context %s',493                                template.name or 'string template',494                                context)495496        from flask import before_render_template497        before_render_template.connect(log_template_renders, app)498499.. data:: request_started500501   This signal is sent when the request context is set up, before502   any request processing happens.  Because the request context is already503   bound, the subscriber can access the request with the standard global504   proxies such as :class:`~flask.request`.505506   Example subscriber::507508        def log_request(sender, **extra):509            sender.logger.debug('Request context is set up')510511        from flask import request_started512        request_started.connect(log_request, app)513514.. data:: request_finished515516   This signal is sent right before the response is sent to the client.517   It is passed the response to be sent named `response`.518519   Example subscriber::520521        def log_response(sender, response, **extra):522            sender.logger.debug('Request context is about to close down.  '523                                'Response: %s', response)524525        from flask import request_finished526        request_finished.connect(log_response, app)527528.. data:: got_request_exception529530   This signal is sent when an exception happens during request processing.531   It is sent *before* the standard exception handling kicks in and even532   in debug mode, where no exception handling happens.  The exception533   itself is passed to the subscriber as `exception`.534535   Example subscriber::536537        def log_exception(sender, exception, **extra):538            sender.logger.debug('Got exception during processing: %s', exception)539540        from flask import got_request_exception541        got_request_exception.connect(log_exception, app)542543.. data:: request_tearing_down544545   This signal is sent when the request is tearing down.  This is always546   called, even if an exception is caused.  Currently functions listening547   to this signal are called after the regular teardown handlers, but this548   is not something you can rely on.549550   Example subscriber::551552        def close_db_connection(sender, **extra):553            session.close()554555        from flask import request_tearing_down556        request_tearing_down.connect(close_db_connection, app)557558   As of Flask 0.9, this will also be passed an `exc` keyword argument559   that has a reference to the exception that caused the teardown if560   there was one.561562.. data:: appcontext_tearing_down563564   This signal is sent when the app context is tearing down.  This is always565   called, even if an exception is caused.  Currently functions listening566   to this signal are called after the regular teardown handlers, but this567   is not something you can rely on.568569   Example subscriber::570571        def close_db_connection(sender, **extra):572            session.close()573574        from flask import appcontext_tearing_down575        appcontext_tearing_down.connect(close_db_connection, app)576577   This will also be passed an `exc` keyword argument that has a reference578   to the exception that caused the teardown if there was one.579580.. data:: appcontext_pushed581582   This signal is sent when an application context is pushed.  The sender583   is the application.  This is usually useful for unittests in order to584   temporarily hook in information.  For instance it can be used to585   set a resource early onto the `g` object.586587   Example usage::588589        from contextlib import contextmanager590        from flask import appcontext_pushed591592        @contextmanager593        def user_set(app, user):594            def handler(sender, **kwargs):595                g.user = user596            with appcontext_pushed.connected_to(handler, app):597                yield598599   And in the testcode::600601        def test_user_me(self):602            with user_set(app, 'john'):603                c = app.test_client()604                resp = c.get('/users/me')605                assert resp.data == 'username=john'606607   .. versionadded:: 0.10608609.. data:: appcontext_popped610611   This signal is sent when an application context is popped.  The sender612   is the application.  This usually falls in line with the613   :data:`appcontext_tearing_down` signal.614615   .. versionadded:: 0.10616617618.. data:: message_flashed619620   This signal is sent when the application is flashing a message.  The621   messages is sent as `message` keyword argument and the category as622   `category`.623624   Example subscriber::625626        recorded = []627        def record(sender, message, category, **extra):628            recorded.append((message, category))629630        from flask import message_flashed631        message_flashed.connect(record, app)632633   .. versionadded:: 0.10634635.. class:: signals.Namespace636637   An alias for :class:`blinker.base.Namespace` if blinker is available,638   otherwise a dummy class that creates fake signals.  This class is639   available for Flask extensions that want to provide the same fallback640   system as Flask itself.641642   .. method:: signal(name, doc=None)643644      Creates a new signal for this namespace if blinker is available,645      otherwise returns a fake signal that has a send method that will646      do nothing but will fail with a :exc:`RuntimeError` for all other647      operations, including connecting.648649650.. _blinker: https://pypi.python.org/pypi/blinker651652653Class-Based Views654-----------------655656.. versionadded:: 0.7657658.. currentmodule:: None659660.. autoclass:: flask.views.View661   :members:662663.. autoclass:: flask.views.MethodView664   :members:665666.. _url-route-registrations:667668URL Route Registrations669-----------------------670671Generally there are three ways to define rules for the routing system:6726731.  You can use the :meth:`flask.Flask.route` decorator.6742.  You can use the :meth:`flask.Flask.add_url_rule` function.6753.  You can directly access the underlying Werkzeug routing system676    which is exposed as :attr:`flask.Flask.url_map`.677678Variable parts in the route can be specified with angular brackets679(``/user/<username>``).  By default a variable part in the URL accepts any680string without a slash however a different converter can be specified as681well by using ``<converter:name>``.682683Variable parts are passed to the view function as keyword arguments.684685The following converters are available:686687=========== ===============================================688`string`    accepts any text without a slash (the default)689`int`       accepts integers690`float`     like `int` but for floating point values691`path`      like the default but also accepts slashes692`any`       matches one of the items provided693`uuid`      accepts UUID strings694=========== ===============================================695696Custom converters can be defined using :attr:`flask.Flask.url_map`.697698Here are some examples::699700    @app.route('/')701    def index():702        pass703704    @app.route('/<username>')705    def show_user(username):706        pass707708    @app.route('/post/<int:post_id>')709    def show_post(post_id):710        pass711712An important detail to keep in mind is how Flask deals with trailing713slashes.  The idea is to keep each URL unique so the following rules714apply:7157161. If a rule ends with a slash and is requested without a slash by the717   user, the user is automatically redirected to the same page with a718   trailing slash attached.7192. If a rule does not end with a trailing slash and the user requests the720   page with a trailing slash, a 404 not found is raised.721722This is consistent with how web servers deal with static files.  This723also makes it possible to use relative link targets safely.724725You can also define multiple rules for the same function.  They have to be726unique however.  Defaults can also be specified.  Here for example is a727definition for a URL that accepts an optional page::728729    @app.route('/users/', defaults={'page': 1})730    @app.route('/users/page/<int:page>')731    def show_users(page):732        pass733734This specifies that ``/users/`` will be the URL for page one and735``/users/page/N`` will be the URL for page `N`.736737Here are the parameters that :meth:`~flask.Flask.route` and738:meth:`~flask.Flask.add_url_rule` accept.  The only difference is that739with the route parameter the view function is defined with the decorator740instead of the `view_func` parameter.741742=============== ==========================================================743`rule`          the URL rule as string744`endpoint`      the endpoint for the registered URL rule.  Flask itself745                assumes that the name of the view function is the name746                of the endpoint if not explicitly stated.747`view_func`     the function to call when serving a request to the748                provided endpoint.  If this is not provided one can749                specify the function later by storing it in the750                :attr:`~flask.Flask.view_functions` dictionary with the751                endpoint as key.752`defaults`      A dictionary with defaults for this rule.  See the753                example above for how defaults work.754`subdomain`     specifies the rule for the subdomain in case subdomain755                matching is in use.  If not specified the default756                subdomain is assumed.757`**options`     the options to be forwarded to the underlying758                :class:`~werkzeug.routing.Rule` object.  A change to759                Werkzeug is handling of method options.  methods is a list760                of methods this rule should be limited to (``GET``, ``POST``761                etc.).  By default a rule just listens for ``GET`` (and762                implicitly ``HEAD``).  Starting with Flask 0.6, ``OPTIONS`` is763                implicitly added and handled by the standard request764                handling.  They have to be specified as keyword arguments.765=============== ==========================================================766767.. _view-func-options:768769View Function Options770---------------------771772For internal usage the view functions can have some attributes attached to773customize behavior the view function would normally not have control over.774The following attributes can be provided optionally to either override775some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:776777-   `__name__`: The name of a function is by default used as endpoint.  If778    endpoint is provided explicitly this value is used.  Additionally this779    will be prefixed with the name of the blueprint by default which780    cannot be customized from the function itself.781782-   `methods`: If methods are not provided when the URL rule is added,783    Flask will look on the view function object itself if a `methods`784    attribute exists.  If it does, it will pull the information for the785    methods from there.786787-   `provide_automatic_options`: if this attribute is set Flask will788    either force enable or disable the automatic implementation of the789    HTTP ``OPTIONS`` response.  This can be useful when working with790    decorators that want to customize the ``OPTIONS`` response on a per-view791    basis.792793-   `required_methods`: if this attribute is set, Flask will always add794    these methods when registering a URL rule even if the methods were795    explicitly overridden in the ``route()`` call.796797Full example::798799    def index():800        if request.method == 'OPTIONS':801            # custom options handling here802            ...803        return 'Hello World!'804    index.provide_automatic_options = False805    index.methods = ['GET', 'OPTIONS']806807    app.add_url_rule('/', index)808809.. versionadded:: 0.8810   The `provide_automatic_options` functionality was added.811812Command Line Interface813----------------------814815.. currentmodule:: flask.cli816817.. autoclass:: FlaskGroup818   :members:819820.. autoclass:: AppGroup821   :members:822823.. autoclass:: ScriptInfo824   :members:825826.. autofunction:: with_appcontext827828.. autofunction:: pass_script_info829830   Marks a function so that an instance of :class:`ScriptInfo` is passed831   as first argument to the click callback.832833.. autodata:: run_command834835.. autodata:: shell_command