Skip to content
Myr

api.rst

This file

Path

docs/api.rst

503 lines · 14.0 KiB

Last changed by

The test client and test_request_context are now both using the same logic internally for creating the environ. Also they use APPLICATION_ROOT now.Armin Ronacherbefore adoptione853a0f

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:: script_root90   .. attribute:: url91   .. attribute:: base_url92   .. attribute:: url_root9394      Provides different ways to look at the current URL.  Imagine your95      application is listening on the following URL::9697          http://www.example.com/myapplication9899      And a user requests the following URL::100101          http://www.example.com/myapplication/page.html?x=y102103      In this case the values of the above mentioned attributes would be104      the following:105106      ============= ======================================================107      `path`        ``/page.html``108      `script_root` ``/myapplication``109      `base_url`    ``http://www.example.com/myapplication/page.html``110      `url`         ``http://www.example.com/myapplication/page.html?x=y``111      `url_root`    ``http://www.example.com/myapplication/``112      ============= ======================================================113114   .. attribute:: is_xhr115116      `True` if the request was triggered via a JavaScript117      `XMLHttpRequest`. This only works with libraries that support the118      ``X-Requested-With`` header and set it to `XMLHttpRequest`.119      Libraries that do that are prototype, jQuery and Mochikit and120      probably some more.121122.. class:: request123124   To access incoming request data, you can use the global `request`125   object.  Flask parses incoming request data for you and gives you126   access to it through that global object.  Internally Flask makes127   sure that you always get the correct data for the active thread if you128   are in a multithreaded environment.129130   This is a proxy.  See :ref:`notes-on-proxies` for more information.131132   The request object is an instance of a :class:`~werkzeug.wrappers.Request`133   subclass and provides all of the attributes Werkzeug defines.  This134   just shows a quick overview of the most important ones.135136137Response 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:219220221Test Client222-----------223224.. currentmodule:: flask.testing225226.. autoclass:: FlaskClient227   :members:228229230Application Globals231-------------------232233.. currentmodule:: flask234235To share data that is valid for one request only from one function to236another, a global variable is not good enough because it would break in237threaded environments.  Flask provides you with a special object that238ensures it is only valid for the active request and that will return239different values for each request.  In a nutshell: it does the right240thing, like it does for :class:`request` and :class:`session`.241242.. data:: g243244   Just store on this whatever you want.  For example a database245   connection or the user that is currently logged in.246247   This is a proxy.  See :ref:`notes-on-proxies` for more information.248249250Useful Functions and Classes251----------------------------252253.. data:: current_app254255   Points to the application handling the request.  This is useful for256   extensions that want to support multiple applications running side257   by side.258259   This is a proxy.  See :ref:`notes-on-proxies` for more information.260261.. autofunction:: has_request_context262263.. autofunction:: url_for264265.. function:: abort(code)266267   Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given268   status code.  For example to abort request handling with a page not269   found exception, you would call ``abort(404)``.270271   :param code: the HTTP error code.272273.. autofunction:: redirect274275.. autofunction:: make_response276277.. autofunction:: send_file278279.. autofunction:: send_from_directory280281.. autofunction:: safe_join282283.. autofunction:: escape284285.. autoclass:: Markup286   :members: escape, unescape, striptags287288Message Flashing289----------------290291.. autofunction:: flash292293.. autofunction:: get_flashed_messages294295Returning JSON296--------------297298.. autofunction:: jsonify299300.. data:: json301302    If JSON support is picked up, this will be the module that Flask is303    using to parse and serialize JSON.  So instead of doing this yourself::304305        try:306            import simplejson as json307        except ImportError:308            import json309310    You can instead just do this::311312        from flask import json313314    For usage examples, read the :mod:`json` documentation.315316    The :func:`~json.dumps` function of this json module is also available317    as filter called ``|tojson`` in Jinja2.  Note that inside `script`318    tags no escaping must take place, so make sure to disable escaping319    with ``|safe`` if you intend to use it inside `script` tags:320321    .. sourcecode:: html+jinja322323        <script type=text/javascript>324            doSomethingWith({{ user.username|tojson|safe }});325        </script>326327    Note that the ``|tojson`` filter escapes forward slashes properly.328329Template Rendering330------------------331332.. autofunction:: render_template333334.. autofunction:: render_template_string335336.. autofunction:: get_template_attribute337338Configuration339-------------340341.. autoclass:: Config342   :members:343344Useful Internals345----------------346347.. autoclass:: flask.ctx.RequestContext348   :members:349350.. data:: _request_ctx_stack351352   The internal :class:`~werkzeug.local.LocalStack` that is used to implement353   all the context local objects used in Flask.  This is a documented354   instance and can be used by extensions and application code but the355   use is discouraged in general.356357   The following attributes are always present on each layer of the358   stack:359360   `app`361      the active Flask application.362363   `url_adapter`364      the URL adapter that was used to match the request.365366   `request`367      the current request object.368369   `session`370      the active session object.371372   `g`373      an object with all the attributes of the :data:`flask.g` object.374375   `flashes`376      an internal cache for the flashed messages.377378   Example usage::379380      from flask import _request_ctx_stack381382      def get_session():383          ctx = _request_ctx_stack.top384          if ctx is not None:385              return ctx.session386387.. autoclass:: flask.blueprints.BlueprintSetupState388   :members:389390Signals391-------392393.. when modifying this list, also update the one in signals.rst394395.. versionadded:: 0.6396397.. data:: signals_available398399   `True` if the signalling system is available.  This is the case400   when `blinker`_ is installed.401402.. data:: template_rendered403404   This signal is sent when a template was successfully rendered.  The405   signal is invoked with the instance of the template as `template`406   and the context as dictionary (named `context`).407408.. data:: request_started409410   This signal is sent before any request processing started but when the411   request context was set up.  Because the request context is already412   bound, the subscriber can access the request with the standard global413   proxies such as :class:`~flask.request`.414415.. data:: request_finished416417   This signal is sent right before the response is sent to the client.418   It is passed the response to be sent named `response`.419420.. data:: got_request_exception421422   This signal is sent when an exception happens during request processing.423   It is sent *before* the standard exception handling kicks in and even424   in debug mode, where no exception handling happens.  The exception425   itself is passed to the subscriber as `exception`.426427.. data:: request_tearing_down428429   This signal is sent when the application is tearing down the request.430   This is always called, even if an error happened.  No arguments are431   provided.432433.. currentmodule:: None434435.. class:: flask.signals.Namespace436437   An alias for :class:`blinker.base.Namespace` if blinker is available,438   otherwise a dummy class that creates fake signals.  This class is439   available for Flask extensions that want to provide the same fallback440   system as Flask itself.441442   .. method:: signal(name, doc=None)443444      Creates a new signal for this namespace if blinker is available,445      otherwise returns a fake signal that has a send method that will446      do nothing but will fail with a :exc:`RuntimeError` for all other447      operations, including connecting.448449.. _blinker: http://pypi.python.org/pypi/blinker450451Class Based Views452-----------------453454.. versionadded:: 0.7455456.. currentmodule:: None457458.. autoclass:: flask.views.View459   :members:460461.. autoclass:: flask.views.MethodView462   :members:463464.. _view-func-options:465466View Function Options467---------------------468469For internal usage the view functions can have some attributes attached to470customize behavior the view function would normally not have control over.471The following attributes can be provided optionally to either override472some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:473474-   `__name__`: The name of a function is by default used as endpoint.  If475    endpoint is provided explicitly this value is used.  Additionally this476    will be prefixed with the name of the blueprint by default which477    cannot be customized from the function itself.478479-   `methods`: If methods are not provided when the URL rule is added,480    Flask will look on the view function object itself is an `methods`481    attribute exists.  If it does, it will pull the information for the482    methods from there.483484-   `provide_automatic_options`: if this attribute is set Flask will485    either force enable or disable the automatic implementation of the486    HTTP `OPTIONS` response.  This can be useful when working with487    decorators that want to customize the `OPTIONS` response on a per-view488    basis.489490Full example::491492    def index():493        if request.method == 'OPTIONS':494            # custom options handling here495            ...496        return 'Hello World!'497    index.provide_automatic_options = False498    index.methods = ['GET', 'OPTIONS']499500    app.add_url_rule('/', index)501502.. versionadded:: 0.8503   The `provide_automatic_options` functionality was added.