Skip to content
Myr

api.rst

This file

Path

docs/api.rst

790 lines · 23.8 KiB

Last changed by

Fix broken linkMarkus Unterwaditzerbefore adoption9c1cf1b

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:3334   .. attribute:: form3536      A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from ``POST``37      or ``PUT`` requests.  Please keep in mind that file uploads will not38      end up here,  but instead in the :attr:`files` attribute.3940   .. attribute:: args4142      A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query43      string.  (The part in the URL after the question mark).4445   .. attribute:: values4647      A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both48      :attr:`form` and :attr:`args`.4950   .. attribute:: cookies5152      A :class:`dict` with the contents of all cookies transmitted with53      the request.5455   .. attribute:: stream5657      If the incoming form data was not encoded with a known mimetype58      the data is stored unmodified in this stream for consumption.  Most59      of the time it is a better idea to use :attr:`data` which will give60      you that data as a string.  The stream only returns the data once.6162   .. attribute:: headers6364      The incoming request headers as a dictionary like object.6566   .. attribute:: data6768      Contains the incoming request data as string in case it came with69      a mimetype Flask does not handle.7071   .. attribute:: files7273      A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a74      ``POST`` or ``PUT`` request.  Each file is stored as75      :class:`~werkzeug.datastructures.FileStorage` object.  It basically behaves like a76      standard file object you know from Python, with the difference that77      it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can78      store the file on the filesystem.7980   .. attribute:: environ8182      The underlying WSGI environment.8384   .. attribute:: method8586      The current request method (``POST``, ``GET`` etc.)8788   .. attribute:: path89   .. attribute:: full_path90   .. attribute:: script_root91   .. attribute:: url92   .. attribute:: base_url93   .. attribute:: url_root9495      Provides different ways to look at the current `IRI96      <http://tools.ietf.org/html/rfc3987>`_.  Imagine your application is97      listening on the following application root::9899          http://www.example.com/myapplication100101      And a user requests the following URI::102103          http://www.example.com/myapplication/%CF%80/page.html?x=y104105      In this case the values of the above mentioned attributes would be106      the following:107108      ============= ======================================================109      `path`        ``u'/π/page.html'``110      `full_path`   ``u'/π/page.html?x=y'``111      `script_root` ``u'/myapplication'``112      `base_url`    ``u'http://www.example.com/myapplication/π/page.html'``113      `url`         ``u'http://www.example.com/myapplication/π/page.html?x=y'``114      `url_root`    ``u'http://www.example.com/myapplication/'``115      ============= ======================================================116117   .. attribute:: is_xhr118119      ``True`` if the request was triggered via a JavaScript120      `XMLHttpRequest`. This only works with libraries that support the121      ``X-Requested-With`` header and set it to `XMLHttpRequest`.122      Libraries that do that are prototype, jQuery and Mochikit and123      probably some more.124125.. class:: request126127   To access incoming request data, you can use the global `request`128   object.  Flask parses incoming request data for you and gives you129   access to it through that global object.  Internally Flask makes130   sure that you always get the correct data for the active thread if you131   are in a multithreaded environment.132133   This is a proxy.  See :ref:`notes-on-proxies` for more information.134135   The request object is an instance of a :class:`~werkzeug.wrappers.Request`136   subclass and provides all of the attributes Werkzeug defines.  This137   just shows a quick overview of the most important ones.138139140Response Objects141----------------142143.. autoclass:: flask.Response144   :members: set_cookie, data, mimetype145146   .. attribute:: headers147148      A :class:`~werkzeug.datastructures.Headers` object representing the response headers.149150   .. attribute:: status151152      A string with a response status.153154   .. attribute:: status_code155156      The response status as integer.157158159Sessions160--------161162If you have the :attr:`Flask.secret_key` set you can use sessions in Flask163applications.  A session basically makes it possible to remember164information from one request to another.  The way Flask does this is by165using a signed cookie.  So the user can look at the session contents, but166not modify it unless they know the secret key, so make sure to set that167to something complex and unguessable.168169To access the current session you can use the :class:`session` object:170171.. class:: session172173   The session object works pretty much like an ordinary dict, with the174   difference that it keeps track on modifications.175176   This is a proxy.  See :ref:`notes-on-proxies` for more information.177178   The following attributes are interesting:179180   .. attribute:: new181182      ``True`` if the session is new, ``False`` otherwise.183184   .. attribute:: modified185186      ``True`` if the session object detected a modification.  Be advised187      that modifications on mutable structures are not picked up188      automatically, in that situation you have to explicitly set the189      attribute to ``True`` yourself.  Here an example::190191          # this change is not picked up because a mutable object (here192          # a list) is changed.193          session['objects'].append(42)194          # so mark it as modified yourself195          session.modified = True196197   .. attribute:: permanent198199      If set to ``True`` the session lives for200      :attr:`~flask.Flask.permanent_session_lifetime` seconds.  The201      default is 31 days.  If set to ``False`` (which is the default) the202      session will be deleted when the user closes the browser.203204205Session Interface206-----------------207208.. versionadded:: 0.8209210The session interface provides a simple way to replace the session211implementation that Flask is using.212213.. currentmodule:: flask.sessions214215.. autoclass:: SessionInterface216   :members:217218.. autoclass:: SecureCookieSessionInterface219   :members:220221.. autoclass:: SecureCookieSession222   :members:223224.. autoclass:: NullSession225   :members:226227.. autoclass:: SessionMixin228   :members:229230.. autodata:: session_json_serializer231232   This object provides dumping and loading methods similar to simplejson233   but it also tags certain builtin Python objects that commonly appear in234   sessions.  Currently the following extended values are supported in235   the JSON it dumps:236237   -    :class:`~markupsafe.Markup` objects238   -    :class:`~uuid.UUID` objects239   -    :class:`~datetime.datetime` objects240   -   :class:`tuple`\s241242.. admonition:: Notice243244   The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer245   starting with Flask 0.8.  Either catch this down yourself or use246   the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the247   app which converts the result to an integer automatically.248249250Test Client251-----------252253.. currentmodule:: flask.testing254255.. autoclass:: FlaskClient256   :members:257258259Application Globals260-------------------261262.. currentmodule:: flask263264To share data that is valid for one request only from one function to265another, a global variable is not good enough because it would break in266threaded environments.  Flask provides you with a special object that267ensures it is only valid for the active request and that will return268different values for each request.  In a nutshell: it does the right269thing, like it does for :class:`request` and :class:`session`.270271.. data:: g272273   Just store on this whatever you want.  For example a database274   connection or the user that is currently logged in.275276   Starting with Flask 0.10 this is stored on the application context and277   no longer on the request context which means it becomes available if278   only the application context is bound and not yet a request.  This279   is especially useful when combined with the :ref:`faking-resources`280   pattern for testing.281282   Additionally as of 0.10 you can use the :meth:`get` method to283   get an attribute or ``None`` (or the second argument) if it's not set.284   These two usages are now equivalent::285286        user = getattr(flask.g, 'user', None)287        user = flask.g.get('user', None)288289   It's now also possible to use the ``in`` operator on it to see if an290   attribute is defined and it yields all keys on iteration.291292   This is a proxy.  See :ref:`notes-on-proxies` for more information.293294295Useful Functions and Classes296----------------------------297298.. data:: current_app299300   Points to the application handling the request.  This is useful for301   extensions that want to support multiple applications running side302   by side.  This is powered by the application context and not by the303   request context, so you can change the value of this proxy by304   using the :meth:`~flask.Flask.app_context` method.305306   This is a proxy.  See :ref:`notes-on-proxies` for more information.307308.. autofunction:: has_request_context309310.. autofunction:: copy_current_request_context311312.. autofunction:: has_app_context313314.. autofunction:: url_for315316.. function:: abort(code)317318   Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given319   status code.  For example to abort request handling with a page not320   found exception, you would call ``abort(404)``.321322   :param code: the HTTP error code.323324.. autofunction:: redirect325326.. autofunction:: make_response327328.. autofunction:: after_this_request329330.. autofunction:: send_file331332.. autofunction:: send_from_directory333334.. autofunction:: safe_join335336.. autofunction:: escape337338.. autoclass:: Markup339   :members: escape, unescape, striptags340341Message Flashing342----------------343344.. autofunction:: flash345346.. autofunction:: get_flashed_messages347348JSON Support349------------350351.. module:: flask.json352353Flask uses ``simplejson`` for the JSON implementation.  Since simplejson354is provided by both the standard library as well as extension, Flask will355try simplejson first and then fall back to the stdlib json module.  On top356of that it will delegate access to the current application's JSON encoders357and decoders for easier customization.358359So for starters instead of doing::360361    try:362        import simplejson as json363    except ImportError:364        import json365366You can instead just do this::367368    from flask import json369370For usage examples, read the :mod:`json` documentation in the standard371library.  The following extensions are by default applied to the stdlib's372JSON module:3733741.  ``datetime`` objects are serialized as :rfc:`822` strings.3752.  Any object with an ``__html__`` method (like :class:`~flask.Markup`)376    will have that method called and then the return value is serialized377    as string.378379The :func:`~htmlsafe_dumps` function of this json module is also available380as filter called ``|tojson`` in Jinja2.  Note that inside ``script``381tags no escaping must take place, so make sure to disable escaping382with ``|safe`` if you intend to use it inside ``script`` tags unless383you are using Flask 0.10 which implies that:384385.. sourcecode:: html+jinja386387    <script type=text/javascript>388        doSomethingWith({{ user.username|tojson|safe }});389    </script>390391.. admonition:: Auto-Sort JSON Keys392393    The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be394    set to false to stop Flask from auto-sorting keys.  By default sorting395    is enabled and outside of the app context sorting is turned on.396397    Notice that disabling key sorting can cause issues when using content398    based HTTP caches and Python's hash randomization feature.399400.. autofunction:: jsonify401402.. autofunction:: dumps403404.. autofunction:: dump405406.. autofunction:: loads407408.. autofunction:: load409410.. autoclass:: JSONEncoder411   :members:412413.. autoclass:: JSONDecoder414   :members:415416Template Rendering417------------------418419.. currentmodule:: flask420421.. autofunction:: render_template422423.. autofunction:: render_template_string424425.. autofunction:: get_template_attribute426427Configuration428-------------429430.. autoclass:: Config431   :members:432433Extensions434----------435436.. data:: flask.ext437438   This module acts as redirect import module to Flask extensions.  It was439   added in 0.8 as the canonical way to import Flask extensions and makes440   it possible for us to have more flexibility in how we distribute441   extensions.442443   If you want to use an extension named “Flask-Foo” you would import it444   from :data:`~flask.ext` as follows::445446        from flask.ext import foo447448   .. versionadded:: 0.8449450Stream Helpers451--------------452453.. autofunction:: stream_with_context454455Useful Internals456----------------457458.. autoclass:: flask.ctx.RequestContext459   :members:460461.. data:: _request_ctx_stack462463   The internal :class:`~werkzeug.local.LocalStack` that is used to implement464   all the context local objects used in Flask.  This is a documented465   instance and can be used by extensions and application code but the466   use is discouraged in general.467468   The following attributes are always present on each layer of the469   stack:470471   `app`472      the active Flask application.473474   `url_adapter`475      the URL adapter that was used to match the request.476477   `request`478      the current request object.479480   `session`481      the active session object.482483   `g`484      an object with all the attributes of the :data:`flask.g` object.485486   `flashes`487      an internal cache for the flashed messages.488489   Example usage::490491      from flask import _request_ctx_stack492493      def get_session():494          ctx = _request_ctx_stack.top495          if ctx is not None:496              return ctx.session497498.. autoclass:: flask.ctx.AppContext499   :members:500501.. data:: _app_ctx_stack502503   Works similar to the request context but only binds the application.504   This is mainly there for extensions to store data.505506   .. versionadded:: 0.9507508.. autoclass:: flask.blueprints.BlueprintSetupState509   :members:510511Signals512-------513514.. when modifying this list, also update the one in signals.rst515516.. versionadded:: 0.6517518.. data:: signals_available519520   ``True`` if the signaling system is available.  This is the case521   when `blinker`_ is installed.522523.. data:: template_rendered524525   This signal is sent when a template was successfully rendered.  The526   signal is invoked with the instance of the template as `template`527   and the context as dictionary (named `context`).528529.. data:: request_started530531   This signal is sent before any request processing started but when the532   request context was set up.  Because the request context is already533   bound, the subscriber can access the request with the standard global534   proxies such as :class:`~flask.request`.535536.. data:: request_finished537538   This signal is sent right before the response is sent to the client.539   It is passed the response to be sent named `response`.540541.. data:: got_request_exception542543   This signal is sent when an exception happens during request processing.544   It is sent *before* the standard exception handling kicks in and even545   in debug mode, where no exception handling happens.  The exception546   itself is passed to the subscriber as `exception`.547548.. data:: request_tearing_down549550   This signal is sent when the application is tearing down the request.551   This is always called, even if an error happened.  An `exc` keyword552   argument is passed with the exception that caused the teardown.553554   .. versionchanged:: 0.9555      The `exc` parameter was added.556557.. data:: appcontext_tearing_down558559   This signal is sent when the application is tearing down the560   application context.  This is always called, even if an error happened.561   An `exc` keyword argument is passed with the exception that caused the562   teardown.  The sender is the application.563564.. data:: appcontext_pushed565566   This signal is sent when an application context is pushed.  The sender567   is the application.568569   .. versionadded:: 0.10570571.. data:: appcontext_popped572573   This signal is sent when an application context is popped.  The sender574   is the application.  This usually falls in line with the575   :data:`appcontext_tearing_down` signal.576577   .. versionadded:: 0.10578579.. data:: message_flashed580581   This signal is sent when the application is flashing a message.  The582   messages is sent as `message` keyword argument and the category as583   `category`.584585   .. versionadded:: 0.10586587.. currentmodule:: None588589.. class:: flask.signals.Namespace590591   An alias for :class:`blinker.base.Namespace` if blinker is available,592   otherwise a dummy class that creates fake signals.  This class is593   available for Flask extensions that want to provide the same fallback594   system as Flask itself.595596   .. method:: signal(name, doc=None)597598      Creates a new signal for this namespace if blinker is available,599      otherwise returns a fake signal that has a send method that will600      do nothing but will fail with a :exc:`RuntimeError` for all other601      operations, including connecting.602603.. _blinker: https://pypi.python.org/pypi/blinker604605Class-Based Views606-----------------607608.. versionadded:: 0.7609610.. currentmodule:: None611612.. autoclass:: flask.views.View613   :members:614615.. autoclass:: flask.views.MethodView616   :members:617618.. _url-route-registrations:619620URL Route Registrations621-----------------------622623Generally there are three ways to define rules for the routing system:6246251.  You can use the :meth:`flask.Flask.route` decorator.6262.  You can use the :meth:`flask.Flask.add_url_rule` function.6273.  You can directly access the underlying Werkzeug routing system628    which is exposed as :attr:`flask.Flask.url_map`.629630Variable parts in the route can be specified with angular brackets631(``/user/<username>``).  By default a variable part in the URL accepts any632string without a slash however a different converter can be specified as633well by using ``<converter:name>``.634635Variable parts are passed to the view function as keyword arguments.636637The following converters are available:638639=========== ===============================================640`string`    accepts any text without a slash (the default)641`int`       accepts integers642`float`     like `int` but for floating point values643`path`      like the default but also accepts slashes644=========== ===============================================645646Here are some examples::647648    @app.route('/')649    def index():650        pass651652    @app.route('/<username>')653    def show_user(username):654        pass655656    @app.route('/post/<int:post_id>')657    def show_post(post_id):658        pass659660An important detail to keep in mind is how Flask deals with trailing661slashes.  The idea is to keep each URL unique so the following rules662apply:6636641. If a rule ends with a slash and is requested without a slash by the665   user, the user is automatically redirected to the same page with a666   trailing slash attached.6672. If a rule does not end with a trailing slash and the user requests the668   page with a trailing slash, a 404 not found is raised.669670This is consistent with how web servers deal with static files.  This671also makes it possible to use relative link targets safely.672673You can also define multiple rules for the same function.  They have to be674unique however.  Defaults can also be specified.  Here for example is a675definition for a URL that accepts an optional page::676677    @app.route('/users/', defaults={'page': 1})678    @app.route('/users/page/<int:page>')679    def show_users(page):680        pass681682This specifies that ``/users/`` will be the URL for page one and683``/users/page/N`` will be the URL for page `N`.684685Here are the parameters that :meth:`~flask.Flask.route` and686:meth:`~flask.Flask.add_url_rule` accept.  The only difference is that687with the route parameter the view function is defined with the decorator688instead of the `view_func` parameter.689690=============== ==========================================================691`rule`          the URL rule as string692`endpoint`      the endpoint for the registered URL rule.  Flask itself693                assumes that the name of the view function is the name694                of the endpoint if not explicitly stated.695`view_func`     the function to call when serving a request to the696                provided endpoint.  If this is not provided one can697                specify the function later by storing it in the698                :attr:`~flask.Flask.view_functions` dictionary with the699                endpoint as key.700`defaults`      A dictionary with defaults for this rule.  See the701                example above for how defaults work.702`subdomain`     specifies the rule for the subdomain in case subdomain703                matching is in use.  If not specified the default704                subdomain is assumed.705`**options`     the options to be forwarded to the underlying706                :class:`~werkzeug.routing.Rule` object.  A change to707                Werkzeug is handling of method options.  methods is a list708                of methods this rule should be limited to (``GET``, ``POST``709                etc.).  By default a rule just listens for ``GET`` (and710                implicitly ``HEAD``).  Starting with Flask 0.6, ``OPTIONS`` is711                implicitly added and handled by the standard request712                handling.  They have to be specified as keyword arguments.713=============== ==========================================================714715.. _view-func-options:716717View Function Options718---------------------719720For internal usage the view functions can have some attributes attached to721customize behavior the view function would normally not have control over.722The following attributes can be provided optionally to either override723some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:724725-   `__name__`: The name of a function is by default used as endpoint.  If726    endpoint is provided explicitly this value is used.  Additionally this727    will be prefixed with the name of the blueprint by default which728    cannot be customized from the function itself.729730-   `methods`: If methods are not provided when the URL rule is added,731    Flask will look on the view function object itself if a `methods`732    attribute exists.  If it does, it will pull the information for the733    methods from there.734735-   `provide_automatic_options`: if this attribute is set Flask will736    either force enable or disable the automatic implementation of the737    HTTP ``OPTIONS`` response.  This can be useful when working with738    decorators that want to customize the ``OPTIONS`` response on a per-view739    basis.740741-   `required_methods`: if this attribute is set, Flask will always add742    these methods when registering a URL rule even if the methods were743    explicitly overridden in the ``route()`` call.744745Full example::746747    def index():748        if request.method == 'OPTIONS':749            # custom options handling here750            ...751        return 'Hello World!'752    index.provide_automatic_options = False753    index.methods = ['GET', 'OPTIONS']754755    app.add_url_rule('/', index)756757.. versionadded:: 0.8758   The `provide_automatic_options` functionality was added.759760Command Line Interface761----------------------762763.. currentmodule:: flask.cli764765.. autoclass:: FlaskGroup766   :members:767768.. autoclass:: AppGroup769   :members:770771.. autoclass:: ScriptInfo772   :members:773774.. autofunction:: with_appcontext775776.. autofunction:: pass_script_info777778   Marks a function so that an instance of :class:`ScriptInfo` is passed779   as first argument to the click callback.780781.. autofunction:: script_info_option782783   A special decorator that informs a click callback to be passed the784   script info object as first argument.  This is normally not useful785   unless you implement very special commands like the run command which786   does not want the application to be loaded yet.787788.. autodata:: run_command789790.. autodata:: shell_command