Skip to content
Myr

api.rst

This file

Path

docs/api.rst

628 lines · 18.8 KiB

Last changed by

Update docs/api.rst a bit to reflect code.awsumbefore adoptiond620ea7

History of this file

Take it

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

Bumped version number for this branch to 0.7.1Armin Ronacherbefore adoption510823c

lines 1–31why, 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:192021Blueprint Objects22-----------------2324.. autoclass:: Blueprint25 :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:

Bumped version number for this branch to 0.7.1Armin Ronacherbefore adoption510823c

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

Bumped version number for this branch to 0.7.1Armin Ronacherbefore adoption510823c

lines 66–121why, 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:: 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.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

Bumped version number for this branch to 0.7.1Armin Ronacherbefore adoption510823c

lines 136–146why, 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.146

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

line 147why, one step back
147 .. attribute:: status

Bumped version number for this branch to 0.7.1Armin Ronacherbefore adoption510823c

line 148why, one step back
148

Update docs/api.rst a bit to reflect code.awsumbefore adoptiond620ea7

lines 149–152why, one step back
149 A string with a response status.
150151 .. attribute:: status_code152

Bumped version number for this branch to 0.7.1Armin Ronacherbefore adoption510823c

lines 153–201why, one step back
153 The response status as integer.
154155156Sessions157--------158159If you have the :attr:`Flask.secret_key` set you can use sessions in Flask160applications. A session basically makes it possible to remember161information from one request to another. The way Flask does this is by162using a signed cookie. So the user can look at the session contents, but163not modify it unless they know the secret key, so make sure to set that164to something complex and unguessable.165166To access the current session you can use the :class:`session` object:167168.. class:: session169170 The session object works pretty much like an ordinary dict, with the171 difference that it keeps track on modifications.172173 This is a proxy. See :ref:`notes-on-proxies` for more information.174175 The following attributes are interesting:176177 .. attribute:: new178179 `True` if the session is new, `False` otherwise.180181 .. attribute:: modified182183 `True` if the session object detected a modification. Be advised184 that modifications on mutable structures are not picked up185 automatically, in that situation you have to explicitly set the186 attribute to `True` yourself. Here an example::187188 # this change is not picked up because a mutable object (here189 # a list) is changed.190 session['objects'].append(42)191 # so mark it as modified yourself192 session.modified = True193194 .. attribute:: permanent195196 If set to `True` the session lives for197 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The198 default is 31 days. If set to `False` (which is the default) the199 session will be deleted when the user closes the browser.200201

Refactored session interfaceArmin Ronacherbefore adoption0fccfe7

lines 202–204why, one step back
202Session Interface
203-----------------204

The session interface is new in 0.8, not 0.7Armin Ronacherbefore adoptiondeb513c

line 205why, one step back
205.. versionadded:: 0.8

Refactored session interfaceArmin Ronacherbefore adoption0fccfe7

lines 206–223why, one step back
206
207The session interface provides a simple way to replace the session208implementation that Flask is using.209210.. currentmodule:: flask.sessions211212.. autoclass:: SessionInterface213 :members:214215.. autoclass:: SecureCookieSessionInterface216 :members:217218.. autoclass:: NullSession219 :members:220221.. autoclass:: SessionMixin222 :members:223

PERMANENT_SESSION_LIFETIME can now be an integer. This fixes #310Armin Ronacherbefore adoption6dccf77

lines 224–230why, one step back
224.. admonition:: Notice
225226 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer227 starting with Flask 0.8. Either catch this down yourself or use228 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the229 app which converts the result to an integer automatically.230

Refactored session interfaceArmin Ronacherbefore adoption0fccfe7

line 231why, one step back
231

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

lines 232–236why, one step back
232Test Client
233-----------234235.. currentmodule:: flask.testing236

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 237why, one step back
237.. autoclass:: FlaskClient

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

lines 238–240why, one step back
238 :members:
239240

Bumped version number for this branch to 0.7.1Armin Ronacherbefore adoption510823c

lines 241–242why, one step back
241Application Globals
242-------------------

