Skip to content
Myr

api.rst

This file

Path

docs/api.rst

445 lines · 13.4 KiB

Last changed by

Add safe_join: returns the filename used by send_from_directory.Simon Sapinbefore adoption7ed3196

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:192021Module Objects22--------------2324.. autoclass:: Module25   :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 he knows the secret key, so make sure to set that to160something 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.196197198Application Globals199-------------------200201To share data that is valid for one request only from one function to202another, a global variable is not good enough because it would break in203threaded environments.  Flask provides you with a special object that204ensures it is only valid for the active request and that will return205different values for each request.  In a nutshell: it does the right206thing, like it does for :class:`request` and :class:`session`.207208.. data:: g209210   Just store on this whatever you want.  For example a database211   connection or the user that is currently logged in.212213   This is a proxy.  See :ref:`notes-on-proxies` for more information.214215216Useful Functions and Classes217----------------------------218219.. data:: current_app220221   Points to the application handling the request.  This is useful for222   extensions that want to support multiple applications running side223   by side.224225   This is a proxy.  See :ref:`notes-on-proxies` for more information.226227.. autofunction:: has_request_context228229.. autofunction:: url_for230231.. function:: abort(code)232233   Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given234   status code.  For example to abort request handling with a page not235   found exception, you would call ``abort(404)``.236237   :param code: the HTTP error code.238239.. autofunction:: redirect240241.. autofunction:: make_response242243.. autofunction:: send_file244245.. autofunction:: send_from_directory246247.. autofunction:: safe_join248249.. autofunction:: escape250251.. autoclass:: Markup252   :members: escape, unescape, striptags253254Message Flashing255----------------256257.. autofunction:: flash258259.. autofunction:: get_flashed_messages260261Returning JSON262--------------263264.. autofunction:: jsonify265266.. data:: json267268    If JSON support is picked up, this will be the module that Flask is269    using to parse and serialize JSON.  So instead of doing this yourself::270271        try:272            import simplejson as json273        except ImportError:274            import json275276    You can instead just do this::277278        from flask import json279280    For usage examples, read the :mod:`json` documentation.281282    The :func:`~json.dumps` function of this json module is also available283    as filter called ``|tojson`` in Jinja2.  Note that inside `script`284    tags no escaping must take place, so make sure to disable escaping285    with ``|safe`` if you intend to use it inside `script` tags:286287    .. sourcecode:: html+jinja288289        <script type=text/javascript>290            doSomethingWith({{ user.username|tojson|safe }});291        </script>292293    Note that the ``|tojson`` filter escapes forward slashes properly.294295Template Rendering296------------------297298.. autofunction:: render_template299300.. autofunction:: render_template_string301302.. autofunction:: get_template_attribute303304Configuration305-------------306307.. autoclass:: Config308   :members:309310Useful Internals311----------------312313.. data:: _request_ctx_stack314315   The internal :class:`~werkzeug.local.LocalStack` that is used to implement316   all the context local objects used in Flask.  This is a documented317   instance and can be used by extensions and application code but the318   use is discouraged in general.319320   The following attributes are always present on each layer of the321   stack:322323   `app`324      the active Flask application.325326   `url_adapter`327      the URL adapter that was used to match the request.328329   `request`330      the current request object.331332   `session`333      the active session object.334335   `g`336      an object with all the attributes of the :data:`flask.g` object.337338   `flashes`339      an internal cache for the flashed messages.340341   Example usage::342343      from flask import _request_ctx_stack344345      def get_session():346          ctx = _request_ctx_stack.top347          if ctx is not None:348              return ctx.session349350   .. versionchanged:: 0.4351352   The request context is automatically popped at the end of the request353   for you.  In debug mode the request context is kept around if354   exceptions happen so that interactive debuggers have a chance to355   introspect the data.  With 0.4 this can also be forced for requests356   that did not fail and outside of `DEBUG` mode.  By setting357   ``'flask._preserve_context'`` to `True` on the WSGI environment the358   context will not pop itself at the end of the request.  This is used by359   the :meth:`~flask.Flask.test_client` for example to implement the360   deferred cleanup functionality.361362   You might find this helpful for unittests where you need the363   information from the context local around for a little longer.  Make364   sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in365   that situation, otherwise your unittests will leak memory.366367Signals368-------369370.. when modifying this list, also update the one in signals.rst371372.. versionadded:: 0.6373374.. data:: signals_available375376   `True` if the signalling system is available.  This is the case377   when `blinker`_ is installed.378379.. data:: template_rendered380381   This signal is sent when a template was successfully rendered.  The382   signal is invoked with the instance of the template as `template`383   and the context as dictionary (named `context`).384385.. data:: request_started386387   This signal is sent before any request processing started but when the388   request context was set up.  Because the request context is already389   bound, the subscriber can access the request with the standard global390   proxies such as :class:`~flask.request`.391392.. data:: request_finished393394   This signal is sent right before the response is sent to the client.395   It is passed the response to be sent named `response`.396397.. data:: got_request_exception398399   This signal is sent when an exception happens during request processing.400   It is sent *before* the standard exception handling kicks in and even401   in debug mode, where no exception handling happens.  The exception402   itself is passed to the subscriber as `exception`.403404.. currentmodule:: None405406.. class:: flask.signals.Namespace407408   An alias for :class:`blinker.base.Namespace` if blinker is available,409   otherwise a dummy class that creates fake signals.  This class is410   available for Flask extensions that want to provide the same fallback411   system as Flask itself.412413   .. method:: signal(name, doc=None)414415      Creates a new signal for this namespace if blinker is available,416      otherwise returns a fake signal that has a send method that will417      do nothing but will fail with a :exc:`RuntimeError` for all other418      operations, including connecting.419420.. _blinker: http://pypi.python.org/pypi/blinker421422.. _notes-on-proxies:423424Notes On Proxies425----------------426427Some of the objects provided by Flask are proxies to other objects.  The428reason behind this is that these proxies are shared between threads and429they have to dispatch to the actual object bound to a thread behind the430scenes as necessary.431432Most of the time you don't have to care about that, but there are some433exceptions where it is good to know that this object is an actual proxy:434435-   The proxy objects do not fake their inherited types, so if you want to436    perform actual instance checks, you have to do that on the instance437    that is being proxied (see `_get_current_object` below).438-   if the object reference is important (so for example for sending439    :ref:`signals`)440441If you need to get access to the underlying object that is proxied, you442can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::443444    app = current_app._get_current_object()445    my_signal.send(app)