Skip to content
Myr

api.rst

This file

Path

docs/api.rst

666 lines · 20.0 KiB

Last changed by

Merge branch 'json-sessions'Armin Ronacherbefore adoptione1a5761

History of this file

Take it

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

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 1–146why, 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:: Request32 :members:3334 .. 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.6162 .. attribute:: headers6364 The incoming request headers as a dictionary like object.6566 .. 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.121122.. 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.135136137Response 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

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

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

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 153–217why, 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.200201202Session Interface203-----------------204205.. versionadded:: 0.8206207The 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:217

Merge branch 'json-sessions'Armin Ronacherbefore adoptione1a5761

lines 218–220why, one step back
218.. autoclass:: SecureCookieSession
219 :members:220

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 221–226why, one step back
221.. autoclass:: NullSession
222 :members:223224.. autoclass:: SessionMixin225 :members:226

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

lines 227–233why, one step back
227.. admonition:: Notice
228229 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer230 starting with Flask 0.8. Either catch this down yourself or use231 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the232 app which converts the result to an integer automatically.233

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 234–270why, one step back
234
235Test Client236-----------237238.. currentmodule:: flask.testing239240.. autoclass:: FlaskClient241 :members:242243244Application Globals245-------------------246247.. currentmodule:: flask248249To share data that is valid for one request only from one function to250another, a global variable is not good enough because it would break in251threaded environments. Flask provides you with a special object that252ensures it is only valid for the active request and that will return253different values for each request. In a nutshell: it does the right254thing, like it does for :class:`request` and :class:`session`.255256.. data:: g257258 Just store on this whatever you want. For example a database259 connection or the user that is currently logged in.260261 This is a proxy. See :ref:`notes-on-proxies` for more information.262263264Useful Functions and Classes265----------------------------266267.. data:: current_app268269 Points to the application handling the request. This is useful for270 extensions that want to support multiple applications running side

Updated docs for the app context.Armin Ronacherbefore adoption0207e90

lines 271–273why, one step back
271 by side. This is powered by the application context and not by the
272 request context, so you can change the value of this proxy by273 using the :meth:`~flask.Flask.app_context` method.

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 274–278why, one step back
274
275 This is a proxy. See :ref:`notes-on-proxies` for more information.276277.. autofunction:: has_request_context278

Updated docs for the app context.Armin Ronacherbefore adoption0207e90

lines 279–280why, one step back
279.. autofunction:: has_app_context
280

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 281–294why, one step back
281.. autofunction:: url_for
282283.. function:: abort(code)284285 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given286 status code. For example to abort request handling with a page not287 found exception, you would call ``abort(404)``.288289 :param code: the HTTP error code.290291.. autofunction:: redirect292293.. autofunction:: make_response294

Added after_this_request decorator.Armin Ronacherbefore adoption086348e

lines 295–296why, one step back
295.. autofunction:: after_this_request
296

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 297–363why, one step back
297.. autofunction:: send_file
298299.. autofunction:: send_from_directory300301.. autofunction:: safe_join302303.. autofunction:: escape304305.. autoclass:: Markup306 :members: escape, unescape, striptags307308Message Flashing309----------------310311.. autofunction:: flash312313.. autofunction:: get_flashed_messages314315Returning JSON316--------------317318.. autofunction:: jsonify319320.. data:: json321322 If JSON support is picked up, this will be the module that Flask is323 using to parse and serialize JSON. So instead of doing this yourself::324325 try:326 import simplejson as json327 except ImportError:328 import json329330 You can instead just do this::331332 from flask import json333334 For usage examples, read the :mod:`json` documentation.335336 The :func:`~json.dumps` function of this json module is also available337 as filter called ``|tojson`` in Jinja2. Note that inside `script`338 tags no escaping must take place, so make sure to disable escaping339 with ``|safe`` if you intend to use it inside `script` tags:340341 .. sourcecode:: html+jinja342343 <script type=text/javascript>344 doSomethingWith({{ user.username|tojson|safe }});345 </script>346347 Note that the ``|tojson`` filter escapes forward slashes properly.348349Template Rendering350------------------351352.. autofunction:: render_template353354.. autofunction:: render_template_string355356.. autofunction:: get_template_attribute357358Configuration359-------------360361.. autoclass:: Config362 :members:363

Documented flask.ext.Armin Ronacherbefore adoption1e6c5f0

lines 364–380why, one step back
364Extensions
365----------366367.. data:: flask.ext368369 This module acts as redirect import module to Flask extensions. It was370 added in 0.8 as the canonical way to import Flask extensions and makes371 it possible for us to have more flexibility in how we distribute372 extensions.373374 If you want to use an extension named “Flask-Foo” you would import it375 from :data:`~flask.ext` as follows::376377 from flask.ext import foo378379 .. versionadded:: 0.8380