Refactored session interfaceArmin Ronacherbefore adoption0fccfe7

lines 243–244why, one step back
243
244.. currentmodule:: flask

Bumped version number for this branch to 0.7.1Armin Ronacherbefore adoption510823c

lines 245–354why, one step back
245
246To share data that is valid for one request only from one function to247another, a global variable is not good enough because it would break in248threaded environments. Flask provides you with a special object that249ensures it is only valid for the active request and that will return250different values for each request. In a nutshell: it does the right251thing, like it does for :class:`request` and :class:`session`.252253.. data:: g254255 Just store on this whatever you want. For example a database256 connection or the user that is currently logged in.257258 This is a proxy. See :ref:`notes-on-proxies` for more information.259260261Useful Functions and Classes262----------------------------263264.. data:: current_app265266 Points to the application handling the request. This is useful for267 extensions that want to support multiple applications running side268 by side.269270 This is a proxy. See :ref:`notes-on-proxies` for more information.271272.. autofunction:: has_request_context273274.. autofunction:: url_for275276.. function:: abort(code)277278 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given279 status code. For example to abort request handling with a page not280 found exception, you would call ``abort(404)``.281282 :param code: the HTTP error code.283284.. autofunction:: redirect285286.. autofunction:: make_response287288.. autofunction:: send_file289290.. autofunction:: send_from_directory291292.. autofunction:: safe_join293294.. autofunction:: escape295296.. autoclass:: Markup297 :members: escape, unescape, striptags298299Message Flashing300----------------301302.. autofunction:: flash303304.. autofunction:: get_flashed_messages305306Returning JSON307--------------308309.. autofunction:: jsonify310311.. data:: json312313 If JSON support is picked up, this will be the module that Flask is314 using to parse and serialize JSON. So instead of doing this yourself::315316 try:317 import simplejson as json318 except ImportError:319 import json320321 You can instead just do this::322323 from flask import json324325 For usage examples, read the :mod:`json` documentation.326327 The :func:`~json.dumps` function of this json module is also available328 as filter called ``|tojson`` in Jinja2. Note that inside `script`329 tags no escaping must take place, so make sure to disable escaping330 with ``|safe`` if you intend to use it inside `script` tags:331332 .. sourcecode:: html+jinja333334 <script type=text/javascript>335 doSomethingWith({{ user.username|tojson|safe }});336 </script>337338 Note that the ``|tojson`` filter escapes forward slashes properly.339340Template Rendering341------------------342343.. autofunction:: render_template344345.. autofunction:: render_template_string346347.. autofunction:: get_template_attribute348349Configuration350-------------351352.. autoclass:: Config353 :members:354

Documented flask.ext.Armin Ronacherbefore adoption1e6c5f0

lines 355–371why, one step back
355Extensions
356----------357358.. data:: flask.ext359360 This module acts as redirect import module to Flask extensions. It was361 added in 0.8 as the canonical way to import Flask extensions and makes362 it possible for us to have more flexibility in how we distribute363 extensions.364365 If you want to use an extension named “Flask-Foo” you would import it366 from :data:`~flask.ext` as follows::367368 from flask.ext import foo369370 .. versionadded:: 0.8371

Bumped version number for this branch to 0.7.1Armin Ronacherbefore adoption510823c

