api.rst
This file
Path
docs/api.rst
891 lines · 26.9 KiB
Last changed by
Use abort docs from WerkzeugMarkus Unterwaditzerbefore adoptiondcfdfc6
History of this fileTake it
The walk stopped after 200 commits: lines older than f63cd72 point at it.
Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 1–291why, 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: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:: full_path90 .. attribute:: script_root91 .. attribute:: url92 .. attribute:: base_url93 .. attribute:: url_root9495 Provides different ways to look at the current `IRI96 <http://tools.ietf.org/html/rfc3987>`_. Imagine your application is97 listening on the following application root::9899 http://www.example.com/myapplication100101 And a user requests the following URI::102103 http://www.example.com/myapplication/%CF%80/page.html?x=y104105 In this case the values of the above mentioned attributes would be106 the following:107108 ============= ======================================================109 `path` ``u'/π/page.html'``110 `full_path` ``u'/π/page.html?x=y'``111 `script_root` ``u'/myapplication'``112 `base_url` ``u'http://www.example.com/myapplication/π/page.html'``113 `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``114 `url_root` ``u'http://www.example.com/myapplication/'``115 ============= ======================================================116117 .. attribute:: is_xhr118119 ``True`` if the request was triggered via a JavaScript120 `XMLHttpRequest`. This only works with libraries that support the121 ``X-Requested-With`` header and set it to `XMLHttpRequest`.122 Libraries that do that are prototype, jQuery and Mochikit and123 probably some more.124125.. class:: request126127 To access incoming request data, you can use the global `request`128 object. Flask parses incoming request data for you and gives you129 access to it through that global object. Internally Flask makes130 sure that you always get the correct data for the active thread if you131 are in a multithreaded environment.132133 This is a proxy. See :ref:`notes-on-proxies` for more information.134135 The request object is an instance of a :class:`~werkzeug.wrappers.Request`136 subclass and provides all of the attributes Werkzeug defines. This137 just shows a quick overview of the most important ones.138139140Response Objects141----------------142143.. autoclass:: flask.Response144 :members: set_cookie, data, mimetype145146 .. attribute:: headers147148 A :class:`~werkzeug.datastructures.Headers` object representing the response headers.149150 .. attribute:: status151152 A string with a response status.153154 .. attribute:: status_code155156 The response status as integer.157158159Sessions160--------161162If you have the :attr:`Flask.secret_key` set you can use sessions in Flask163applications. A session basically makes it possible to remember164information from one request to another. The way Flask does this is by165using a signed cookie. So the user can look at the session contents, but166not modify it unless they know the secret key, so make sure to set that167to something complex and unguessable.168169To access the current session you can use the :class:`session` object:170171.. class:: session172173 The session object works pretty much like an ordinary dict, with the174 difference that it keeps track on modifications.175176 This is a proxy. See :ref:`notes-on-proxies` for more information.177178 The following attributes are interesting:179180 .. attribute:: new181182 ``True`` if the session is new, ``False`` otherwise.183184 .. attribute:: modified185186 ``True`` if the session object detected a modification. Be advised187 that modifications on mutable structures are not picked up188 automatically, in that situation you have to explicitly set the189 attribute to ``True`` yourself. Here an example::190191 # this change is not picked up because a mutable object (here192 # a list) is changed.193 session['objects'].append(42)194 # so mark it as modified yourself195 session.modified = True196197 .. attribute:: permanent198199 If set to ``True`` the session lives for200 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The201 default is 31 days. If set to ``False`` (which is the default) the202 session will be deleted when the user closes the browser.203204205Session Interface206-----------------207208.. versionadded:: 0.8209210The session interface provides a simple way to replace the session211implementation that Flask is using.212213.. currentmodule:: flask.sessions214215.. autoclass:: SessionInterface216 :members:217218.. autoclass:: SecureCookieSessionInterface219 :members:220221.. autoclass:: SecureCookieSession222 :members:223224.. autoclass:: NullSession225 :members:226227.. autoclass:: SessionMixin228 :members:229230.. autodata:: session_json_serializer231232 This object provides dumping and loading methods similar to simplejson233 but it also tags certain builtin Python objects that commonly appear in234 sessions. Currently the following extended values are supported in235 the JSON it dumps:236237 - :class:`~markupsafe.Markup` objects238 - :class:`~uuid.UUID` objects239 - :class:`~datetime.datetime` objects240 - :class:`tuple`\s241242.. admonition:: Notice243244 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer245 starting with Flask 0.8. Either catch this down yourself or use246 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the247 app which converts the result to an integer automatically.248249250Test Client251-----------252253.. currentmodule:: flask.testing254255.. autoclass:: FlaskClient256 :members:257258259Application Globals260-------------------261262.. currentmodule:: flask263264To share data that is valid for one request only from one function to265another, a global variable is not good enough because it would break in266threaded environments. Flask provides you with a special object that267ensures it is only valid for the active request and that will return268different values for each request. In a nutshell: it does the right269thing, like it does for :class:`request` and :class:`session`.270271.. data:: g272273 Just store on this whatever you want. For example a database274 connection or the user that is currently logged in.275276 Starting with Flask 0.10 this is stored on the application context and277 no longer on the request context which means it becomes available if278 only the application context is bound and not yet a request. This279 is especially useful when combined with the :ref:`faking-resources`280 pattern for testing.281282 Additionally as of 0.10 you can use the :meth:`get` method to283 get an attribute or ``None`` (or the second argument) if it's not set.284 These two usages are now equivalent::285286 user = getattr(flask.g, 'user', None)287 user = flask.g.get('user', None)288289 It's now also possible to use the ``in`` operator on it to see if an290 attribute is defined and it yields all keys on iteration.2911.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe
line 292why, one step back292 As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the sameMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 293–318why, one step back293 way you would use them on a dictionary.294295 This is a proxy. See :ref:`notes-on-proxies` for more information.296297298Useful Functions and Classes299----------------------------300301.. data:: current_app302303 Points to the application handling the request. This is useful for304 extensions that want to support multiple applications running side305 by side. This is powered by the application context and not by the306 request context, so you can change the value of this proxy by307 using the :meth:`~flask.Flask.app_context` method.308309 This is a proxy. See :ref:`notes-on-proxies` for more information.310311.. autofunction:: has_request_context312313.. autofunction:: copy_current_request_context314315.. autofunction:: has_app_context316317.. autofunction:: url_for318Use abort docs from WerkzeugMarkus Unterwaditzerbefore adoptiondcfdfc6
line 319why, one step back319.. autofunction:: abortMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 320–747why, one step back320321.. 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 by both 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 standard368library. 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.. admonition:: Auto-Sort JSON Keys389390 The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be391 set to false to stop Flask from auto-sorting keys. By default sorting392 is enabled and outside of the app context sorting is turned on.393394 Notice that disabling key sorting can cause issues when using content395 based HTTP caches and Python's hash randomization feature.396397.. autofunction:: jsonify398399.. autofunction:: dumps400401.. autofunction:: dump402403.. autofunction:: loads404405.. autofunction:: load406407.. autoclass:: JSONEncoder408 :members:409410.. autoclass:: JSONDecoder411 :members:412413Template Rendering414------------------415416.. currentmodule:: flask417418.. autofunction:: render_template419420.. autofunction:: render_template_string421422.. autofunction:: get_template_attribute423424Configuration425-------------426427.. autoclass:: Config428 :members:429430Extensions431----------432433.. data:: flask.ext434435 This module acts as redirect import module to Flask extensions. It was436 added in 0.8 as the canonical way to import Flask extensions and makes437 it possible for us to have more flexibility in how we distribute438 extensions.439440 If you want to use an extension named “Flask-Foo” you would import it441 from :data:`~flask.ext` as follows::442443 from flask.ext import foo444445 .. versionadded:: 0.8446447Stream Helpers448--------------449450.. autofunction:: stream_with_context451452Useful Internals453----------------454455.. autoclass:: flask.ctx.RequestContext456 :members:457458.. data:: _request_ctx_stack459460 The internal :class:`~werkzeug.local.LocalStack` that is used to implement461 all the context local objects used in Flask. This is a documented462 instance and can be used by extensions and application code but the463 use is discouraged in general.464465 The following attributes are always present on each layer of the466 stack:467468 `app`469 the active Flask application.470471 `url_adapter`472 the URL adapter that was used to match the request.473474 `request`475 the current request object.476477 `session`478 the active session object.479480 `g`481 an object with all the attributes of the :data:`flask.g` object.482483 `flashes`484 an internal cache for the flashed messages.485486 Example usage::487488 from flask import _request_ctx_stack489490 def get_session():491 ctx = _request_ctx_stack.top492 if ctx is not None:493 return ctx.session494495.. autoclass:: flask.ctx.AppContext496 :members:497498.. data:: _app_ctx_stack499500 Works similar to the request context but only binds the application.501 This is mainly there for extensions to store data.502503 .. versionadded:: 0.9504505.. autoclass:: flask.blueprints.BlueprintSetupState506 :members:507508.. _core-signals-list:509510Signals511-------512513.. versionadded:: 0.6514515.. data:: signals.signals_available516517 ``True`` if the signaling system is available. This is the case518 when `blinker`_ is installed.519520The following signals exist in Flask:521522.. data:: template_rendered523524 This signal is sent when a template was successfully rendered. The525 signal is invoked with the instance of the template as `template`526 and the context as dictionary (named `context`).527528 Example subscriber::529530 def log_template_renders(sender, template, context, **extra):531 sender.logger.debug('Rendering template "%s" with context %s',532 template.name or 'string template',533 context)534535 from flask import template_rendered536 template_rendered.connect(log_template_renders, app)537538.. data:: flask.before_render_template539 :noindex:540541 This signal is sent before template rendering process. The542 signal is invoked with the instance of the template as `template`543 and the context as dictionary (named `context`).544545 Example subscriber::546547 def log_template_renders(sender, template, context, **extra):548 sender.logger.debug('Rendering template "%s" with context %s',549 template.name or 'string template',550 context)551552 from flask import before_render_template553 before_render_template.connect(log_template_renders, app)554555.. data:: request_started556557 This signal is sent when the request context is set up, before558 any request processing happens. Because the request context is already559 bound, the subscriber can access the request with the standard global560 proxies such as :class:`~flask.request`.561562 Example subscriber::563564 def log_request(sender, **extra):565 sender.logger.debug('Request context is set up')566567 from flask import request_started568 request_started.connect(log_request, app)569570.. data:: request_finished571572 This signal is sent right before the response is sent to the client.573 It is passed the response to be sent named `response`.574575 Example subscriber::576577 def log_response(sender, response, **extra):578 sender.logger.debug('Request context is about to close down. '579 'Response: %s', response)580581 from flask import request_finished582 request_finished.connect(log_response, app)583584.. data:: got_request_exception585586 This signal is sent when an exception happens during request processing.587 It is sent *before* the standard exception handling kicks in and even588 in debug mode, where no exception handling happens. The exception589 itself is passed to the subscriber as `exception`.590591 Example subscriber::592593 def log_exception(sender, exception, **extra):594 sender.logger.debug('Got exception during processing: %s', exception)595596 from flask import got_request_exception597 got_request_exception.connect(log_exception, app)598599.. data:: request_tearing_down600601 This signal is sent when the request is tearing down. This is always602 called, even if an exception is caused. Currently functions listening603 to this signal are called after the regular teardown handlers, but this604 is not something you can rely on.605606 Example subscriber::607608 def close_db_connection(sender, **extra):609 session.close()610611 from flask import request_tearing_down612 request_tearing_down.connect(close_db_connection, app)613614 As of Flask 0.9, this will also be passed an `exc` keyword argument615 that has a reference to the exception that caused the teardown if616 there was one.617618.. data:: appcontext_tearing_down619620 This signal is sent when the app context is tearing down. This is always621 called, even if an exception is caused. Currently functions listening622 to this signal are called after the regular teardown handlers, but this623 is not something you can rely on.624625 Example subscriber::626627 def close_db_connection(sender, **extra):628 session.close()629630 from flask import appcontext_tearing_down631 appcontext_tearing_down.connect(close_db_connection, app)632633 This will also be passed an `exc` keyword argument that has a reference634 to the exception that caused the teardown if there was one.635636.. data:: appcontext_pushed637638 This signal is sent when an application context is pushed. The sender639 is the application. This is usually useful for unittests in order to640 temporarily hook in information. For instance it can be used to641 set a resource early onto the `g` object.642643 Example usage::644645 from contextlib import contextmanager646 from flask import appcontext_pushed647648 @contextmanager649 def user_set(app, user):650 def handler(sender, **kwargs):651 g.user = user652 with appcontext_pushed.connected_to(handler, app):653 yield654655 And in the testcode::656657 def test_user_me(self):658 with user_set(app, 'john'):659 c = app.test_client()660 resp = c.get('/users/me')661 assert resp.data == 'username=john'662663 .. versionadded:: 0.10664665.. data:: appcontext_popped666667 This signal is sent when an application context is popped. The sender668 is the application. This usually falls in line with the669 :data:`appcontext_tearing_down` signal.670671 .. versionadded:: 0.10672673674.. data:: message_flashed675676 This signal is sent when the application is flashing a message. The677 messages is sent as `message` keyword argument and the category as678 `category`.679680 Example subscriber::681682 recorded = []683 def record(sender, message, category, **extra):684 recorded.append((message, category))685686 from flask import message_flashed687 message_flashed.connect(record, app)688689 .. versionadded:: 0.10690691.. class:: signals.Namespace692693 An alias for :class:`blinker.base.Namespace` if blinker is available,694 otherwise a dummy class that creates fake signals. This class is695 available for Flask extensions that want to provide the same fallback696 system as Flask itself.697698 .. method:: signal(name, doc=None)699700 Creates a new signal for this namespace if blinker is available,701 otherwise returns a fake signal that has a send method that will702 do nothing but will fail with a :exc:`RuntimeError` for all other703 operations, including connecting.704705706.. _blinker: https://pypi.python.org/pypi/blinker707708709Class-Based Views710-----------------711712.. versionadded:: 0.7713714.. currentmodule:: None715716.. autoclass:: flask.views.View717 :members:718719.. autoclass:: flask.views.MethodView720 :members:721722.. _url-route-registrations:723724URL Route Registrations725-----------------------726727Generally there are three ways to define rules for the routing system:7287291. You can use the :meth:`flask.Flask.route` decorator.7302. You can use the :meth:`flask.Flask.add_url_rule` function.7313. You can directly access the underlying Werkzeug routing system732 which is exposed as :attr:`flask.Flask.url_map`.733734Variable parts in the route can be specified with angular brackets735(``/user/<username>``). By default a variable part in the URL accepts any736string without a slash however a different converter can be specified as737well by using ``<converter:name>``.738739Variable parts are passed to the view function as keyword arguments.740741The following converters are available:742743=========== ===============================================744`string` accepts any text without a slash (the default)745`int` accepts integers746`float` like `int` but for floating point values747`path` like the default but also accepts slashesAdd two missing converters for flask in the docslord63before adoptione0a8fd3
lines 748–749why, one step back748`any` matches one of the items provided749`uuid` accepts UUID stringsMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
lines 750–891why, one step back750=========== ===============================================751752Custom converters can be defined using :attr:`flask.Flask.url_map`.753754Here are some examples::755756 @app.route('/')757 def index():758 pass759760 @app.route('/<username>')761 def show_user(username):762 pass763764 @app.route('/post/<int:post_id>')765 def show_post(post_id):766 pass767768An important detail to keep in mind is how Flask deals with trailing769slashes. The idea is to keep each URL unique so the following rules770apply:7717721. If a rule ends with a slash and is requested without a slash by the773 user, the user is automatically redirected to the same page with a774 trailing slash attached.7752. If a rule does not end with a trailing slash and the user requests the776 page with a trailing slash, a 404 not found is raised.777778This is consistent with how web servers deal with static files. This779also makes it possible to use relative link targets safely.780781You can also define multiple rules for the same function. They have to be782unique however. Defaults can also be specified. Here for example is a783definition for a URL that accepts an optional page::784785 @app.route('/users/', defaults={'page': 1})786 @app.route('/users/page/<int:page>')787 def show_users(page):788 pass789790This specifies that ``/users/`` will be the URL for page one and791``/users/page/N`` will be the URL for page `N`.792793Here are the parameters that :meth:`~flask.Flask.route` and794:meth:`~flask.Flask.add_url_rule` accept. The only difference is that795with the route parameter the view function is defined with the decorator796instead of the `view_func` parameter.797798=============== ==========================================================799`rule` the URL rule as string800`endpoint` the endpoint for the registered URL rule. Flask itself801 assumes that the name of the view function is the name802 of the endpoint if not explicitly stated.803`view_func` the function to call when serving a request to the804 provided endpoint. If this is not provided one can805 specify the function later by storing it in the806 :attr:`~flask.Flask.view_functions` dictionary with the807 endpoint as key.808`defaults` A dictionary with defaults for this rule. See the809 example above for how defaults work.810`subdomain` specifies the rule for the subdomain in case subdomain811 matching is in use. If not specified the default812 subdomain is assumed.813`**options` the options to be forwarded to the underlying814 :class:`~werkzeug.routing.Rule` object. A change to815 Werkzeug is handling of method options. methods is a list816 of methods this rule should be limited to (``GET``, ``POST``817 etc.). By default a rule just listens for ``GET`` (and818 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is819 implicitly added and handled by the standard request820 handling. They have to be specified as keyword arguments.821=============== ==========================================================822823.. _view-func-options:824825View Function Options826---------------------827828For internal usage the view functions can have some attributes attached to829customize behavior the view function would normally not have control over.830The following attributes can be provided optionally to either override831some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:832833- `__name__`: The name of a function is by default used as endpoint. If834 endpoint is provided explicitly this value is used. Additionally this835 will be prefixed with the name of the blueprint by default which836 cannot be customized from the function itself.837838- `methods`: If methods are not provided when the URL rule is added,839 Flask will look on the view function object itself if a `methods`840 attribute exists. If it does, it will pull the information for the841 methods from there.842843- `provide_automatic_options`: if this attribute is set Flask will844 either force enable or disable the automatic implementation of the845 HTTP ``OPTIONS`` response. This can be useful when working with846 decorators that want to customize the ``OPTIONS`` response on a per-view847 basis.848849- `required_methods`: if this attribute is set, Flask will always add850 these methods when registering a URL rule even if the methods were851 explicitly overridden in the ``route()`` call.852853Full example::854855 def index():856 if request.method == 'OPTIONS':857 # custom options handling here858 ...859 return 'Hello World!'860 index.provide_automatic_options = False861 index.methods = ['GET', 'OPTIONS']862863 app.add_url_rule('/', index)864865.. versionadded:: 0.8866 The `provide_automatic_options` functionality was added.867868Command Line Interface869----------------------870871.. currentmodule:: flask.cli872873.. autoclass:: FlaskGroup874 :members:875876.. autoclass:: AppGroup877 :members:878879.. autoclass:: ScriptInfo880 :members:881882.. autofunction:: with_appcontext883884.. autofunction:: pass_script_info885886 Marks a function so that an instance of :class:`ScriptInfo` is passed887 as first argument to the click callback.888889.. autodata:: run_command890891.. autodata:: shell_command