Added flask.stream_with_contextArmin Ronacherbefore adoptiond521899

lines 381–385why, one step back
381Stream Helpers
382--------------383384.. autofunction:: stream_with_context385

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 386–427why, one step back
386Useful Internals
387----------------388389.. autoclass:: flask.ctx.RequestContext390 :members:391392.. data:: _request_ctx_stack393394 The internal :class:`~werkzeug.local.LocalStack` that is used to implement395 all the context local objects used in Flask. This is a documented396 instance and can be used by extensions and application code but the397 use is discouraged in general.398399 The following attributes are always present on each layer of the400 stack:401402 `app`403 the active Flask application.404405 `url_adapter`406 the URL adapter that was used to match the request.407408 `request`409 the current request object.410411 `session`412 the active session object.413414 `g`415 an object with all the attributes of the :data:`flask.g` object.416417 `flashes`418 an internal cache for the flashed messages.419420 Example usage::421422 from flask import _request_ctx_stack423424 def get_session():425 ctx = _request_ctx_stack.top426 if ctx is not None:427 return ctx.session

Updated docs for the app context.Armin Ronacherbefore adoption0207e90

lines 428–437why, one step back
428
429.. autoclass:: flask.ctx.AppContext430 :members:431432.. data:: _app_ctx_stack433434 Works similar to the request context but only binds the application.435 This is mainly there for extensions to store data.436437 .. versionadded:: 0.9

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 438–481why, one step back
438
439.. autoclass:: flask.blueprints.BlueprintSetupState440 :members:441442Signals443-------444445.. when modifying this list, also update the one in signals.rst446447.. versionadded:: 0.6448449.. data:: signals_available450451 `True` if the signalling system is available. This is the case452 when `blinker`_ is installed.453454.. data:: template_rendered455456 This signal is sent when a template was successfully rendered. The457 signal is invoked with the instance of the template as `template`458 and the context as dictionary (named `context`).459460.. data:: request_started461462 This signal is sent before any request processing started but when the463 request context was set up. Because the request context is already464 bound, the subscriber can access the request with the standard global465 proxies such as :class:`~flask.request`.466467.. data:: request_finished468469 This signal is sent right before the response is sent to the client.470 It is passed the response to be sent named `response`.471472.. data:: got_request_exception473474 This signal is sent when an exception happens during request processing.475 It is sent *before* the standard exception handling kicks in and even476 in debug mode, where no exception handling happens. The exception477 itself is passed to the subscriber as `exception`.478479.. data:: request_tearing_down480481 This signal is sent when the application is tearing down the request.

Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c

lines 482–493why, one step back
482 This is always called, even if an error happened. An `exc` keyword
483 argument is passed with the exception that caused the teardown.484485 .. versionchanged:: 0.9486 The `exc` parameter was added.487488.. data:: appcontext_tearing_down489490 This signal is sent when the application is tearing down the491 application context. This is always called, even if an error happened.492 An `exc` keyword argument is passed with the exception that caused the493 teardown.

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 494–512why, one step back
494
495.. currentmodule:: None496497.. class:: flask.signals.Namespace498499 An alias for :class:`blinker.base.Namespace` if blinker is available,500 otherwise a dummy class that creates fake signals. This class is501 available for Flask extensions that want to provide the same fallback502 system as Flask itself.503504 .. method:: signal(name, doc=None)505506 Creates a new signal for this namespace if blinker is available,507 otherwise returns a fake signal that has a send method that will508 do nothing but will fail with a :exc:`RuntimeError` for all other509 operations, including connecting.510511.. _blinker: http://pypi.python.org/pypi/blinker512

Merge pull request #392 from FND/docsRon DuPlainbefore adoption7ba5196

line 513why, one step back
513Class-Based Views

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 514–525why, one step back
514-----------------
515516.. versionadded:: 0.7517518.. currentmodule:: None519520.. autoclass:: flask.views.View521 :members:522523.. autoclass:: flask.views.MethodView524 :members:525

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

lines 526–537why, one step back
526.. _url-route-registrations:
527528URL Route Registrations529-----------------------530531Generally there are three ways to define rules for the routing system:5325331. You can use the :meth:`flask.Flask.route` decorator.5342. You can use the :meth:`flask.Flask.add_url_rule` function.5353. You can directly access the underlying Werkzeug routing system536 which is exposed as :attr:`flask.Flask.url_map`.537

Fixed typos in copy/pasted textArmin Ronacherbefore adoption142c9c3

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

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

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

Fixed typos in copy/pasted textArmin Ronacherbefore adoption142c9c3

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

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