lines 372–490why, one step back
372Useful Internals
373----------------374375.. autoclass:: flask.ctx.RequestContext376 :members:377378.. data:: _request_ctx_stack379380 The internal :class:`~werkzeug.local.LocalStack` that is used to implement381 all the context local objects used in Flask. This is a documented382 instance and can be used by extensions and application code but the383 use is discouraged in general.384385 The following attributes are always present on each layer of the386 stack:387388 `app`389 the active Flask application.390391 `url_adapter`392 the URL adapter that was used to match the request.393394 `request`395 the current request object.396397 `session`398 the active session object.399400 `g`401 an object with all the attributes of the :data:`flask.g` object.402403 `flashes`404 an internal cache for the flashed messages.405406 Example usage::407408 from flask import _request_ctx_stack409410 def get_session():411 ctx = _request_ctx_stack.top412 if ctx is not None:413 return ctx.session414415.. autoclass:: flask.blueprints.BlueprintSetupState416 :members:417418Signals419-------420421.. when modifying this list, also update the one in signals.rst422423.. versionadded:: 0.6424425.. data:: signals_available426427 `True` if the signalling system is available. This is the case428 when `blinker`_ is installed.429430.. data:: template_rendered431432 This signal is sent when a template was successfully rendered. The433 signal is invoked with the instance of the template as `template`434 and the context as dictionary (named `context`).435436.. data:: request_started437438 This signal is sent before any request processing started but when the439 request context was set up. Because the request context is already440 bound, the subscriber can access the request with the standard global441 proxies such as :class:`~flask.request`.442443.. data:: request_finished444445 This signal is sent right before the response is sent to the client.446 It is passed the response to be sent named `response`.447448.. data:: got_request_exception449450 This signal is sent when an exception happens during request processing.451 It is sent *before* the standard exception handling kicks in and even452 in debug mode, where no exception handling happens. The exception453 itself is passed to the subscriber as `exception`.454455.. data:: request_tearing_down456457 This signal is sent when the application is tearing down the request.458 This is always called, even if an error happened. No arguments are459 provided.460461.. currentmodule:: None462463.. class:: flask.signals.Namespace464465 An alias for :class:`blinker.base.Namespace` if blinker is available,466 otherwise a dummy class that creates fake signals. This class is467 available for Flask extensions that want to provide the same fallback468 system as Flask itself.469470 .. method:: signal(name, doc=None)471472 Creates a new signal for this namespace if blinker is available,473 otherwise returns a fake signal that has a send method that will474 do nothing but will fail with a :exc:`RuntimeError` for all other475 operations, including connecting.476477.. _blinker: http://pypi.python.org/pypi/blinker478479Class Based Views480-----------------481482.. versionadded:: 0.7483484.. currentmodule:: None485486.. autoclass:: flask.views.View487 :members:488489.. autoclass:: flask.views.MethodView490 :members:

Documented view function optionsArmin Ronacherbefore adoption76796c3

line 491why, one step back
491

Cleaned up url routing common docs. This fixes #279Armin Ronacherbefore adoptiondf1dd57

lines 492–503why, one step back
492.. _url-route-registrations:
493494URL Route Registrations495-----------------------496497Generally there are three ways to define rules for the routing system:4984991. You can use the :meth:`flask.Flask.route` decorator.5002. You can use the :meth:`flask.Flask.add_url_rule` function.5013. You can directly access the underlying Werkzeug routing system502 which is exposed as :attr:`flask.Flask.url_map`.503

Fixed typos in copy/pasted textArmin Ronacherbefore adoption142c9c3

line 504why, one step back
504Variable parts in the route can be specified with angular brackets

Cleaned up url routing common docs. This fixes #279Armin Ronacherbefore adoptiondf1dd57

lines 505–510why, one step back
505(``/user/<username>``). By default a variable part in the URL accepts any
506string without a slash however a different converter can be specified as507well by using ``<converter:name>``.508509Variable parts are passed to the view function as keyword arguments.510

Fixed typos in copy/pasted textArmin Ronacherbefore adoption142c9c3

line 511why, one step back
511The following converters are available:

Cleaned up url routing common docs. This fixes #279Armin Ronacherbefore adoptiondf1dd57

lines 512–519why, one step back
512
513=========== ===============================================514`unicode` accepts any text without a slash (the default)515`int` accepts integers516`float` like `int` but for floating point values517`path` like the default but also accepts slashes518=========== ===============================================519

More doc typo fixesArmin Ronacherbefore adoption363d9ed

line 520why, one step back
520Here are some examples::

Cleaned up url routing common docs. This fixes #279Armin Ronacherbefore adoptiondf1dd57

