Skip to content
Myr

api.rst

This file

Path

docs/api.rst

443 lines · 13.4 KiB

Last changed by

Implemented flask.has_request_context()Armin Ronacherbefore adoptionfbd4886

History of this file

Take it

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

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

lines 1–40why, 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: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.40

Added notes on proxiesArmin Ronacherbefore adoption3b0eb0f

lines 41–42why, one step back
41 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`

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

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`

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

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

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

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

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

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

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

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

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

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

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

lines 87–168why, 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, 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.168

Added notes on proxiesArmin Ronacherbefore adoption3b0eb0f

lines 169–170why, one step back
169 This is a proxy. See :ref:`notes-on-proxies` for more information.
170

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

lines 171–189why, one step back
171 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

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

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.

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

lines 196–212why, one step back
196
197198Application 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.212

Added notes on proxiesArmin Ronacherbefore adoption3b0eb0f

line 213why, one step back
213 This is a proxy. See :ref:`notes-on-proxies` for more information.

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

line 214why, one step back
214

Added notes on proxiesArmin Ronacherbefore adoption3b0eb0f

line 215why, one step back
215

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

lines 216–224why, one step back
216Useful Functions and Classes
217----------------------------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.224

Added notes on proxiesArmin Ronacherbefore adoption3b0eb0f

lines 225–226why, one step back
225 This is a proxy. See :ref:`notes-on-proxies` for more information.
226

Implemented flask.has_request_context()Armin Ronacherbefore adoptionfbd4886

lines 227–228why, one step back
227.. autofunction:: has_request_context
228

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

lines 229–232why, one step back
229.. autofunction:: url_for
230231.. function:: abort(code)232

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

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

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

lines 234–240why, one step back
234 status code. For example to abort request handling with a page not
235 found exception, you would call ``abort(404)``.236237 :param code: the HTTP error code.238239.. autofunction:: redirect240

Added make_responseArmin Ronacherbefore adoption6fc1492

lines 241–242why, one step back
241.. autofunction:: make_response
242

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

lines 243–244why, one step back
243.. autofunction:: send_file
244

Documented send_from_directoryArmin Ronacherbefore adoptionc34b03e

lines 245–246why, one step back
245.. autofunction:: send_from_directory
246

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

lines 247–312why, one step back
247.. autofunction:: escape
248249.. autoclass:: Markup250 :members: escape, unescape, striptags251252Message Flashing253----------------254255.. autofunction:: flash256257.. autofunction:: get_flashed_messages258259Returning JSON260--------------261262.. autofunction:: jsonify263264.. data:: json265266 If JSON support is picked up, this will be the module that Flask is267 using to parse and serialize JSON. So instead of doing this yourself::268269 try:270 import simplejson as json271 except ImportError:272 import json273274 You can instead just do this::275276 from flask import json277278 For usage examples, read the :mod:`json` documentation.279280 The :func:`~json.dumps` function of this json module is also available281 as filter called ``|tojson`` in Jinja2. Note that inside `script`282 tags no escaping must take place, so make sure to disable escaping283 with ``|safe`` if you intend to use it inside `script` tags:284285 .. sourcecode:: html+jinja286287 <script type=text/javascript>288 doSomethingWith({{ user.username|tojson|safe }});289 </script>290291 Note that the ``|tojson`` filter escapes forward slashes properly.292293Template Rendering294------------------295296.. autofunction:: render_template297298.. autofunction:: render_template_string299300.. autofunction:: get_template_attribute301302Configuration303-------------304305.. autoclass:: Config306 :members:307308Useful Internals309----------------310311.. data:: _request_ctx_stack312

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

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

Moved templating stuff into a separate moduleArmin Ronacherbefore adoptiona3c9494