lines 546–547why, one step back
546
547=========== ===============================================

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

line 548why, one step back
548`string` accepts any text without a slash (the default)

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

lines 549–553why, one step back
549`int` accepts integers
550`float` like `int` but for floating point values551`path` like the default but also accepts slashes552=========== ===============================================553

More doc typo fixesArmin Ronacherbefore adoption363d9ed

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

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

lines 555–574why, one step back
555
556 @app.route('/')557 def index():558 pass559560 @app.route('/<username>')561 def show_user(username):562 pass563564 @app.route('/post/<int:post_id>')565 def show_post(post_id):566 pass567568An important detail to keep in mind is how Flask deals with trailing569slashes. The idea is to keep each URL unique so the following rules570apply:5715721. If a rule ends with a slash and is requested without a slash by the573 user, the user is automatically redirected to the same page with a574 trailing slash attached.

More doc typo fixesArmin Ronacherbefore adoption363d9ed

line 575why, one step back
5752. 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 576–592why, one step back
576 page with a trailing slash, a 404 not found is raised.
577578This is consistent with how web servers deal with static files. This579also makes it possible to use relative link targets safely.580581You can also define multiple rules for the same function. They have to be582unique however. Defaults can also be specified. Here for example is a583definition for a URL that accepts an optional page::584585 @app.route('/users/', defaults={'page': 1})586 @app.route('/users/page/<int:page>')587 def show_users(page):588 pass589590This specifies that ``/users/`` will be the URL for page one and591``/users/page/N`` will be the URL for page `N`.592

Inserted verbArmin Ronacherbefore adoption83b1da8

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

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

lines 594–598why, one step back
594:meth:`~flask.Flask.add_url_rule` accept. The only difference is that
595with the route parameter the view function is defined with the decorator596instead of the `view_func` parameter.597598=============== ==========================================================

Merge pull request #493 from kuyanatan/patch-1Ron DuPlainbefore adoptionfd62cd8

line 599why, one step back
599`rule` the URL rule as string

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

lines 600–622why, one step back
600`endpoint` the endpoint for the registered URL rule. Flask itself
601 assumes that the name of the view function is the name602 of the endpoint if not explicitly stated.603`view_func` the function to call when serving a request to the604 provided endpoint. If this is not provided one can605 specify the function later by storing it in the606 :attr:`~flask.Flask.view_functions` dictionary with the607 endpoint as key.608`defaults` A dictionary with defaults for this rule. See the609 example above for how defaults work.610`subdomain` specifies the rule for the subdomain in case subdomain611 matching is in use. If not specified the default612 subdomain is assumed.613`**options` the options to be forwarded to the underlying614 :class:`~werkzeug.routing.Rule` object. A change to615 Werkzeug is handling of method options. methods is a list616 of methods this rule should be limited to (`GET`, `POST`617 etc.). By default a rule just listens for `GET` (and618 implicitly `HEAD`). Starting with Flask 0.6, `OPTIONS` is619 implicitly added and handled by the standard request620 handling. They have to be specified as keyword arguments.621=============== ==========================================================622

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 623–648why, one step back
623.. _view-func-options:
624625View Function Options626---------------------627628For internal usage the view functions can have some attributes attached to629customize behavior the view function would normally not have control over.630The following attributes can be provided optionally to either override631some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:632633- `__name__`: The name of a function is by default used as endpoint. If634 endpoint is provided explicitly this value is used. Additionally this635 will be prefixed with the name of the blueprint by default which636 cannot be customized from the function itself.637638- `methods`: If methods are not provided when the URL rule is added,639 Flask will look on the view function object itself is an `methods`640 attribute exists. If it does, it will pull the information for the641 methods from there.642643- `provide_automatic_options`: if this attribute is set Flask will644 either force enable or disable the automatic implementation of the645 HTTP `OPTIONS` response. This can be useful when working with646 decorators that want to customize the `OPTIONS` response on a per-view647 basis.648

Added required_methodsArmin Ronacherbefore adoptiondbfd406

lines 649–652why, one step back
649- `required_methods`: if this attribute is set, Flask will always add
650 these methods when registering a URL rule even if the methods were651 explicitly overriden in the ``route()`` call.652

make_default_options_response now tries to use Werkzeug 0.7 functionality before falling back.Armin Ronacherbefore adoptionb256e9f

lines 653–666why, one step back
653Full example::
654655 def index():656 if request.method == 'OPTIONS':657 # custom options handling here658 ...659 return 'Hello World!'660 index.provide_automatic_options = False661 index.methods = ['GET', 'OPTIONS']662663 app.add_url_rule('/', index)664665.. versionadded:: 0.8666 The `provide_automatic_options` functionality was added.