api.rst
This file
Path
docs/api.rst
746 lines · 22.4 KiB
Last changed by
Merge pull request #776 from seedofjoy/masterDaniel Neuhäuserbefore adoption2132040
History of this fileTake it
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.146147 .. attribute:: status148149 A string with a response status.150151 .. attribute:: status_code152153 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:217218.. autoclass:: SecureCookieSession219 :members:220221.. autoclass:: NullSession222 :members:223224.. autoclass:: SessionMixin225 :members:226227.. autodata:: session_json_serializer228229 This object provides dumping and loading methods similar to simplejson230 but it also tags certain builtin Python objects that commonly appear in231 sessions. Currently the following extended values are supported in232 the JSON it dumps:233234 - :class:`~markupsafe.Markup` objects235 - :class:`~uuid.UUID` objects236 - :class:`~datetime.datetime` objects237 - :class:`tuple`\s238239.. admonition:: Notice240241 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer242 starting with Flask 0.8. Either catch this down yourself or use243 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the244 app which converts the result to an integer automatically.245246247Test Client248-----------249250.. currentmodule:: flask.testing251252.. autoclass:: FlaskClient253 :members:254255256Application Globals257-------------------258259.. currentmodule:: flask260261To share data that is valid for one request only from one function to262another, a global variable is not good enough because it would break in263threaded environments. Flask provides you with a special object that264ensures it is only valid for the active request and that will return265different values for each request. In a nutshell: it does the right266thing, like it does for :class:`request` and :class:`session`.267268.. data:: g269270 Just store on this whatever you want. For example a database271 connection or the user that is currently logged in.272273 Starting with Flask 0.10 this is stored on the application context and274 no longer on the request context which means it becomes available if275 only the application context is bound and not yet a request. This276 is especially useful when combined with the :ref:`faking-resources`277 pattern for testing.278279 Additionally as of 0.10 you can use the :meth:`get` method to280 get an attribute or `None` (or the second argument) if it's not set.281 These two usages are now equivalent::282283 user = getattr(flask.g, 'user', None)284 user = flask.g.get('user', None)285286 It's now also possible to use the ``in`` operator on it to see if an287 attribute is defined and it yields all keys on iteration.288289 This is a proxy. See :ref:`notes-on-proxies` for more information.290291292Useful Functions and Classes293----------------------------294295.. data:: current_app296297 Points to the application handling the request. This is useful for298 extensions that want to support multiple applications running side299 by side. This is powered by the application context and not by the300 request context, so you can change the value of this proxy by301 using the :meth:`~flask.Flask.app_context` method.302303 This is a proxy. See :ref:`notes-on-proxies` for more information.304305.. autofunction:: has_request_context306307.. autofunction:: copy_current_request_context308309.. autofunction:: has_app_context310311.. autofunction:: url_for312313.. function:: abort(code)314315 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given316 status code. For example to abort request handling with a page not317 found exception, you would call ``abort(404)``.318319 :param code: the HTTP error code.320321.. autofunction:: redirect322323.. autofunction:: make_response324325.. autofunction:: after_this_request326327.. autofunction:: send_file328329.. autofunction:: send_from_directory330331.. autofunction:: safe_join332333.. autofunction:: escape334335.. autoclass:: Markup336 :members: escape, unescape, striptags337338Message Flashing339----------------340341.. autofunction:: flash342343.. autofunction:: get_flashed_messages344345JSON Support346------------347348.. module:: flask.json349350Flask uses ``simplejson`` for the JSON implementation. Since simplejson351is provided both by the standard library as well as extension Flask will352try simplejson first and then fall back to the stdlib json module. On top353of that it will delegate access to the current application's JSOn encoders354and decoders for easier customization.355356So for starters instead of doing::357358 try:359 import simplejson as json360 except ImportError:361 import json362363You can instead just do this::364365 from flask import json366367For usage examples, read the :mod:`json` documentation in the standard368lirbary. The following extensions are by default applied to the stdlib's369JSON module:3703711. ``datetime`` objects are serialized as :rfc:`822` strings.3722. Any object with an ``__html__`` method (like :class:`~flask.Markup`)373 will have that method called and then the return value is serialized374 as string.375376The :func:`~htmlsafe_dumps` function of this json module is also available377as filter called ``|tojson`` in Jinja2. Note that inside `script`378tags no escaping must take place, so make sure to disable escaping379with ``|safe`` if you intend to use it inside `script` tags unless380you are using Flask 0.10 which implies that:381382.. sourcecode:: html+jinja383384 <script type=text/javascript>385 doSomethingWith({{ user.username|tojson|safe }});386 </script>387388.. autofunction:: jsonify389390.. autofunction:: dumps391392.. autofunction:: dump393394.. autofunction:: loads395396.. autofunction:: load397398.. autoclass:: JSONEncoder399 :members:400401.. autoclass:: JSONDecoder402 :members:403404Template Rendering405------------------406407.. currentmodule:: flask408409.. autofunction:: render_template410411.. autofunction:: render_template_string412413.. autofunction:: get_template_attribute414415Configuration416-------------417418.. autoclass:: Config419 :members:420421Extensions422----------423424.. data:: flask.ext425426 This module acts as redirect import module to Flask extensions. It was427 added in 0.8 as the canonical way to import Flask extensions and makes428 it possible for us to have more flexibility in how we distribute429 extensions.430431 If you want to use an extension named “Flask-Foo” you would import it432 from :data:`~flask.ext` as follows::433434 from flask.ext import foo435436 .. versionadded:: 0.8437438Stream Helpers439--------------440441.. autofunction:: stream_with_context442443Useful Internals444----------------445446.. autoclass:: flask.ctx.RequestContext447 :members:448449.. data:: _request_ctx_stack450451 The internal :class:`~werkzeug.local.LocalStack` that is used to implement452 all the context local objects used in Flask. This is a documented453 instance and can be used by extensions and application code but the454 use is discouraged in general.455456 The following attributes are always present on each layer of the457 stack:458459 `app`460 the active Flask application.461462 `url_adapter`463 the URL adapter that was used to match the request.464465 `request`466 the current request object.467468 `session`469 the active session object.470471 `g`472 an object with all the attributes of the :data:`flask.g` object.473474 `flashes`475 an internal cache for the flashed messages.476477 Example usage::478479 from flask import _request_ctx_stack480481 def get_session():482 ctx = _request_ctx_stack.top483 if ctx is not None:484 return ctx.session485486.. autoclass:: flask.ctx.AppContext487 :members:488489.. data:: _app_ctx_stack490491 Works similar to the request context but only binds the application.492 This is mainly there for extensions to store data.493494 .. versionadded:: 0.9495496.. autoclass:: flask.blueprints.BlueprintSetupState497 :members:498499Signals500-------501502.. when modifying this list, also update the one in signals.rst503504.. versionadded:: 0.6505506.. data:: signals_available507508 `True` if the signalling system is available. This is the case509 when `blinker`_ is installed.510511.. data:: template_rendered512513 This signal is sent when a template was successfully rendered. The514 signal is invoked with the instance of the template as `template`515 and the context as dictionary (named `context`).516517.. data:: request_started518519 This signal is sent before any request processing started but when the520 request context was set up. Because the request context is already521 bound, the subscriber can access the request with the standard global522 proxies such as :class:`~flask.request`.523524.. data:: request_finished525526 This signal is sent right before the response is sent to the client.527 It is passed the response to be sent named `response`.528529.. data:: got_request_exception530531 This signal is sent when an exception happens during request processing.532 It is sent *before* the standard exception handling kicks in and even533 in debug mode, where no exception handling happens. The exception534 itself is passed to the subscriber as `exception`.535536.. data:: request_tearing_down537538 This signal is sent when the application is tearing down the request.539 This is always called, even if an error happened. An `exc` keyword540 argument is passed with the exception that caused the teardown.541542 .. versionchanged:: 0.9543 The `exc` parameter was added.544545.. data:: appcontext_tearing_down546547 This signal is sent when the application is tearing down the548 application context. This is always called, even if an error happened.549 An `exc` keyword argument is passed with the exception that caused the550 teardown. The sender is the application.551552.. data:: appcontext_pushed553554 This signal is sent when an application context is pushed. The sender555 is the application.556557 .. versionadded:: 0.10558559.. data:: appcontext_popped560561 This signal is sent when an application context is popped. The sender562 is the application. This usually falls in line with the563 :data:`appcontext_tearing_down` signal.564565 .. versionadded:: 0.10566567.. data:: message_flashed568569 This signal is sent when the application is flashing a message. The570 messages is sent as `message` keyword argument and the category as571 `category`.572573 .. versionadded:: 0.10574575.. currentmodule:: None576577.. class:: flask.signals.Namespace578579 An alias for :class:`blinker.base.Namespace` if blinker is available,580 otherwise a dummy class that creates fake signals. This class is581 available for Flask extensions that want to provide the same fallback582 system as Flask itself.583584 .. method:: signal(name, doc=None)585586 Creates a new signal for this namespace if blinker is available,587 otherwise returns a fake signal that has a send method that will588 do nothing but will fail with a :exc:`RuntimeError` for all other589 operations, including connecting.590591.. _blinker: http://pypi.python.org/pypi/blinker592593Class-Based Views594-----------------595596.. versionadded:: 0.7597598.. currentmodule:: None599600.. autoclass:: flask.views.View601 :members:602603.. autoclass:: flask.views.MethodView604 :members:605606.. _url-route-registrations:607608URL Route Registrations609-----------------------610611Generally there are three ways to define rules for the routing system:6126131. You can use the :meth:`flask.Flask.route` decorator.6142. You can use the :meth:`flask.Flask.add_url_rule` function.6153. You can directly access the underlying Werkzeug routing system616 which is exposed as :attr:`flask.Flask.url_map`.617618Variable parts in the route can be specified with angular brackets619(``/user/<username>``). By default a variable part in the URL accepts any620string without a slash however a different converter can be specified as621well by using ``<converter:name>``.622623Variable parts are passed to the view function as keyword arguments.624625The following converters are available:626627=========== ===============================================628`string` accepts any text without a slash (the default)629`int` accepts integers630`float` like `int` but for floating point values631`path` like the default but also accepts slashes632=========== ===============================================633634Here are some examples::635636 @app.route('/')637 def index():638 pass639640 @app.route('/<username>')641 def show_user(username):642 pass643644 @app.route('/post/<int:post_id>')645 def show_post(post_id):646 pass647648An important detail to keep in mind is how Flask deals with trailing649slashes. The idea is to keep each URL unique so the following rules650apply:6516521. If a rule ends with a slash and is requested without a slash by the653 user, the user is automatically redirected to the same page with a654 trailing slash attached.6552. If a rule does not end with a trailing slash and the user requests the656 page with a trailing slash, a 404 not found is raised.657658This is consistent with how web servers deal with static files. This659also makes it possible to use relative link targets safely.660661You can also define multiple rules for the same function. They have to be662unique however. Defaults can also be specified. Here for example is a663definition for a URL that accepts an optional page::664665 @app.route('/users/', defaults={'page': 1})666 @app.route('/users/page/<int:page>')667 def show_users(page):668 pass669670This specifies that ``/users/`` will be the URL for page one and671``/users/page/N`` will be the URL for page `N`.672673Here are the parameters that :meth:`~flask.Flask.route` and674:meth:`~flask.Flask.add_url_rule` accept. The only difference is that675with the route parameter the view function is defined with the decorator676instead of the `view_func` parameter.677678=============== ==========================================================679`rule` the URL rule as string680`endpoint` the endpoint for the registered URL rule. Flask itself681 assumes that the name of the view function is the name682 of the endpoint if not explicitly stated.683`view_func` the function to call when serving a request to the684 provided endpoint. If this is not provided one can685 specify the function later by storing it in the686 :attr:`~flask.Flask.view_functions` dictionary with the687 endpoint as key.688`defaults` A dictionary with defaults for this rule. See the689 example above for how defaults work.690`subdomain` specifies the rule for the subdomain in case subdomain691 matching is in use. If not specified the default692 subdomain is assumed.693`**options` the options to be forwarded to the underlying694 :class:`~werkzeug.routing.Rule` object. A change to695 Werkzeug is handling of method options. methods is a list696 of methods this rule should be limited to (`GET`, `POST`697 etc.). By default a rule just listens for `GET` (and698 implicitly `HEAD`). Starting with Flask 0.6, `OPTIONS` is699 implicitly added and handled by the standard request700 handling. They have to be specified as keyword arguments.701=============== ==========================================================702703.. _view-func-options:704705View Function Options706---------------------707708For internal usage the view functions can have some attributes attached to709customize behavior the view function would normally not have control over.710The following attributes can be provided optionally to either override711some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:712713- `__name__`: The name of a function is by default used as endpoint. If714 endpoint is provided explicitly this value is used. Additionally this715 will be prefixed with the name of the blueprint by default which716 cannot be customized from the function itself.717718- `methods`: If methods are not provided when the URL rule is added,719 Flask will look on the view function object itself is an `methods`720 attribute exists. If it does, it will pull the information for the721 methods from there.722723- `provide_automatic_options`: if this attribute is set Flask will724 either force enable or disable the automatic implementation of the725 HTTP `OPTIONS` response. This can be useful when working with726 decorators that want to customize the `OPTIONS` response on a per-view727 basis.728729- `required_methods`: if this attribute is set, Flask will always add730 these methods when registering a URL rule even if the methods were731 explicitly overriden in the ``route()`` call.732733Full example::734735 def index():736 if request.method == 'OPTIONS':737 # custom options handling here738 ...739 return 'Hello World!'740 index.provide_automatic_options = False741 index.methods = ['GET', 'OPTIONS']742743 app.add_url_rule('/', index)744745.. versionadded:: 0.8746 The `provide_automatic_options` functionality was added.