api.rst
This file
Path
docs/api.rst
453 lines · 12.5 KiB
Last changed by
The session interface is new in 0.8, not 0.7Armin Ronacherbefore adoptiondeb513c
History of this fileTake it
The walk stopped after 200 commits: lines older than 3e297e8 point at it.
Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 1–20why, one step back1.. _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:1920More docstrings for blueprints.Armin Ronacherbefore adoption8617505
lines 21–22why, one step back21Blueprint Objects22-----------------Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
line 23why, one step back23More docstrings for blueprints.Armin Ronacherbefore adoption8617505
line 24why, one step back24.. autoclass:: BlueprintApproved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 25–42why, one step back25 :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.42fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa
line 43why, one step back43 The request object is an instance of a :class:`~werkzeug.wrappers.Request`Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 44–48why, one step back44 subclass and provides all of the attributes Werkzeug defines. This45 just shows a quick overview of the most important ones.4647 .. attribute:: form48fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa
line 49why, one step back49 A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from `POST`Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 50–54why, one step back50 or `PUT` requests. Please keep in mind that file uploads will not51 end up here, but instead in the :attr:`files` attribute.5253 .. attribute:: args54fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa
line 55why, one step back55 A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the queryApproved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 56–59why, one step back56 string. (The part in the URL after the question mark).5758 .. attribute:: values59fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa
line 60why, one step back60 A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of bothApproved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 61–81why, one step back61 :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:: files81fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa
line 82why, one step back82 A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of aApproved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
line 83why, one step back83 `POST` or `PUT` request. Each file is stored asfixing cross-reference links on API doc pagematt swansonbefore adoption4141afa
line 84why, one step back84 :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like aApproved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
line 85why, one step back85 standard file object you know from Python, with the difference thatfixing cross-reference links on API doc pagematt swansonbefore adoption4141afa
line 86why, one step back86 it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that canApproved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 87–158why, one step back87 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, butLess annoying gender neutral formsArmin Ronacherbefore adoption22d468e
line 159why, one step back159not modify it unless they know the secret key, so make sure to set thatMerge branch 'master' into blueprintsArmin Ronacherbefore adoption4e47ea9
line 160why, one step back160to something complex and unguessable.Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 161–189why, one step back161162To 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 = True189Fixed: incorrect indentation level for session's permanent attributeDaniel D. Beckbefore adoption4f1b086
line 190why, one step back190 .. attribute:: permanentApproved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
line 191why, one step back191Typo in docsDag Odenhallbefore adoption384ad21
line 192why, one step back192 If set to `True` the session lives forFixed: incorrect indentation level for session's permanent attributeDaniel D. Beckbefore adoption4f1b086
lines 193–195why, one step back193 :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.Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 196–197why, one step back196197Refactored session interfaceArmin Ronacherbefore adoption0fccfe7
lines 198–200why, one step back198Session Interface199-----------------200The session interface is new in 0.8, not 0.7Armin Ronacherbefore adoptiondeb513c
line 201why, one step back201.. versionadded:: 0.8Refactored session interfaceArmin Ronacherbefore adoption0fccfe7
lines 202–220why, one step back202203The 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:219220Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 221–222why, one step back221Application Globals222-------------------Refactored session interfaceArmin Ronacherbefore adoption0fccfe7
lines 223–224why, one step back223224.. currentmodule:: flaskApproved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 225–251why, one step back225226To 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.251Implemented flask.has_request_context()Armin Ronacherbefore adoptionfbd4886
lines 252–253why, one step back252.. autofunction:: has_request_context253Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 254–257why, one step back254.. autofunction:: url_for255256.. function:: abort(code)257fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa
line 258why, one step back258 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the givenApproved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 259–271why, one step back259 status code. For example to abort request handling with a page not260 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_directory271Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18
lines 272–273why, one step back272.. autofunction:: safe_join273Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 274–337why, one step back274.. autofunction:: escape275276.. 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----------------337Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18
lines 338–340why, one step back338.. autoclass:: flask.ctx.RequestContext339 :members:340Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 341–342why, one step back341.. data:: _request_ctx_stack342fixing cross-reference links on API doc pagematt swansonbefore adoption4141afa
line 343why, one step back343 The internal :class:`~werkzeug.local.LocalStack` that is used to implementApproved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 344–376why, one step back344 all the context local objects used in Flask. This is a documented345 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.sessionMore docstrings for blueprints.Armin Ronacherbefore adoption8617505
lines 377–379why, one step back377378.. autoclass:: flask.blueprints.BlueprintSetupState379 :members:Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 380–417why, one step back380381Signals382-------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`.417Merge branch 'new-request-dispatching' into blueprintsArmin Ronacherbefore adoption673fa18
lines 418–423why, one step back418.. data:: request_tearing_down419420 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.423Approved Flask-Themes and Flask-UploadsArmin Ronacherbefore adoption3e297e8
lines 424–440why, one step back424.. currentmodule:: None425426.. 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/blinkerAdded class based view documentationArmin Ronacherbefore adoptionb36d7b3
lines 441–453why, one step back441442Class Based Views443-----------------444445.. versionadded:: 0.7446447.. currentmodule:: None448449.. autoclass:: flask.views.View450 :members:451452.. autoclass:: flask.views.MethodView453 :members: