api.rst
This file
Path
docs/api.rst
520 lines · 14.4 KiB
Last changed by
Documented flask.ext.Armin Ronacherbefore adoption1e6c5f0
History of this fileTake it
The walk stopped after 200 commits: lines older than dbb9a2e point at it.
Added note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
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-----------------Added note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
line 23why, one step back23More docstrings for blueprints.Armin Ronacherbefore adoption8617505
line 24why, one step back24.. autoclass:: BlueprintAdded note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
lines 25–31why, one step back25 :members:26 :inherited-members:2728Incoming Request Data29---------------------3031.. autoclass:: RequestFixed the docs for the request object. They were incompleteArmin Ronacherbefore adoption153d727
line 32why, one step back32 :members:Added note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
lines 33–61why, one step back3334 .. attribute:: form3536 A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from `POST`37 or `PUT` requests. Please keep in mind that file uploads will not38 end up here, but instead in the :attr:`files` attribute.3940 .. attribute:: args4142 A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query43 string. (The part in the URL after the question mark).4445 .. attribute:: values4647 A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both48 :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.61Documented Request.headersArmin Ronacherbefore adoption92c7bdd
lines 62–65why, one step back62 .. attribute:: headers6364 The incoming request headers as a dictionary like object.65Added note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
lines 66–121why, one step back66 .. attribute:: data6768 Contains the incoming request data as string in case it came with69 a mimetype Flask does not handle.7071 .. attribute:: files7273 A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a74 `POST` or `PUT` request. Each file is stored as75 :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a76 standard file object you know from Python, with the difference that77 it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can78 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.121Fixed the docs for the request object. They were incompleteArmin Ronacherbefore adoption153d727
lines 122–135why, one step back122.. class:: request123124 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.135Added note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
lines 136–158why, one step back136137Response 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.Added note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
lines 161–197why, 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 = 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.196197Refactored 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:219220Implemented flask.testing.TestClient.session_transaction for quick session modifications in test environments.Armin Ronacherbefore adoptiona5da2c9
lines 221–225why, one step back221Test Client222-----------223224.. currentmodule:: flask.testing225The 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 back226.. autoclass:: FlaskClientImplemented flask.testing.TestClient.session_transaction for quick session modifications in test environments.Armin Ronacherbefore adoptiona5da2c9
lines 227–229why, one step back227 :members:228229Added note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
lines 230–231why, one step back230Application Globals231-------------------Refactored session interfaceArmin Ronacherbefore adoption0fccfe7
lines 232–233why, one step back232233.. currentmodule:: flaskAdded note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
lines 234–343why, one step back234235To 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.260261.. autofunction:: has_request_context262263.. autofunction:: url_for264265.. function:: abort(code)266267 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given268 status code. For example to abort request handling with a page not269 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_directory280281.. autofunction:: safe_join282283.. autofunction:: escape284285.. 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:343Documented flask.ext.Armin Ronacherbefore adoption1e6c5f0
lines 344–360why, one step back344Extensions345----------346347.. data:: flask.ext348349 This module acts as redirect import module to Flask extensions. It was350 added in 0.8 as the canonical way to import Flask extensions and makes351 it possible for us to have more flexibility in how we distribute352 extensions.353354 If you want to use an extension named “Flask-Foo” you would import it355 from :data:`~flask.ext` as follows::356357 from flask.ext import foo358359 .. versionadded:: 0.8360Added note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
lines 361–402why, one step back361Useful Internals362----------------363364.. autoclass:: flask.ctx.RequestContext365 :members:366367.. data:: _request_ctx_stack368369 The internal :class:`~werkzeug.local.LocalStack` that is used to implement370 all the context local objects used in Flask. This is a documented371 instance and can be used by extensions and application code but the372 use is discouraged in general.373374 The following attributes are always present on each layer of the375 stack:376377 `app`378 the active Flask application.379380 `url_adapter`381 the URL adapter that was used to match the request.382383 `request`384 the current request object.385386 `session`387 the active session object.388389 `g`390 an object with all the attributes of the :data:`flask.g` object.391392 `flashes`393 an internal cache for the flashed messages.394395 Example usage::396397 from flask import _request_ctx_stack398399 def get_session():400 ctx = _request_ctx_stack.top401 if ctx is not None:402 return ctx.sessionMore docstrings for blueprints.Armin Ronacherbefore adoption8617505
lines 403–405why, one step back403404.. autoclass:: flask.blueprints.BlueprintSetupState405 :members:Added note on templates not being updatedArmin Ronacherbefore adoptiondbb9a2e
lines 406–466why, one step back406407Signals408-------409410.. when modifying this list, also update the one in signals.rst411412.. versionadded:: 0.6413414.. data:: signals_available415416 `True` if the signalling system is available. This is the case417 when `blinker`_ is installed.418419.. data:: template_rendered420421 This signal is sent when a template was successfully rendered. The422 signal is invoked with the instance of the template as `template`423 and the context as dictionary (named `context`).424425.. data:: request_started426427 This signal is sent before any request processing started but when the428 request context was set up. Because the request context is already429 bound, the subscriber can access the request with the standard global430 proxies such as :class:`~flask.request`.431432.. data:: request_finished433434 This signal is sent right before the response is sent to the client.435 It is passed the response to be sent named `response`.436437.. data:: got_request_exception438439 This signal is sent when an exception happens during request processing.440 It is sent *before* the standard exception handling kicks in and even441 in debug mode, where no exception handling happens. The exception442 itself is passed to the subscriber as `exception`.443444.. data:: request_tearing_down445446 This signal is sent when the application is tearing down the request.447 This is always called, even if an error happened. No arguments are448 provided.449450.. currentmodule:: None451452.. class:: flask.signals.Namespace453454 An alias for :class:`blinker.base.Namespace` if blinker is available,455 otherwise a dummy class that creates fake signals. This class is456 available for Flask extensions that want to provide the same fallback457 system as Flask itself.458459 .. method:: signal(name, doc=None)460461 Creates a new signal for this namespace if blinker is available,462 otherwise returns a fake signal that has a send method that will463 do nothing but will fail with a :exc:`RuntimeError` for all other464 operations, including connecting.465466.. _blinker: http://pypi.python.org/pypi/blinkerAdded class based view documentationArmin Ronacherbefore adoptionb36d7b3
lines 467–479why, one step back467468Class Based Views469-----------------470471.. versionadded:: 0.7472473.. currentmodule:: None474475.. autoclass:: flask.views.View476 :members:477478.. autoclass:: flask.views.MethodView479 :members:Documented view function optionsArmin Ronacherbefore adoption76796c3
lines 480–517why, one step back480481.. _view-func-options:482483View Function Options484---------------------485486For internal usage the view functions can have some attributes attached to487customize behavior the view function would normally not have control over.488The following attributes can be provided optionally to either override489some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:490491- `__name__`: The name of a function is by default used as endpoint. If492 endpoint is provided explicitly this value is used. Additionally this493 will be prefixed with the name of the blueprint by default which494 cannot be customized from the function itself.495496- `methods`: If methods are not provided when the URL rule is added,497 Flask will look on the view function object itself is an `methods`498 attribute exists. If it does, it will pull the information for the499 methods from there.500501- `provide_automatic_options`: if this attribute is set Flask will502 either force enable or disable the automatic implementation of the503 HTTP `OPTIONS` response. This can be useful when working with504 decorators that want to customize the `OPTIONS` response on a per-view505 basis.506507Full example::508509 def index():510 if request.method == 'OPTIONS':511 # custom options handling here512 ...513 return 'Hello World!'514 index.provide_automatic_options = False515 index.methods = ['GET', 'OPTIONS']516517 app.add_url_rule('/', index)Added a versionaddedArmin Ronacherbefore adoption6ca321c
lines 518–520why, one step back518519.. versionadded:: 0.8520 The `provide_automatic_options` functionality was added.