Skip to content
Myr

api.rst

This file

Path

docs/api.rst

494 lines · 14.0 KiB

Last changed by

Added a versionaddedArmin Ronacherbefore adoption6ca321c

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:: Request3233.. class:: request3435   To access incoming request data, you can use the global `request`36   object.  Flask parses incoming request data for you and gives you37   access to it through that global object.  Internally Flask makes38   sure that you always get the correct data for the active thread if you39   are in a multithreaded environment.4041   This is a proxy.  See :ref:`notes-on-proxies` for more information.4243   The request object is an instance of a :class:`~werkzeug.wrappers.Request`44   subclass and provides all of the attributes Werkzeug defines.  This45   just shows a quick overview of the most important ones.4647   .. attribute:: form4849      A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from `POST`50      or `PUT` requests.  Please keep in mind that file uploads will not51      end up here,  but instead in the :attr:`files` attribute.5253   .. attribute:: args5455      A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query56      string.  (The part in the URL after the question mark).5758   .. attribute:: values5960      A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both61      :attr:`form` and :attr:`args`.6263   .. attribute:: cookies6465      A :class:`dict` with the contents of all cookies transmitted with66      the request.6768   .. attribute:: stream6970      If the incoming form data was not encoded with a known mimetype71      the data is stored unmodified in this stream for consumption.  Most72      of the time it is a better idea to use :attr:`data` which will give73      you that data as a string.  The stream only returns the data once.7475   .. attribute:: data7677      Contains the incoming request data as string in case it came with78      a mimetype Flask does not handle.7980   .. attribute:: files8182      A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a83      `POST` or `PUT` request.  Each file is stored as84      :class:`~werkzeug.datastructures.FileStorage` object.  It basically behaves like a85      standard file object you know from Python, with the difference that86      it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can87      store the file on the filesystem.8889   .. attribute:: environ9091      The underlying WSGI environment.9293   .. attribute:: method9495      The current request method (``POST``, ``GET`` etc.)9697   .. attribute:: path98   .. attribute:: script_root99   .. attribute:: url100   .. attribute:: base_url101   .. attribute:: url_root102103      Provides different ways to look at the current URL.  Imagine your104      application is listening on the following URL::105106          http://www.example.com/myapplication107108      And a user requests the following URL::109110          http://www.example.com/myapplication/page.html?x=y111112      In this case the values of the above mentioned attributes would be113      the following:114115      ============= ======================================================116      `path`        ``/page.html``117      `script_root` ``/myapplication``118      `base_url`    ``http://www.example.com/myapplication/page.html``119      `url`         ``http://www.example.com/myapplication/page.html?x=y``120      `url_root`    ``http://www.example.com/myapplication/``121      ============= ======================================================122123   .. attribute:: is_xhr124125      `True` if the request was triggered via a JavaScript126      `XMLHttpRequest`. This only works with libraries that support the127      ``X-Requested-With`` header and set it to `XMLHttpRequest`.128      Libraries that do that are prototype, jQuery and Mochikit and129      probably some more.130131   .. attribute:: json132133      Contains the parsed body of the JSON request if the mimetype of134      the incoming data was `application/json`.  This requires Python 2.6135      or an installed version of simplejson.136137Response Objects138----------------139140.. autoclass:: flask.Response141   :members: set_cookie, data, mimetype142143   .. attribute:: headers144145      A :class:`Headers` object representing the response headers.146147   .. attribute:: status_code148149      The response status as integer.150151152Sessions153--------154155If you have the :attr:`Flask.secret_key` set you can use sessions in Flask156applications.  A session basically makes it possible to remember157information from one request to another.  The way Flask does this is by158using a signed cookie.  So the user can look at the session contents, but159not modify it unless they know the secret key, so make sure to set that160to something complex and unguessable.161162To access the current session you can use the :class:`session` object:163164.. class:: session165166   The session object works pretty much like an ordinary dict, with the167   difference that it keeps track on modifications.168169   This is a proxy.  See :ref:`notes-on-proxies` for more information.170171   The following attributes are interesting:172173   .. attribute:: new174175      `True` if the session is new, `False` otherwise.176177   .. attribute:: modified178179      `True` if the session object detected a modification.  Be advised180      that modifications on mutable structures are not picked up181      automatically, in that situation you have to explicitly set the182      attribute to `True` yourself.  Here an example::183184          # this change is not picked up because a mutable object (here185          # a list) is changed.186          session['objects'].append(42)187          # so mark it as modified yourself188          session.modified = True189190   .. attribute:: permanent191192      If set to `True` the session lives for193      :attr:`~flask.Flask.permanent_session_lifetime` seconds.  The194      default is 31 days.  If set to `False` (which is the default) the195      session will be deleted when the user closes the browser.196197198Session Interface199-----------------200201.. versionadded:: 0.8202203The session interface provides a simple way to replace the session204implementation that Flask is using.205206.. currentmodule:: flask.sessions207208.. autoclass:: SessionInterface209   :members:210211.. autoclass:: SecureCookieSessionInterface212   :members:213214.. autoclass:: NullSession215   :members:216217.. autoclass:: SessionMixin218   :members:219220221Application Globals222-------------------223224.. currentmodule:: flask225226To share data that is valid for one request only from one function to227another, a global variable is not good enough because it would break in228threaded environments.  Flask provides you with a special object that229ensures it is only valid for the active request and that will return230different values for each request.  In a nutshell: it does the right231thing, like it does for :class:`request` and :class:`session`.232233.. data:: g234235   Just store on this whatever you want.  For example a database236   connection or the user that is currently logged in.237238   This is a proxy.  See :ref:`notes-on-proxies` for more information.239240241Useful Functions and Classes242----------------------------243244.. data:: current_app245246   Points to the application handling the request.  This is useful for247   extensions that want to support multiple applications running side248   by side.249250   This is a proxy.  See :ref:`notes-on-proxies` for more information.251252.. autofunction:: has_request_context253254.. autofunction:: url_for255256.. function:: abort(code)257258   Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given259   status code.  For example to abort request handling with a page not260   found exception, you would call ``abort(404)``.261262   :param code: the HTTP error code.263264.. autofunction:: redirect265266.. autofunction:: make_response267268.. 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_messages285286Returning JSON287--------------288289.. autofunction:: jsonify290291.. data:: json292293    If JSON support is picked up, this will be the module that Flask is294    using to parse and serialize JSON.  So instead of doing this yourself::295296        try:297            import simplejson as json298        except ImportError:299            import json300301    You can instead just do this::302303        from flask import json304305    For usage examples, read the :mod:`json` documentation.306307    The :func:`~json.dumps` function of this json module is also available308    as filter called ``|tojson`` in Jinja2.  Note that inside `script`309    tags no escaping must take place, so make sure to disable escaping310    with ``|safe`` if you intend to use it inside `script` tags:311312    .. sourcecode:: html+jinja313314        <script type=text/javascript>315            doSomethingWith({{ user.username|tojson|safe }});316        </script>317318    Note that the ``|tojson`` filter escapes forward slashes properly.319320Template Rendering321------------------322323.. autofunction:: render_template324325.. autofunction:: render_template_string326327.. autofunction:: get_template_attribute328329Configuration330-------------331332.. autoclass:: Config333   :members:334335Useful Internals336----------------337338.. autoclass:: flask.ctx.RequestContext339   :members:340341.. data:: _request_ctx_stack342343   The internal :class:`~werkzeug.local.LocalStack` that is used to implement344   all the context local objects used in Flask.  This is a documented345   instance and can be used by extensions and application code but the346   use is discouraged in general.347348   The following attributes are always present on each layer of the349   stack:350351   `app`352      the active Flask application.353354   `url_adapter`355      the URL adapter that was used to match the request.356357   `request`358      the current request object.359360   `session`361      the active session object.362363   `g`364      an object with all the attributes of the :data:`flask.g` object.365366   `flashes`367      an internal cache for the flashed messages.368369   Example usage::370371      from flask import _request_ctx_stack372373      def get_session():374          ctx = _request_ctx_stack.top375          if ctx is not None:376              return ctx.session377378.. autoclass:: flask.blueprints.BlueprintSetupState379   :members:380381Signals382-------383384.. when modifying this list, also update the one in signals.rst385386.. versionadded:: 0.6387388.. data:: signals_available389390   `True` if the signalling system is available.  This is the case391   when `blinker`_ is installed.392393.. data:: template_rendered394395   This signal is sent when a template was successfully rendered.  The396   signal is invoked with the instance of the template as `template`397   and the context as dictionary (named `context`).398399.. data:: request_started400401   This signal is sent before any request processing started but when the402   request context was set up.  Because the request context is already403   bound, the subscriber can access the request with the standard global404   proxies such as :class:`~flask.request`.405406.. data:: request_finished407408   This signal is sent right before the response is sent to the client.409   It is passed the response to be sent named `response`.410411.. data:: got_request_exception412413   This signal is sent when an exception happens during request processing.414   It is sent *before* the standard exception handling kicks in and even415   in debug mode, where no exception handling happens.  The exception416   itself is passed to the subscriber as `exception`.417418.. data:: request_tearing_down419420   This signal is sent when the application is tearing down the request.421   This is always called, even if an error happened.  No arguments are422   provided.423424.. currentmodule:: None425426.. class:: flask.signals.Namespace427428   An alias for :class:`blinker.base.Namespace` if blinker is available,429   otherwise a dummy class that creates fake signals.  This class is430   available for Flask extensions that want to provide the same fallback431   system as Flask itself.432433   .. method:: signal(name, doc=None)434435      Creates a new signal for this namespace if blinker is available,436      otherwise returns a fake signal that has a send method that will437      do nothing but will fail with a :exc:`RuntimeError` for all other438      operations, including connecting.439440.. _blinker: http://pypi.python.org/pypi/blinker441442Class Based Views443-----------------444445.. versionadded:: 0.7446447.. currentmodule:: None448449.. autoclass:: flask.views.View450   :members:451452.. autoclass:: flask.views.MethodView453   :members:454455.. _view-func-options:456457View Function Options458---------------------459460For internal usage the view functions can have some attributes attached to461customize behavior the view function would normally not have control over.462The following attributes can be provided optionally to either override463some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:464465-   `__name__`: The name of a function is by default used as endpoint.  If466    endpoint is provided explicitly this value is used.  Additionally this467    will be prefixed with the name of the blueprint by default which468    cannot be customized from the function itself.469470-   `methods`: If methods are not provided when the URL rule is added,471    Flask will look on the view function object itself is an `methods`472    attribute exists.  If it does, it will pull the information for the473    methods from there.474475-   `provide_automatic_options`: if this attribute is set Flask will476    either force enable or disable the automatic implementation of the477    HTTP `OPTIONS` response.  This can be useful when working with478    decorators that want to customize the `OPTIONS` response on a per-view479    basis.480481Full example::482483    def index():484        if request.method == 'OPTIONS':485            # custom options handling here486            ...487        return 'Hello World!'488    index.provide_automatic_options = False489    index.methods = ['GET', 'OPTIONS']490491    app.add_url_rule('/', index)492493.. versionadded:: 0.8494   The `provide_automatic_options` functionality was added.