Skip to content
Myr

api.rst

This file

Path

docs/api.rst

837 lines · 24.7 KiB

Last changed by

add test_cli_runner for testing app.cli commandsDavid Lordbefore adoptioncf5525f

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.. 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, 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 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.. 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   Just store on this whatever you want.  For example a database215   connection or the user that is currently logged in.216217   Starting with Flask 0.10 this is stored on the application context and218   no longer on the request context which means it becomes available if219   only the application context is bound and not yet a request.  This220   is especially useful when combined with the :ref:`faking-resources`221   pattern for testing.222223   Additionally as of 0.10 you can use the :meth:`get` method to224   get an attribute or ``None`` (or the second argument) if it's not set.225   These two usages are now equivalent::226227        user = getattr(flask.g, 'user', None)228        user = flask.g.get('user', None)229230   It's now also possible to use the ``in`` operator on it to see if an231   attribute is defined and it yields all keys on iteration.232233   As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same234   way you would use them on a dictionary.235236   This is a proxy.  See :ref:`notes-on-proxies` for more information.237238239Useful Functions and Classes240----------------------------241242.. data:: current_app243244   Points to the application handling the request.  This is useful for245   extensions that want to support multiple applications running side246   by side.  This is powered by the application context and not by the247   request context, so you can change the value of this proxy by248   using the :meth:`~flask.Flask.app_context` method.249250   This is a proxy.  See :ref:`notes-on-proxies` for more information.251252.. autofunction:: has_request_context253254.. autofunction:: copy_current_request_context255256.. autofunction:: has_app_context257258.. autofunction:: url_for259260.. autofunction:: abort261262.. autofunction:: redirect263264.. autofunction:: make_response265266.. autofunction:: after_this_request267268.. autofunction:: send_file269270.. autofunction:: send_from_directory271272.. autofunction:: safe_join273274.. autofunction:: escape275276.. autoclass:: Markup277   :members: escape, unescape, striptags278279Message Flashing280----------------281282.. autofunction:: flash283284.. autofunction:: get_flashed_messages285286JSON Support287------------288289.. module:: flask.json290291Flask uses ``simplejson`` for the JSON implementation.  Since simplejson292is provided by both the standard library as well as extension, Flask will293try simplejson first and then fall back to the stdlib json module.  On top294of that it will delegate access to the current application's JSON encoders295and decoders for easier customization.296297So for starters instead of doing::298299    try:300        import simplejson as json301    except ImportError:302        import json303304You can instead just do this::305306    from flask import json307308For usage examples, read the :mod:`json` documentation in the standard309library.  The following extensions are by default applied to the stdlib's310JSON module:3113121.  ``datetime`` objects are serialized as :rfc:`822` strings.3132.  Any object with an ``__html__`` method (like :class:`~flask.Markup`)314    will have that method called and then the return value is serialized315    as string.316317The :func:`~htmlsafe_dumps` function of this json module is also available318as filter called ``|tojson`` in Jinja2.  Note that inside ``script``319tags no escaping must take place, so make sure to disable escaping320with ``|safe`` if you intend to use it inside ``script`` tags unless321you are using Flask 0.10 which implies that:322323.. sourcecode:: html+jinja324325    <script type=text/javascript>326        doSomethingWith({{ user.username|tojson|safe }});327    </script>328329.. admonition:: Auto-Sort JSON Keys330331    The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be332    set to false to stop Flask from auto-sorting keys.  By default sorting333    is enabled and outside of the app context sorting is turned on.334335    Notice that disabling key sorting can cause issues when using content336    based HTTP caches and Python's hash randomization feature.337338.. autofunction:: jsonify339340.. autofunction:: dumps341342.. autofunction:: dump343344.. autofunction:: loads345346.. autofunction:: load347348.. autoclass:: JSONEncoder349   :members:350351.. autoclass:: JSONDecoder352   :members:353354.. automodule:: flask.json.tag355356Template Rendering357------------------358359.. currentmodule:: flask360361.. autofunction:: render_template362363.. autofunction:: render_template_string364365.. autofunction:: get_template_attribute366367Configuration368-------------369370.. autoclass:: Config371   :members:372373Extensions374----------375376.. data:: flask.ext377378   This module acts as redirect import module to Flask extensions.  It was379   added in 0.8 as the canonical way to import Flask extensions and makes380   it possible for us to have more flexibility in how we distribute381   extensions.382383   If you want to use an extension named “Flask-Foo” you would import it384   from :data:`~flask.ext` as follows::385386        from flask.ext import foo387388   .. versionadded:: 0.8389390Stream Helpers391--------------392393.. autofunction:: stream_with_context394395Useful Internals396----------------397398.. autoclass:: flask.ctx.RequestContext399   :members:400401.. data:: _request_ctx_stack402403   The internal :class:`~werkzeug.local.LocalStack` that is used to implement404   all the context local objects used in Flask.  This is a documented405   instance and can be used by extensions and application code but the406   use is discouraged in general.407408   The following attributes are always present on each layer of the409   stack:410411   `app`412      the active Flask application.413414   `url_adapter`415      the URL adapter that was used to match the request.416417   `request`418      the current request object.419420   `session`421      the active session object.422423   `g`424      an object with all the attributes of the :data:`flask.g` object.425426   `flashes`427      an internal cache for the flashed messages.428429   Example usage::430431      from flask import _request_ctx_stack432433      def get_session():434          ctx = _request_ctx_stack.top435          if ctx is not None:436              return ctx.session437438.. autoclass:: flask.ctx.AppContext439   :members:440441.. data:: _app_ctx_stack442443   Works similar to the request context but only binds the application.444   This is mainly there for extensions to store data.445446   .. versionadded:: 0.9447448.. autoclass:: flask.blueprints.BlueprintSetupState449   :members:450451.. _core-signals-list:452453Signals454-------455456.. versionadded:: 0.6457458.. data:: signals.signals_available459460   ``True`` if the signaling system is available.  This is the case461   when `blinker`_ is installed.462463The following signals exist in Flask:464465.. data:: template_rendered466467   This signal is sent when a template was successfully rendered.  The468   signal is invoked with the instance of the template as `template`469   and the context as dictionary (named `context`).470471   Example subscriber::472473        def log_template_renders(sender, template, context, **extra):474            sender.logger.debug('Rendering template "%s" with context %s',475                                template.name or 'string template',476                                context)477478        from flask import template_rendered479        template_rendered.connect(log_template_renders, app)480481.. data:: flask.before_render_template482   :noindex:483484   This signal is sent before template rendering process. The485   signal is invoked with the instance of the template as `template`486   and the context as dictionary (named `context`).487488   Example subscriber::489490        def log_template_renders(sender, template, context, **extra):491            sender.logger.debug('Rendering template "%s" with context %s',492                                template.name or 'string template',493                                context)494495        from flask import before_render_template496        before_render_template.connect(log_template_renders, app)497498.. data:: request_started499500   This signal is sent when the request context is set up, before501   any request processing happens.  Because the request context is already502   bound, the subscriber can access the request with the standard global503   proxies such as :class:`~flask.request`.504505   Example subscriber::506507        def log_request(sender, **extra):508            sender.logger.debug('Request context is set up')509510        from flask import request_started511        request_started.connect(log_request, app)512513.. data:: request_finished514515   This signal is sent right before the response is sent to the client.516   It is passed the response to be sent named `response`.517518   Example subscriber::519520        def log_response(sender, response, **extra):521            sender.logger.debug('Request context is about to close down.  '522                                'Response: %s', response)523524        from flask import request_finished525        request_finished.connect(log_response, app)526527.. data:: got_request_exception528529   This signal is sent when an exception happens during request processing.530   It is sent *before* the standard exception handling kicks in and even531   in debug mode, where no exception handling happens.  The exception532   itself is passed to the subscriber as `exception`.533534   Example subscriber::535536        def log_exception(sender, exception, **extra):537            sender.logger.debug('Got exception during processing: %s', exception)538539        from flask import got_request_exception540        got_request_exception.connect(log_exception, app)541542.. data:: request_tearing_down543544   This signal is sent when the request is tearing down.  This is always545   called, even if an exception is caused.  Currently functions listening546   to this signal are called after the regular teardown handlers, but this547   is not something you can rely on.548549   Example subscriber::550551        def close_db_connection(sender, **extra):552            session.close()553554        from flask import request_tearing_down555        request_tearing_down.connect(close_db_connection, app)556557   As of Flask 0.9, this will also be passed an `exc` keyword argument558   that has a reference to the exception that caused the teardown if559   there was one.560561.. data:: appcontext_tearing_down562563   This signal is sent when the app context is tearing down.  This is always564   called, even if an exception is caused.  Currently functions listening565   to this signal are called after the regular teardown handlers, but this566   is not something you can rely on.567568   Example subscriber::569570        def close_db_connection(sender, **extra):571            session.close()572573        from flask import appcontext_tearing_down574        appcontext_tearing_down.connect(close_db_connection, app)575576   This will also be passed an `exc` keyword argument that has a reference577   to the exception that caused the teardown if there was one.578579.. data:: appcontext_pushed580581   This signal is sent when an application context is pushed.  The sender582   is the application.  This is usually useful for unittests in order to583   temporarily hook in information.  For instance it can be used to584   set a resource early onto the `g` object.585586   Example usage::587588        from contextlib import contextmanager589        from flask import appcontext_pushed590591        @contextmanager592        def user_set(app, user):593            def handler(sender, **kwargs):594                g.user = user595            with appcontext_pushed.connected_to(handler, app):596                yield597598   And in the testcode::599600        def test_user_me(self):601            with user_set(app, 'john'):602                c = app.test_client()603                resp = c.get('/users/me')604                assert resp.data == 'username=john'605606   .. versionadded:: 0.10607608.. data:: appcontext_popped609610   This signal is sent when an application context is popped.  The sender611   is the application.  This usually falls in line with the612   :data:`appcontext_tearing_down` signal.613614   .. versionadded:: 0.10615616617.. data:: message_flashed618619   This signal is sent when the application is flashing a message.  The620   messages is sent as `message` keyword argument and the category as621   `category`.622623   Example subscriber::624625        recorded = []626        def record(sender, message, category, **extra):627            recorded.append((message, category))628629        from flask import message_flashed630        message_flashed.connect(record, app)631632   .. versionadded:: 0.10633634.. class:: signals.Namespace635636   An alias for :class:`blinker.base.Namespace` if blinker is available,637   otherwise a dummy class that creates fake signals.  This class is638   available for Flask extensions that want to provide the same fallback639   system as Flask itself.640641   .. method:: signal(name, doc=None)642643      Creates a new signal for this namespace if blinker is available,644      otherwise returns a fake signal that has a send method that will645      do nothing but will fail with a :exc:`RuntimeError` for all other646      operations, including connecting.647648649.. _blinker: https://pypi.python.org/pypi/blinker650651.. _class-based-views:652653Class-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:: load_dotenv827828.. autofunction:: with_appcontext829830.. autofunction:: pass_script_info831832   Marks a function so that an instance of :class:`ScriptInfo` is passed833   as first argument to the click callback.834835.. autodata:: run_command836837.. autodata:: shell_command