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

The walk stopped after 200 commits: lines older than d09aa37 point at it.

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 1–20why, one step back
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:1920

More docstrings for blueprints.Armin Ronacherbefore adoption8617505

lines 21–22why, one step back
21Blueprint Objects
22-----------------

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

line 23why, one step back
23

More docstrings for blueprints.Armin Ronacherbefore adoption8617505

line 24why, one step back
24.. autoclass:: Blueprint

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 25–42why, one step back
25 :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.42

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

line 43why, one step back
43 The request object is an instance of a :class:`~werkzeug.wrappers.Request`

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 44–48why, one step back
44 subclass and provides all of the attributes Werkzeug defines. This
45 just shows a quick overview of the most important ones.4647 .. attribute:: form48

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

line 49why, one step back
49 A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from `POST`

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 50–54why, one step back
50 or `PUT` requests. Please keep in mind that file uploads will not
51 end up here, but instead in the :attr:`files` attribute.5253 .. attribute:: args54

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

line 55why, one step back
55 A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 56–59why, one step back
56 string. (The part in the URL after the question mark).
5758 .. attribute:: values59

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

line 60why, one step back
60 A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 61–81why, one step back
61 :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:: files81

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

line 82why, one step back
82 A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

line 83why, one step back
83 `POST` or `PUT` request. Each file is stored as

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

line 84why, one step back
84 :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

line 85why, one step back
85 standard file object you know from Python, with the difference that

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

line 86why, one step back
86 it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 87–158why, one step back
87 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, but

Less annoying gender neutral formsArmin Ronacherbefore adoption22d468e

line 159why, one step back
159not modify it unless they know the secret key, so make sure to set that

Merge branch 'master' into blueprintsArmin Ronacherbefore adoption4e47ea9

line 160why, one step back
160to something complex and unguessable.

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 161–189why, one step back
161
162To 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 = True189

Fixed: incorrect indentation level for session's permanent attributeDaniel D. Beckbefore adoption4f1b086

line 190why, one step back
190 .. attribute:: permanent

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

line 191why, one step back
191

Typo in docsDag Odenhallbefore adoption384ad21

line 192why, one step back
192 If set to `True` the session lives for

Fixed: incorrect indentation level for session's permanent attributeDaniel D. Beckbefore adoption4f1b086

lines 193–195why, one step back
193 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The
194 default is 31 days. If set to `False` (which is the default) the195 session will be deleted when the user closes the browser.

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 196–197why, one step back
196
197

Refactored session interfaceArmin Ronacherbefore adoption0fccfe7

lines 198–200why, one step back
198Session Interface
199-----------------200

The session interface is new in 0.8, not 0.7Armin Ronacherbefore adoptiondeb513c

line 201why, one step back
201.. versionadded:: 0.8

Refactored session interfaceArmin Ronacherbefore adoption0fccfe7

lines 202–220why, one step back
202
203The 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:219220

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 221–222why, one step back
221Application Globals
222-------------------

Refactored session interfaceArmin Ronacherbefore adoption0fccfe7

lines 223–224why, one step back
223
224.. currentmodule:: flask

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 225–251why, one step back
225
226To 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.251

Implemented flask.has_request_context()Armin Ronacherbefore adoptionfbd4886

lines 252–253why, one step back
252.. autofunction:: has_request_context
253

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 254–257why, one step back
254.. autofunction:: url_for
255256.. function:: abort(code)257

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

line 258why, one step back
258 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 259–271why, one step back
259 status code. For example to abort request handling with a page not
260 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_directory271

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

lines 272–273why, one step back
272.. autofunction:: safe_join
273

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 274–337why, one step back
274.. autofunction:: escape
275276.. 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----------------337

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

lines 338–340why, one step back
338.. autoclass:: flask.ctx.RequestContext
339 :members:340

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 341–342why, one step back
341.. data:: _request_ctx_stack
342

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

line 343why, one step back
343 The internal :class:`~werkzeug.local.LocalStack` that is used to implement

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 344–376why, one step back
344 all the context local objects used in Flask. This is a documented
345 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.session

More docstrings for blueprints.Armin Ronacherbefore adoption8617505

lines 377–379why, one step back
377
378.. autoclass:: flask.blueprints.BlueprintSetupState379 :members:

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 380–417why, one step back
380
381Signals382-------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`.417

Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18

lines 418–423why, one step back
418.. data:: request_tearing_down
419420 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.423

Approved Flask-XML-RPCArmin Ronacherbefore adoptiond09aa37

lines 424–440why, one step back
424.. currentmodule:: None
425426.. 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/blinker

Added class based view documentationArmin Ronacherbefore adoptionb36d7b3

lines 441–453why, one step back
441
442Class Based Views443-----------------444445.. versionadded:: 0.7446447.. currentmodule:: None448449.. autoclass:: flask.views.View450 :members:451452.. autoclass:: flask.views.MethodView453 :members:

Documented view function optionsArmin Ronacherbefore adoption76796c3

lines 454–491why, one step back
454
455.. _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)

Added a versionaddedArmin Ronacherbefore adoption6ca321c

lines 492–494why, one step back
492
493.. versionadded:: 0.8494 The `provide_automatic_options` functionality was added.