Skip to content
Myr

api.rst

This file

Path

docs/api.rst

406 lines · 12.0 KiB

Last changed by

Added signal documentationArmin Ronacherbefore adoptionc360f00

History of this file

Take it

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

Beefed up latex output. Unfortunately parts look ugly.Armin Ronacherbefore adoptioncbcd15c

lines 1–71why, 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.4041 The request object is an instance of a :class:`~werkzeug.Request`42 subclass and provides all of the attributes Werkzeug defines. This43 just shows a quick overview of the most important ones.4445 .. attribute:: form4647 A :class:`~werkzeug.MultiDict` with the parsed form data from `POST`48 or `PUT` requests. Please keep in mind that file uploads will not49 end up here, but instead in the :attr:`files` attribute.5051 .. attribute:: args5253 A :class:`~werkzeug.MultiDict` with the parsed contents of the query54 string. (The part in the URL after the question mark).5556 .. attribute:: values5758 A :class:`~werkzeug.CombinedMultiDict` with the contents of both59 :attr:`form` and :attr:`args`.6061 .. attribute:: cookies6263 A :class:`dict` with the contents of all cookies transmitted with64 the request.6566 .. attribute:: stream6768 If the incoming form data was not encoded with a known mimetype69 the data is stored unmodified in this stream for consumption. Most70 of the time it is a better idea to use :attr:`data` which will give71 you that data as a string. The stream only returns the data once.

More typo fixes.Georg Brandlbefore adoptiona224fec

line 72why, one step back
72

Beefed up latex output. Unfortunately parts look ugly.Armin Ronacherbefore adoptioncbcd15c

lines 73–230why, one step back
73 .. attribute:: data
7475 Contains the incoming request data as string in case it came with76 a mimetype Flask does not handle.7778 .. attribute:: files7980 A :class:`~werkzeug.MultiDict` with files uploaded as part of a81 `POST` or `PUT` request. Each file is stored as82 :class:`~werkzeug.FileStorage` object. It basically behaves like a83 standard file object you know from Python, with the difference that84 it also has a :meth:`~werkzeug.FileStorage.save` function that can85 store the file on the filesystem.8687 .. attribute:: environ8889 The underlying WSGI environment.9091 .. attribute:: method9293 The current request method (``POST``, ``GET`` etc.)9495 .. attribute:: path96 .. attribute:: script_root97 .. attribute:: url98 .. attribute:: base_url99 .. attribute:: url_root100101 Provides different ways to look at the current URL. Imagine your102 application is listening on the following URL::103104 http://www.example.com/myapplication105106 And a user requests the following URL::107108 http://www.example.com/myapplication/page.html?x=y109110 In this case the values of the above mentioned attributes would be111 the following:112113 ============= ======================================================114 `path` ``/page.html``115 `script_root` ``/myapplication``116 `base_url` ``http://www.example.com/myapplication/page.html``117 `url` ``http://www.example.com/myapplication/page.html?x=y``118 `url_root` ``http://www.example.com/myapplication/``119 ============= ======================================================120121 .. attribute:: is_xhr122123 `True` if the request was triggered via a JavaScript124 `XMLHttpRequest`. This only works with libraries that support the125 ``X-Requested-With`` header and set it to `XMLHttpRequest`.126 Libraries that do that are prototype, jQuery and Mochikit and127 probably some more.128129 .. attribute:: json130131 Contains the parsed body of the JSON request if the mimetype of132 the incoming data was `application/json`. This requires Python 2.6133 or an installed version of simplejson.134135Response Objects136----------------137138.. autoclass:: flask.Response139 :members: set_cookie, data, mimetype140141 .. attribute:: headers142143 A :class:`Headers` object representing the response headers.144145 .. attribute:: status_code146147 The response status as integer.148149150Sessions151--------152153If you have the :attr:`Flask.secret_key` set you can use sessions in Flask154applications. A session basically makes it possible to remember155information from one request to another. The way Flask does this is by156using a signed cookie. So the user can look at the session contents, but157not modify it unless he knows the secret key, so make sure to set that to158something complex and unguessable.159160To access the current session you can use the :class:`session` object:161162.. class:: session163164 The session object works pretty much like an ordinary dict, with the165 difference that it keeps track on modifications.166167 The following attributes are interesting:168169 .. attribute:: new170171 `True` if the session is new, `False` otherwise.172173 .. attribute:: modified174175 `True` if the session object detected a modification. Be advised176 that modifications on mutable structures are not picked up177 automatically, in that situation you have to explicitly set the178 attribute to `True` yourself. Here an example::179180 # this change is not picked up because a mutable object (here181 # a list) is changed.182 session['objects'].append(42)183 # so mark it as modified yourself184 session.modified = True185186 .. attribute:: permanent187188 If set to `True` the session life for189 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The190 default is 31 days. If set to `False` (which is the default) the191 session will be deleted when the user closes the browser.192193194Application Globals195-------------------196197To share data that is valid for one request only from one function to198another, a global variable is not good enough because it would break in199threaded environments. Flask provides you with a special object that200ensures it is only valid for the active request and that will return201different values for each request. In a nutshell: it does the right202thing, like it does for :class:`request` and :class:`session`.203204.. data:: g205206 Just store on this whatever you want. For example a database207 connection or the user that is currently logged in.208209210Useful Functions and Classes211----------------------------212213.. data:: current_app214215 Points to the application handling the request. This is useful for216 extensions that want to support multiple applications running side217 by side.218219.. autofunction:: url_for220221.. function:: abort(code)222223 Raises an :exc:`~werkzeug.exception.HTTPException` for the given224 status code. For example to abort request handling with a page not225 found exception, you would call ``abort(404)``.226227 :param code: the HTTP error code.228229.. autofunction:: redirect230

