Skip to content
Myr

api.rst

This file

Path

docs/api.rst

826 lines · 24.5 KiB

Last changed by

Merge pull request #2370 from tony/patch-2David Lordbefore adoptione97f6e2

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 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.. 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:189190191Application Globals192-------------------193194.. currentmodule:: flask195196To share data that is valid for one request only from one function to197another, a global variable is not good enough because it would break in198threaded environments.  Flask provides you with a special object that199ensures it is only valid for the active request and that will return200different values for each request.  In a nutshell: it does the right201thing, like it does for :class:`request` and :class:`session`.202203.. data:: g204205   Just store on this whatever you want.  For example a database206   connection or the user that is currently logged in.207208   Starting with Flask 0.10 this is stored on the application context and209   no longer on the request context which means it becomes available if210   only the application context is bound and not yet a request.  This211   is especially useful when combined with the :ref:`faking-resources`212   pattern for testing.213214   Additionally as of 0.10 you can use the :meth:`get` method to215   get an attribute or ``None`` (or the second argument) if it's not set.216   These two usages are now equivalent::217218        user = getattr(flask.g, 'user', None)219        user = flask.g.get('user', None)220221   It's now also possible to use the ``in`` operator on it to see if an222   attribute is defined and it yields all keys on iteration.223224   As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same225   way you would use them on a dictionary.226227   This is a proxy.  See :ref:`notes-on-proxies` for more information.228229230Useful Functions and Classes231----------------------------232233.. data:: current_app234235   Points to the application handling the request.  This is useful for236   extensions that want to support multiple applications running side237   by side.  This is powered by the application context and not by the238   request context, so you can change the value of this proxy by239   using the :meth:`~flask.Flask.app_context` method.240241   This is a proxy.  See :ref:`notes-on-proxies` for more information.242243.. autofunction:: has_request_context244245.. autofunction:: copy_current_request_context246247.. autofunction:: has_app_context248249.. autofunction:: url_for250251.. autofunction:: abort252253.. autofunction:: redirect254255.. autofunction:: make_response256257.. autofunction:: after_this_request258259.. autofunction:: send_file260261.. autofunction:: send_from_directory262263.. autofunction:: safe_join264265.. autofunction:: escape266267.. autoclass:: Markup268   :members: escape, unescape, striptags269270Message Flashing271----------------272273.. autofunction:: flash274275.. autofunction:: get_flashed_messages276277JSON Support278------------279280.. module:: flask.json281282Flask uses ``simplejson`` for the JSON implementation.  Since simplejson283is provided by both the standard library as well as extension, Flask will284try simplejson first and then fall back to the stdlib json module.  On top285of that it will delegate access to the current application's JSON encoders286and decoders for easier customization.287288So for starters instead of doing::289290    try:291        import simplejson as json292    except ImportError:293        import json294295You can instead just do this::296297    from flask import json298299For usage examples, read the :mod:`json` documentation in the standard300library.  The following extensions are by default applied to the stdlib's301JSON module:3023031.  ``datetime`` objects are serialized as :rfc:`822` strings.3042.  Any object with an ``__html__`` method (like :class:`~flask.Markup`)305    will have that method called and then the return value is serialized306    as string.307308The :func:`~htmlsafe_dumps` function of this json module is also available309as filter called ``|tojson`` in Jinja2.  Note that inside ``script``310tags no escaping must take place, so make sure to disable escaping311with ``|safe`` if you intend to use it inside ``script`` tags unless312you are using Flask 0.10 which implies that:313314.. sourcecode:: html+jinja315316    <script type=text/javascript>317        doSomethingWith({{ user.username|tojson|safe }});318    </script>319320.. admonition:: Auto-Sort JSON Keys321322    The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be323    set to false to stop Flask from auto-sorting keys.  By default sorting324    is enabled and outside of the app context sorting is turned on.325326    Notice that disabling key sorting can cause issues when using content327    based HTTP caches and Python's hash randomization feature.328329.. autofunction:: jsonify330331.. autofunction:: dumps332333.. autofunction:: dump334335.. autofunction:: loads336337.. autofunction:: load338339.. autoclass:: JSONEncoder340   :members:341342.. autoclass:: JSONDecoder343   :members:344345.. automodule:: flask.json.tag346347Template Rendering348------------------349350.. currentmodule:: flask351352.. autofunction:: render_template353354.. autofunction:: render_template_string355356.. autofunction:: get_template_attribute357358Configuration359-------------360361.. autoclass:: Config362   :members:363364Extensions365----------366367.. data:: flask.ext368369   This module acts as redirect import module to Flask extensions.  It was370   added in 0.8 as the canonical way to import Flask extensions and makes371   it possible for us to have more flexibility in how we distribute372   extensions.373374   If you want to use an extension named “Flask-Foo” you would import it375   from :data:`~flask.ext` as follows::376377        from flask.ext import foo378379   .. versionadded:: 0.8380381Stream Helpers382--------------383384.. autofunction:: stream_with_context385386Useful Internals387----------------388389.. autoclass:: flask.ctx.RequestContext390   :members:391392.. data:: _request_ctx_stack393394   The internal :class:`~werkzeug.local.LocalStack` that is used to implement395   all the context local objects used in Flask.  This is a documented396   instance and can be used by extensions and application code but the397   use is discouraged in general.398399   The following attributes are always present on each layer of the400   stack:401402   `app`403      the active Flask application.404405   `url_adapter`406      the URL adapter that was used to match the request.407408   `request`409      the current request object.410411   `session`412      the active session object.413414   `g`415      an object with all the attributes of the :data:`flask.g` object.416417   `flashes`418      an internal cache for the flashed messages.419420   Example usage::421422      from flask import _request_ctx_stack423424      def get_session():425          ctx = _request_ctx_stack.top426          if ctx is not None:427              return ctx.session428429.. autoclass:: flask.ctx.AppContext430   :members:431432.. data:: _app_ctx_stack433434   Works similar to the request context but only binds the application.435   This is mainly there for extensions to store data.436437   .. versionadded:: 0.9438439.. autoclass:: flask.blueprints.BlueprintSetupState440   :members:441442.. _core-signals-list:443444Signals445-------446447.. versionadded:: 0.6448449.. data:: signals.signals_available450451   ``True`` if the signaling system is available.  This is the case452   when `blinker`_ is installed.453454The following signals exist in Flask:455456.. data:: template_rendered457458   This signal is sent when a template was successfully rendered.  The459   signal is invoked with the instance of the template as `template`460   and the context as dictionary (named `context`).461462   Example subscriber::463464        def log_template_renders(sender, template, context, **extra):465            sender.logger.debug('Rendering template "%s" with context %s',466                                template.name or 'string template',467                                context)468469        from flask import template_rendered470        template_rendered.connect(log_template_renders, app)471472.. data:: flask.before_render_template473   :noindex:474475   This signal is sent before template rendering process. The476   signal is invoked with the instance of the template as `template`477   and the context as dictionary (named `context`).478479   Example subscriber::480481        def log_template_renders(sender, template, context, **extra):482            sender.logger.debug('Rendering template "%s" with context %s',483                                template.name or 'string template',484                                context)485486        from flask import before_render_template487        before_render_template.connect(log_template_renders, app)488489.. data:: request_started490491   This signal is sent when the request context is set up, before492   any request processing happens.  Because the request context is already493   bound, the subscriber can access the request with the standard global494   proxies such as :class:`~flask.request`.495496   Example subscriber::497498        def log_request(sender, **extra):499            sender.logger.debug('Request context is set up')500501        from flask import request_started502        request_started.connect(log_request, app)503504.. data:: request_finished505506   This signal is sent right before the response is sent to the client.507   It is passed the response to be sent named `response`.508509   Example subscriber::510511        def log_response(sender, response, **extra):512            sender.logger.debug('Request context is about to close down.  '513                                'Response: %s', response)514515        from flask import request_finished516        request_finished.connect(log_response, app)517518.. data:: got_request_exception519520   This signal is sent when an exception happens during request processing.521   It is sent *before* the standard exception handling kicks in and even522   in debug mode, where no exception handling happens.  The exception523   itself is passed to the subscriber as `exception`.524525   Example subscriber::526527        def log_exception(sender, exception, **extra):528            sender.logger.debug('Got exception during processing: %s', exception)529530        from flask import got_request_exception531        got_request_exception.connect(log_exception, app)532533.. data:: request_tearing_down534535   This signal is sent when the request is tearing down.  This is always536   called, even if an exception is caused.  Currently functions listening537   to this signal are called after the regular teardown handlers, but this538   is not something you can rely on.539540   Example subscriber::541542        def close_db_connection(sender, **extra):543            session.close()544545        from flask import request_tearing_down546        request_tearing_down.connect(close_db_connection, app)547548   As of Flask 0.9, this will also be passed an `exc` keyword argument549   that has a reference to the exception that caused the teardown if550   there was one.551552.. data:: appcontext_tearing_down553554   This signal is sent when the app context is tearing down.  This is always555   called, even if an exception is caused.  Currently functions listening556   to this signal are called after the regular teardown handlers, but this557   is not something you can rely on.558559   Example subscriber::560561        def close_db_connection(sender, **extra):562            session.close()563564        from flask import appcontext_tearing_down565        appcontext_tearing_down.connect(close_db_connection, app)566567   This will also be passed an `exc` keyword argument that has a reference568   to the exception that caused the teardown if there was one.569570.. data:: appcontext_pushed571572   This signal is sent when an application context is pushed.  The sender573   is the application.  This is usually useful for unittests in order to574   temporarily hook in information.  For instance it can be used to575   set a resource early onto the `g` object.576577   Example usage::578579        from contextlib import contextmanager580        from flask import appcontext_pushed581582        @contextmanager583        def user_set(app, user):584            def handler(sender, **kwargs):585                g.user = user586            with appcontext_pushed.connected_to(handler, app):587                yield588589   And in the testcode::590591        def test_user_me(self):592            with user_set(app, 'john'):593                c = app.test_client()594                resp = c.get('/users/me')595                assert resp.data == 'username=john'596597   .. versionadded:: 0.10598599.. data:: appcontext_popped600601   This signal is sent when an application context is popped.  The sender602   is the application.  This usually falls in line with the603   :data:`appcontext_tearing_down` signal.604605   .. versionadded:: 0.10606607608.. data:: message_flashed609610   This signal is sent when the application is flashing a message.  The611   messages is sent as `message` keyword argument and the category as612   `category`.613614   Example subscriber::615616        recorded = []617        def record(sender, message, category, **extra):618            recorded.append((message, category))619620        from flask import message_flashed621        message_flashed.connect(record, app)622623   .. versionadded:: 0.10624625.. class:: signals.Namespace626627   An alias for :class:`blinker.base.Namespace` if blinker is available,628   otherwise a dummy class that creates fake signals.  This class is629   available for Flask extensions that want to provide the same fallback630   system as Flask itself.631632   .. method:: signal(name, doc=None)633634      Creates a new signal for this namespace if blinker is available,635      otherwise returns a fake signal that has a send method that will636      do nothing but will fail with a :exc:`RuntimeError` for all other637      operations, including connecting.638639640.. _blinker: https://pypi.python.org/pypi/blinker641642.. _class-based-views:643644Class-Based Views645-----------------646647.. versionadded:: 0.7648649.. currentmodule:: None650651.. autoclass:: flask.views.View652   :members:653654.. autoclass:: flask.views.MethodView655   :members:656657.. _url-route-registrations:658659URL Route Registrations660-----------------------661662Generally there are three ways to define rules for the routing system:6636641.  You can use the :meth:`flask.Flask.route` decorator.6652.  You can use the :meth:`flask.Flask.add_url_rule` function.6663.  You can directly access the underlying Werkzeug routing system667    which is exposed as :attr:`flask.Flask.url_map`.668669Variable parts in the route can be specified with angular brackets670(``/user/<username>``).  By default a variable part in the URL accepts any671string without a slash however a different converter can be specified as672well by using ``<converter:name>``.673674Variable parts are passed to the view function as keyword arguments.675676The following converters are available:677678=========== ===============================================679`string`    accepts any text without a slash (the default)680`int`       accepts integers681`float`     like `int` but for floating point values682`path`      like the default but also accepts slashes683`any`       matches one of the items provided684`uuid`      accepts UUID strings685=========== ===============================================686687Custom converters can be defined using :attr:`flask.Flask.url_map`.688689Here are some examples::690691    @app.route('/')692    def index():693        pass694695    @app.route('/<username>')696    def show_user(username):697        pass698699    @app.route('/post/<int:post_id>')700    def show_post(post_id):701        pass702703An important detail to keep in mind is how Flask deals with trailing704slashes.  The idea is to keep each URL unique so the following rules705apply:7067071. If a rule ends with a slash and is requested without a slash by the708   user, the user is automatically redirected to the same page with a709   trailing slash attached.7102. If a rule does not end with a trailing slash and the user requests the711   page with a trailing slash, a 404 not found is raised.712713This is consistent with how web servers deal with static files.  This714also makes it possible to use relative link targets safely.715716You can also define multiple rules for the same function.  They have to be717unique however.  Defaults can also be specified.  Here for example is a718definition for a URL that accepts an optional page::719720    @app.route('/users/', defaults={'page': 1})721    @app.route('/users/page/<int:page>')722    def show_users(page):723        pass724725This specifies that ``/users/`` will be the URL for page one and726``/users/page/N`` will be the URL for page `N`.727728Here are the parameters that :meth:`~flask.Flask.route` and729:meth:`~flask.Flask.add_url_rule` accept.  The only difference is that730with the route parameter the view function is defined with the decorator731instead of the `view_func` parameter.732733=============== ==========================================================734`rule`          the URL rule as string735`endpoint`      the endpoint for the registered URL rule.  Flask itself736                assumes that the name of the view function is the name737                of the endpoint if not explicitly stated.738`view_func`     the function to call when serving a request to the739                provided endpoint.  If this is not provided one can740                specify the function later by storing it in the741                :attr:`~flask.Flask.view_functions` dictionary with the742                endpoint as key.743`defaults`      A dictionary with defaults for this rule.  See the744                example above for how defaults work.745`subdomain`     specifies the rule for the subdomain in case subdomain746                matching is in use.  If not specified the default747                subdomain is assumed.748`**options`     the options to be forwarded to the underlying749                :class:`~werkzeug.routing.Rule` object.  A change to750                Werkzeug is handling of method options.  methods is a list751                of methods this rule should be limited to (``GET``, ``POST``752                etc.).  By default a rule just listens for ``GET`` (and753                implicitly ``HEAD``).  Starting with Flask 0.6, ``OPTIONS`` is754                implicitly added and handled by the standard request755                handling.  They have to be specified as keyword arguments.756=============== ==========================================================757758.. _view-func-options:759760View Function Options761---------------------762763For internal usage the view functions can have some attributes attached to764customize behavior the view function would normally not have control over.765The following attributes can be provided optionally to either override766some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:767768-   `__name__`: The name of a function is by default used as endpoint.  If769    endpoint is provided explicitly this value is used.  Additionally this770    will be prefixed with the name of the blueprint by default which771    cannot be customized from the function itself.772773-   `methods`: If methods are not provided when the URL rule is added,774    Flask will look on the view function object itself if a `methods`775    attribute exists.  If it does, it will pull the information for the776    methods from there.777778-   `provide_automatic_options`: if this attribute is set Flask will779    either force enable or disable the automatic implementation of the780    HTTP ``OPTIONS`` response.  This can be useful when working with781    decorators that want to customize the ``OPTIONS`` response on a per-view782    basis.783784-   `required_methods`: if this attribute is set, Flask will always add785    these methods when registering a URL rule even if the methods were786    explicitly overridden in the ``route()`` call.787788Full example::789790    def index():791        if request.method == 'OPTIONS':792            # custom options handling here793            ...794        return 'Hello World!'795    index.provide_automatic_options = False796    index.methods = ['GET', 'OPTIONS']797798    app.add_url_rule('/', index)799800.. versionadded:: 0.8801   The `provide_automatic_options` functionality was added.802803Command Line Interface804----------------------805806.. currentmodule:: flask.cli807808.. autoclass:: FlaskGroup809   :members:810811.. autoclass:: AppGroup812   :members:813814.. autoclass:: ScriptInfo815   :members:816817.. autofunction:: with_appcontext818819.. autofunction:: pass_script_info820821   Marks a function so that an instance of :class:`ScriptInfo` is passed822   as first argument to the click callback.823824.. autodata:: run_command825826.. autodata:: shell_command