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

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

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

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-----------------

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

line 23why, one step back
23

More docstrings for blueprints.Armin Ronacherbefore adoption8617505

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

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 25–31why, one step back
25 :members:
26 :inherited-members:2728Incoming Request Data29---------------------3031.. autoclass:: Request

Fixed the docs for the request object. They were incompleteArmin Ronacherbefore adoption153d727

line 32why, one step back
32 :members:

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 33–35why, one step back
33
34 .. attribute:: form35

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

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

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 37–41why, one step back
37 or `PUT` requests. Please keep in mind that file uploads will not
38 end up here, but instead in the :attr:`files` attribute.3940 .. attribute:: args41

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

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

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 43–46why, one step back
43 string. (The part in the URL after the question mark).
4445 .. attribute:: values46

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

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

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

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

Documented Request.headersArmin Ronacherbefore adoption92c7bdd

lines 62–65why, one step back
62 .. attribute:: headers
6364 The incoming request headers as a dictionary like object.65

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 66–72why, one step back
66 .. attribute:: data
6768 Contains the incoming request data as string in case it came with69 a mimetype Flask does not handle.7071 .. attribute:: files72

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

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

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

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

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

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

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

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

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

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

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 78–121why, one step back
78 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.121

Fixed the docs for the request object. They were incompleteArmin Ronacherbefore adoption153d727

lines 122–135why, one step back
122.. class:: request
123124 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.135

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 136–158why, one step back
136
137Response 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.

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 161–197why, 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 = 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.196197

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

Implemented flask.testing.TestClient.session_transaction for quick session modifications in test environments.Armin Ronacherbefore adoptiona5da2c9

lines 221–225why, one step back
221Test Client
222-----------223224.. currentmodule:: flask.testing225

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

line 226why, one step back
226.. autoclass:: FlaskClient

Implemented flask.testing.TestClient.session_transaction for quick session modifications in test environments.Armin Ronacherbefore adoptiona5da2c9

lines 227–229why, one step back
227 :members:
228229

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 230–231why, one step back
230Application Globals
231-------------------

Refactored session interfaceArmin Ronacherbefore adoption0fccfe7

lines 232–233why, one step back
232
233.. currentmodule:: flask

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 234–260why, one step back
234
235To 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.260

Implemented flask.has_request_context()Armin Ronacherbefore adoptionfbd4886

lines 261–262why, one step back
261.. autofunction:: has_request_context
262

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 263–266why, one step back
263.. autofunction:: url_for
264265.. function:: abort(code)266

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

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

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 268–280why, one step back
268 status code. For example to abort request handling with a page not
269 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_directory280

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

lines 281–282why, one step back
281.. autofunction:: safe_join
282

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 283–346why, one step back
283.. autofunction:: escape
284285.. 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----------------346

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

lines 347–349why, one step back
347.. autoclass:: flask.ctx.RequestContext
348 :members:349

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 350–351why, one step back
350.. data:: _request_ctx_stack
351

fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa

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

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

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

More docstrings for blueprints.Armin Ronacherbefore adoption8617505

lines 386–388why, one step back
386
387.. autoclass:: flask.blueprints.BlueprintSetupState388 :members:

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 389–426why, one step back
389
390Signals391-------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`.426

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

lines 427–432why, one step back
427.. data:: request_tearing_down
428429 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.432

Fixing a word usage issue in docs.Sean Reifschneiderbefore adoption1643e5c

lines 433–449why, one step back
433.. currentmodule:: None
434435.. 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/blinker

Added class based view documentationArmin Ronacherbefore adoptionb36d7b3

lines 450–462why, one step back
450
451Class Based Views452-----------------453454.. versionadded:: 0.7455456.. currentmodule:: None457458.. autoclass:: flask.views.View459 :members:460461.. autoclass:: flask.views.MethodView462 :members:

Documented view function optionsArmin Ronacherbefore adoption76796c3

lines 463–500why, one step back
463
464.. _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)

Added a versionaddedArmin Ronacherbefore adoption6ca321c

lines 501–503why, one step back
501
502.. versionadded:: 0.8503 The `provide_automatic_options` functionality was added.