Added make_responseArmin Ronacherbefore adoption6fc1492

lines 231–232why, one step back
231.. autofunction:: make_response
232

Beefed up latex output. Unfortunately parts look ugly.Armin Ronacherbefore adoptioncbcd15c

lines 233–234why, one step back
233.. autofunction:: send_file
234

Documented send_from_directoryArmin Ronacherbefore adoptionc34b03e

lines 235–236why, one step back
235.. autofunction:: send_from_directory
236

Beefed up latex output. Unfortunately parts look ugly.Armin Ronacherbefore adoptioncbcd15c

lines 237–290why, one step back
237.. autofunction:: escape
238239.. autoclass:: Markup240 :members: escape, unescape, striptags241242Message Flashing243----------------244245.. autofunction:: flash246247.. autofunction:: get_flashed_messages248249Returning JSON250--------------251252.. autofunction:: jsonify253254.. data:: json255256 If JSON support is picked up, this will be the module that Flask is257 using to parse and serialize JSON. So instead of doing this yourself::258259 try:260 import simplejson as json261 except ImportError:262 import json263264 You can instead just do this::265266 from flask import json267268 For usage examples, read the :mod:`json` documentation.269270 The :func:`~json.dumps` function of this json module is also available271 as filter called ``|tojson`` in Jinja2. Note that inside `script`272 tags no escaping must take place, so make sure to disable escaping273 with ``|safe`` if you intend to use it inside `script` tags:274275 .. sourcecode:: html+jinja276277 <script type=text/javascript>278 doSomethingWith({{ user.username|tojson|safe }});279 </script>280281 Note that the ``|tojson`` filter escapes forward slashes properly.282283Template Rendering284------------------285286.. autofunction:: render_template287288.. autofunction:: render_template_string289290.. autofunction:: get_template_attribute

Improved configuration support.Armin Ronacherbefore adoption4d16486

lines 291–295why, one step back
291
292Configuration293-------------294295.. autoclass:: Config

Added chapter about configArmin Ronacherbefore adoption182ee31

line 296why, one step back
296 :members:

Documented _request_ctx_stack. This fixes #57Armin Ronacherbefore adoptiona6617f4