lines 314–363why, one step back
314 all the context local objects used in Flask. This is a documented
315 instance and can be used by extensions and application code but the316 use is discouraged in general.317318 The following attributes are always present on each layer of the319 stack:320321 `app`322 the active Flask application.323324 `url_adapter`325 the URL adapter that was used to match the request.326327 `request`328 the current request object.329330 `session`331 the active session object.332333 `g`334 an object with all the attributes of the :data:`flask.g` object.335336 `flashes`337 an internal cache for the flashed messages.338339 Example usage::340341 from flask import _request_ctx_stack342343 def get_session():344 ctx = _request_ctx_stack.top345 if ctx is not None:346 return ctx.session347348 .. versionchanged:: 0.4349350 The request context is automatically popped at the end of the request351 for you. In debug mode the request context is kept around if352 exceptions happen so that interactive debuggers have a chance to353 introspect the data. With 0.4 this can also be forced for requests354 that did not fail and outside of `DEBUG` mode. By setting355 ``'flask._preserve_context'`` to `True` on the WSGI environment the356 context will not pop itself at the end of the request. This is used by357 the :meth:`~flask.Flask.test_client` for example to implement the358 deferred cleanup functionality.359360 You might find this helpful for unittests where you need the361 information from the context local around for a little longer. Make362 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in363 that situation, otherwise your unittests will leak memory.

Added support for signalsArmin Ronacherbefore adoptione0712b4

lines 364–367why, one step back
364
365Signals366-------367

Added signal documentationArmin Ronacherbefore adoptionc360f00

lines 368–369why, one step back
368.. when modifying this list, also update the one in signals.rst
369

Added support for signalsArmin Ronacherbefore adoptione0712b4

lines 370–401why, one step back
370.. versionadded:: 0.6
371372.. data:: signals_available373374 `True` if the signalling system is available. This is the case375 when `blinker`_ is installed.376377.. data:: template_rendered378379 This signal is sent when a template was successfully rendered. The380 signal is invoked with the instance of the template as `template`381 and the context as dictionary (named `context`).382383.. data:: request_started384385 This signal is sent before any request processing started but when the386 request context was set up. Because the request context is already387 bound, the subscriber can access the request with the standard global388 proxies such as :class:`~flask.request`.389390.. data:: request_finished391392 This signal is sent right before the response is sent to the client.393 It is passed the response to be sent named `response`.394395.. data:: got_request_exception396397 This signal is sent when an exception happens during request processing.398 It is sent *before* the standard exception handling kicks in and even399 in debug mode, where no exception handling happens. The exception400 itself is passed to the subscriber as `exception`.401

Added notes on proxiesArmin Ronacherbefore adoption3b0eb0f

lines 402–403why, one step back
402.. currentmodule:: None
403

Added support for signalsArmin Ronacherbefore adoptione0712b4

lines 404–418why, one step back
404.. class:: flask.signals.Namespace
405406 An alias for :class:`blinker.base.Namespace` if blinker is available,407 otherwise a dummy class that creates fake signals. This class is408 available for Flask extensions that want to provide the same fallback409 system as Flask itself.410411 .. method:: signal(name, doc=None)412413 Creates a new signal for this namespace if blinker is available,414 otherwise returns a fake signal that has a send method that will415 do nothing but will fail with a :exc:`RuntimeError` for all other416 operations, including connecting.417418.. _blinker: http://pypi.python.org/pypi/blinker

Added notes on proxiesArmin Ronacherbefore adoption3b0eb0f

lines 419–425why, one step back
419
420.. _notes-on-proxies:421422Notes On Proxies423----------------424425Some of the objects provided by Flask are proxies to other objects. The

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption5ecf01d

line 426why, one step back
426reason behind this is that these proxies are shared between threads and

Added notes on proxiesArmin Ronacherbefore adoption3b0eb0f

lines 427–434why, one step back
427they have to dispatch to the actual object bound to a thread behind the
428scenes as necessary.429430Most of the time you don't have to care about that, but there are some431exceptions where it is good to know that this object is an actual proxy:432433- The proxy objects do not fake their inherited types, so if you want to434 perform actual instance checks, you have to do that on the instance

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption5ecf01d

line 435why, one step back
435 that is being proxied (see `_get_current_object` below).

Added notes on proxiesArmin Ronacherbefore adoption3b0eb0f

lines 436–439why, one step back
436- if the object reference is important (so for example for sending
437 :ref:`signals`)438439If you need to get access to the underlying object that is proxied, you

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

line 440why, one step back
440can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::

Added notes on proxiesArmin Ronacherbefore adoption3b0eb0f

lines 441–443why, one step back
441
442 app = current_app._get_current_object()443 my_signal.send(app)