Skip to content
Myr

api.rst

This file

Path

docs/api.rst

262 lines · 7.7 KiB

Last changed by

Fix typos and remove unused import.florentxbefore adoption3c821a0

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:1819Incoming Request Data20---------------------2122.. autoclass:: Request2324.. class:: request2526   To access incoming request data, you can use the global `request`27   object.  Flask parses incoming request data for you and gives you28   access to it through that global object.  Internally Flask makes29   sure that you always get the correct data for the active thread if you30   are in a multithreaded environment.3132   The request object is an instance of a :class:`~werkzeug.Request`33   subclass and provides all of the attributes Werkzeug defines.  This34   just shows a quick overview of the most important ones.3536   .. attribute:: form3738      A :class:`~werkzeug.MultiDict` with the parsed form data from `POST`39      or `PUT` requests.  Please keep in mind that file uploads will not40      end up here,  but instead in the :attr:`files` attribute.4142   .. attribute:: args4344      A :class:`~werkzeug.MultiDict` with the parsed contents of the query45      string.  (The part in the URL after the question mark).4647   .. attribute:: values4849      A :class:`~werkzeug.CombinedMultiDict` with the contents of both50      :attr:`form` and :attr:`args`.5152   .. attribute:: cookies5354      A :class:`dict` with the contents of all cookies transmitted with55      the request.5657   .. attribute:: stream5859      If the incoming form data was not encoded with a known mimetype60      the data is stored unmodified in this stream for consumption.  Most61      of the time it is a better idea to use :attr:`data` which will give62      you that data as a string.  The stream only returns the data once.63      64   .. attribute:: data6566      Contains the incoming request data as string in case it came with67      a mimetype Flask does not handle.6869   .. attribute:: files7071      A :class:`~werkzeug.MultiDict` with files uploaded as part of a72      `POST` or `PUT` request.  Each file is stored as73      :class:`~werkzeug.FileStorage` object.  It basically behaves like a74      standard file object you know from Python, with the difference that75      it also has a :meth:`~werkzeug.FileStorage.save` function that can76      store the file on the filesystem.7778   .. attribute:: environ7980      The underlying WSGI environment.8182   .. attribute:: method8384      The current request method (``POST``, ``GET`` etc.)8586   .. attribute:: path87   .. attribute:: script_root88   .. attribute:: url89   .. attribute:: base_url90   .. attribute:: url_root9192      Provides different ways to look at the current URL.  Imagine your93      application is listening on the following URL::9495          http://www.example.com/myapplication9697      And a user requests the following URL::9899          http://www.example.com/myapplication/page.html?x=y100101      In this case the values of the above mentioned attributes would be102      the following:103104      ============= ======================================================105      `path`        ``/page.html``106      `script_root` ``/myapplication``107      `url`         ``http://www.example.com/myapplication/page.html``108      `base_url`    ``http://www.example.com/myapplication/page.html?x=y``109      `url_root`    ``http://www.example.com/myapplication/``110      ============= ======================================================111112   .. attribute:: is_xhr113114      `True` if the request was triggered via a JavaScript115      `XMLHttpRequest`. This only works with libraries that support the116      ``X-Requested-With`` header and set it to `XMLHttpRequest`.117      Libraries that do that are prototype, jQuery and Mochikit and118      probably some more.119120   .. attribute:: json121122      Contains the parsed body of the JSON request if the mimetype of123      the incoming data was `application/json`.  This requires Python 2.6124      or an installed version of simplejson.125126Response Objects127----------------128129.. autoclass:: flask.Response130   :members: set_cookie, data, mimetype131132   .. attribute:: headers133134      A :class:`Headers` object representing the response headers.135136   .. attribute:: status_code137138      The response status as integer.139140141Sessions142--------143144If you have the :attr:`Flask.secret_key` set you can use sessions in Flask145applications.  A session basically makes it possible to remember146information from one request to another.  The way Flask does this is by147using a signed cookie.  So the user can look at the session contents, but148not modify it unless he knows the secret key, so make sure to set that to149something complex and unguessable.150151To access the current session you can use the :class:`session` object:152153.. class:: session154155   The session object works pretty much like an ordinary dict, with the156   difference that it keeps track on modifications.157158   The following attributes are interesting:159160   .. attribute:: new161162      `True` if the session is new, `False` otherwise.163164   .. attribute:: modified165166      `True` if the session object detected a modification.  Be advised167      that modifications on mutable structures are not picked up168      automatically, in that situation you have to explicitly set the169      attribute to `True` yourself.  Here an example::170171          # this change is not picked up because a mutable object (here172          # a list) is changed.173          session['objects'].append(42)174          # so mark it as modified yourself175          session.modified = True176177178Application Globals179-------------------180181To share data that is valid for one request only from one function to182another, a global variable is not good enough because it would break in183threaded environments.  Flask provides you with a special object that184ensures it is only valid for the active request and that will return185different values for each request.  In a nutshell: it does the right186thing, like it does for :class:`request` and :class:`session`.187188.. data:: g189190   Just store on this whatever you want.  For example a database191   connection or the user that is currently logged in.192193194Useful Functions and Classes195----------------------------196197.. autofunction:: url_for198199.. function:: abort(code)200201   Raises an :exc:`~werkzeug.exception.HTTPException` for the given202   status code.  For example to abort request handling with a page not203   found exception, you would call ``abort(404)``.204205   :param code: the HTTP error code.206207.. autofunction:: redirect208209.. autofunction:: escape210211.. autoclass:: Markup212   :members: escape, unescape, striptags213214Message Flashing215----------------216217.. autofunction:: flash218219.. autofunction:: get_flashed_messages220221Returning JSON222--------------223224.. autofunction:: jsonify225226.. data:: json227228    If JSON support is picked up, this will be the module that Flask is229    using to parse and serialize JSON.  So instead of doing this yourself::230231        try:232            import simplejson as json233        except ImportError:234            import json235236    You can instead just do this::237238        from flask import json239240    For usage examples, read the :mod:`json` documentation.241242    The :func:`~json.dumps` function of this json module is also available243    as filter called ``|tojson`` in Jinja2.  Note that inside `script`244    tags no escaping must take place, so make sure to disable escaping245    with ``|safe`` if you intend to use it inside `script` tags:246247    .. sourcecode:: html+jinja248249        <script type=text/javascript>250            doSomethingWith({{ user.username|tojson|safe }});251        </script>252253    Note that the ``|tojson`` filter escapes forward slashes properly.254255Template Rendering256------------------257258.. autofunction:: render_template259260.. autofunction:: render_template_string261262.. autofunction:: get_template_attribute