lines 297–306why, one step back
297
298Useful Internals299----------------300301.. data:: _request_ctx_stack302303 The internal :class:`~werkzeug.LocalStack` that is used to implement304 all the context local objects used in Flask. This is a documented305 instance and can be used by extensions and application code but the306 use is discouraged in general.

Added support for deferred context cleanup. test_client users can now access the context locals after the actual request if the client is used with a with-block. This fixes #59.Armin Ronacherbefore adoptionbc00fd1

line 307why, one step back
307

improved _request_ctx_stack docsArmin Ronacherbefore adoption9373a71

line 308why, one step back
308 The following attributes are always present on each layer of the

Fixed an rst syntax errorArmin Ronacherbefore adoption881aa3a

line 309why, one step back
309 stack:

improved _request_ctx_stack docsArmin Ronacherbefore adoption9373a71

lines 310–337why, one step back
310
311 `app`312 the active Flask application.313314 `url_adapter`315 the URL adapter that was used to match the request.316317 `request`318 the current request object.319320 `session`321 the active session object.322323 `g`324 an object with all the attributes of the :data:`flask.g` object.325326 `flashes`327 an internal cache for the flashed messages.328329 Example usage::330331 from flask import _request_ctx_stack332333 def get_session():334 ctx = _request_ctx_stack.top335 if ctx is not None:336 return ctx.session337

Added support for deferred context cleanup. test_client users can now access the context locals after the actual request if the client is used with a with-block. This fixes #59.Armin Ronacherbefore adoptionbc00fd1

lines 338–353why, one step back
338 .. versionchanged:: 0.4
339340 The request context is automatically popped at the end of the request341 for you. In debug mode the request context is kept around if342 exceptions happen so that interactive debuggers have a chance to343 introspect the data. With 0.4 this can also be forced for requests344 that did not fail and outside of `DEBUG` mode. By setting345 ``'flask._preserve_context'`` to `True` on the WSGI environment the346 context will not pop itself at the end of the request. This is used by347 the :meth:`~flask.Flask.test_client` for example to implement the348 deferred cleanup functionality.349350 You might find this helpful for unittests where you need the351 information from the context local around for a little longer. Make352 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in353 that situation, otherwise your unittests will leak memory.

Added support for signalsArmin Ronacherbefore adoptione0712b4

lines 354–357why, one step back
354
355Signals356-------357

Added signal documentationArmin Ronacherbefore adoptionc360f00

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

Added support for signalsArmin Ronacherbefore adoptione0712b4

lines 360–406why, one step back
360.. versionadded:: 0.6
361362.. data:: signals_available363364 `True` if the signalling system is available. This is the case365 when `blinker`_ is installed.366367.. data:: template_rendered368369 This signal is sent when a template was successfully rendered. The370 signal is invoked with the instance of the template as `template`371 and the context as dictionary (named `context`).372373.. data:: request_started374375 This signal is sent before any request processing started but when the376 request context was set up. Because the request context is already377 bound, the subscriber can access the request with the standard global378 proxies such as :class:`~flask.request`.379380.. data:: request_finished381382 This signal is sent right before the response is sent to the client.383 It is passed the response to be sent named `response`.384385.. data:: got_request_exception386387 This signal is sent when an exception happens during request processing.388 It is sent *before* the standard exception handling kicks in and even389 in debug mode, where no exception handling happens. The exception390 itself is passed to the subscriber as `exception`.391392.. class:: flask.signals.Namespace393394 An alias for :class:`blinker.base.Namespace` if blinker is available,395 otherwise a dummy class that creates fake signals. This class is396 available for Flask extensions that want to provide the same fallback397 system as Flask itself.398399 .. method:: signal(name, doc=None)400401 Creates a new signal for this namespace if blinker is available,402 otherwise returns a fake signal that has a send method that will403 do nothing but will fail with a :exc:`RuntimeError` for all other404 operations, including connecting.405406.. _blinker: http://pypi.python.org/pypi/blinker