lines 521–540why, one step back
521
522 @app.route('/')523 def index():524 pass525526 @app.route('/<username>')527 def show_user(username):528 pass529530 @app.route('/post/<int:post_id>')531 def show_post(post_id):532 pass533534An important detail to keep in mind is how Flask deals with trailing535slashes. The idea is to keep each URL unique so the following rules536apply:5375381. If a rule ends with a slash and is requested without a slash by the539 user, the user is automatically redirected to the same page with a540 trailing slash attached.

More doc typo fixesArmin Ronacherbefore adoption363d9ed

line 541why, one step back
5412. If a rule does not end with a trailing slash and the user requests the

Cleaned up url routing common docs. This fixes #279Armin Ronacherbefore adoptiondf1dd57

lines 542–558why, one step back
542 page with a trailing slash, a 404 not found is raised.
543544This is consistent with how web servers deal with static files. This545also makes it possible to use relative link targets safely.546547You can also define multiple rules for the same function. They have to be548unique however. Defaults can also be specified. Here for example is a549definition for a URL that accepts an optional page::550551 @app.route('/users/', defaults={'page': 1})552 @app.route('/users/page/<int:page>')553 def show_users(page):554 pass555556This specifies that ``/users/`` will be the URL for page one and557``/users/page/N`` will be the URL for page `N`.558

Inserted verbArmin Ronacherbefore adoption83b1da8

line 559why, one step back
559Here are the parameters that :meth:`~flask.Flask.route` and

Cleaned up url routing common docs. This fixes #279Armin Ronacherbefore adoptiondf1dd57

lines 560–588why, one step back
560:meth:`~flask.Flask.add_url_rule` accept. The only difference is that
561with the route parameter the view function is defined with the decorator562instead of the `view_func` parameter.563564=============== ==========================================================565`rule` the URL roule as string566`endpoint` the endpoint for the registered URL rule. Flask itself567 assumes that the name of the view function is the name568 of the endpoint if not explicitly stated.569`view_func` the function to call when serving a request to the570 provided endpoint. If this is not provided one can571 specify the function later by storing it in the572 :attr:`~flask.Flask.view_functions` dictionary with the573 endpoint as key.574`defaults` A dictionary with defaults for this rule. See the575 example above for how defaults work.576`subdomain` specifies the rule for the subdomain in case subdomain577 matching is in use. If not specified the default578 subdomain is assumed.579`**options` the options to be forwarded to the underlying580 :class:`~werkzeug.routing.Rule` object. A change to581 Werkzeug is handling of method options. methods is a list582 of methods this rule should be limited to (`GET`, `POST`583 etc.). By default a rule just listens for `GET` (and584 implicitly `HEAD`). Starting with Flask 0.6, `OPTIONS` is585 implicitly added and handled by the standard request586 handling. They have to be specified as keyword arguments.587=============== ==========================================================588

Documented view function optionsArmin Ronacherbefore adoption76796c3

lines 589–625why, one step back
589.. _view-func-options:
590591View Function Options592---------------------593594For internal usage the view functions can have some attributes attached to595customize behavior the view function would normally not have control over.596The following attributes can be provided optionally to either override597some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:598599- `__name__`: The name of a function is by default used as endpoint. If600 endpoint is provided explicitly this value is used. Additionally this601 will be prefixed with the name of the blueprint by default which602 cannot be customized from the function itself.603604- `methods`: If methods are not provided when the URL rule is added,605 Flask will look on the view function object itself is an `methods`606 attribute exists. If it does, it will pull the information for the607 methods from there.608609- `provide_automatic_options`: if this attribute is set Flask will610 either force enable or disable the automatic implementation of the611 HTTP `OPTIONS` response. This can be useful when working with612 decorators that want to customize the `OPTIONS` response on a per-view613 basis.614615Full example::616617 def index():618 if request.method == 'OPTIONS':619 # custom options handling here620 ...621 return 'Hello World!'622 index.provide_automatic_options = False623 index.methods = ['GET', 'OPTIONS']624625 app.add_url_rule('/', index)

Added a versionaddedArmin Ronacherbefore adoption6ca321c

lines 626–628why, one step back
626
627.. versionadded:: 0.8628 The `provide_automatic_options` functionality was added.