api.rst
This file
Path
docs/api.rst
902 lines · 27.3 KiB
Last changed by
Merge pull request #1509 from ThiefMaster/appctxglobals-candyMarkus Unterwaditzerbefore adoption3747487
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:: 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.291292 As of 1.0 you can use :meth:`pop` and :meth:`setdefault` in the same293 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_for318319.. function:: abort(code)320321 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given322 status code. For example to abort request handling with a page not323 found exception, you would call ``abort(404)``.324325 :param code: the HTTP error code.326327.. autofunction:: redirect328329.. autofunction:: make_response330331.. autofunction:: after_this_request332333.. autofunction:: send_file334335.. autofunction:: send_from_directory336337.. autofunction:: safe_join338339.. autofunction:: escape340341.. autoclass:: Markup342 :members: escape, unescape, striptags343344Message Flashing345----------------346347.. autofunction:: flash348349.. autofunction:: get_flashed_messages350351JSON Support352------------353354.. module:: flask.json355356Flask uses ``simplejson`` for the JSON implementation. Since simplejson357is provided by both the standard library as well as extension, Flask will358try simplejson first and then fall back to the stdlib json module. On top359of that it will delegate access to the current application's JSON encoders360and decoders for easier customization.361362So for starters instead of doing::363364 try:365 import simplejson as json366 except ImportError:367 import json368369You can instead just do this::370371 from flask import json372373For usage examples, read the :mod:`json` documentation in the standard374library. The following extensions are by default applied to the stdlib's375JSON module:3763771. ``datetime`` objects are serialized as :rfc:`822` strings.3782. Any object with an ``__html__`` method (like :class:`~flask.Markup`)379 will have that method called and then the return value is serialized380 as string.381382The :func:`~htmlsafe_dumps` function of this json module is also available383as filter called ``|tojson`` in Jinja2. Note that inside ``script``384tags no escaping must take place, so make sure to disable escaping385with ``|safe`` if you intend to use it inside ``script`` tags unless386you are using Flask 0.10 which implies that:387388.. sourcecode:: html+jinja389390 <script type=text/javascript>391 doSomethingWith({{ user.username|tojson|safe }});392 </script>393394.. admonition:: Auto-Sort JSON Keys395396 The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be397 set to false to stop Flask from auto-sorting keys. By default sorting398 is enabled and outside of the app context sorting is turned on.399400 Notice that disabling key sorting can cause issues when using content401 based HTTP caches and Python's hash randomization feature.402403.. autofunction:: jsonify404405.. autofunction:: dumps406407.. autofunction:: dump408409.. autofunction:: loads410411.. autofunction:: load412413.. autoclass:: JSONEncoder414 :members:415416.. autoclass:: JSONDecoder417 :members:418419Template Rendering420------------------421422.. currentmodule:: flask423424.. autofunction:: render_template425426.. autofunction:: render_template_string427428.. autofunction:: get_template_attribute429430Configuration431-------------432433.. autoclass:: Config434 :members:435436Extensions437----------438439.. data:: flask.ext440441 This module acts as redirect import module to Flask extensions. It was442 added in 0.8 as the canonical way to import Flask extensions and makes443 it possible for us to have more flexibility in how we distribute444 extensions.445446 If you want to use an extension named “Flask-Foo” you would import it447 from :data:`~flask.ext` as follows::448449 from flask.ext import foo450451 .. versionadded:: 0.8452453Stream Helpers454--------------455456.. autofunction:: stream_with_context457458Useful Internals459----------------460461.. autoclass:: flask.ctx.RequestContext462 :members:463464.. data:: _request_ctx_stack465466 The internal :class:`~werkzeug.local.LocalStack` that is used to implement467 all the context local objects used in Flask. This is a documented468 instance and can be used by extensions and application code but the469 use is discouraged in general.470471 The following attributes are always present on each layer of the472 stack:473474 `app`475 the active Flask application.476477 `url_adapter`478 the URL adapter that was used to match the request.479480 `request`481 the current request object.482483 `session`484 the active session object.485486 `g`487 an object with all the attributes of the :data:`flask.g` object.488489 `flashes`490 an internal cache for the flashed messages.491492 Example usage::493494 from flask import _request_ctx_stack495496 def get_session():497 ctx = _request_ctx_stack.top498 if ctx is not None:499 return ctx.session500501.. autoclass:: flask.ctx.AppContext502 :members:503504.. data:: _app_ctx_stack505506 Works similar to the request context but only binds the application.507 This is mainly there for extensions to store data.508509 .. versionadded:: 0.9510511.. autoclass:: flask.blueprints.BlueprintSetupState512 :members:513514.. _core-signals-list:515516Signals517-------518519.. versionadded:: 0.6520521.. data:: signals.signals_available522523 ``True`` if the signaling system is available. This is the case524 when `blinker`_ is installed.525526The following signals exist in Flask:527528.. data:: template_rendered529530 This signal is sent when a template was successfully rendered. The531 signal is invoked with the instance of the template as `template`532 and the context as dictionary (named `context`).533534 Example subscriber::535536 def log_template_renders(sender, template, context, **extra):537 sender.logger.debug('Rendering template "%s" with context %s',538 template.name or 'string template',539 context)540541 from flask import template_rendered542 template_rendered.connect(log_template_renders, app)543544.. data:: flask.before_render_template545 :noindex:546547 This signal is sent before template rendering process. The548 signal is invoked with the instance of the template as `template`549 and the context as dictionary (named `context`).550551 Example subscriber::552553 def log_template_renders(sender, template, context, **extra):554 sender.logger.debug('Rendering template "%s" with context %s',555 template.name or 'string template',556 context)557558 from flask import before_render_template559 before_render_template.connect(log_template_renders, app)560561.. data:: request_started562563 This signal is sent when the request context is set up, before564 any request processing happens. Because the request context is already565 bound, the subscriber can access the request with the standard global566 proxies such as :class:`~flask.request`.567568 Example subscriber::569570 def log_request(sender, **extra):571 sender.logger.debug('Request context is set up')572573 from flask import request_started574 request_started.connect(log_request, app)575576.. data:: request_finished577578 This signal is sent right before the response is sent to the client.579 It is passed the response to be sent named `response`.580581 Example subscriber::582583 def log_response(sender, response, **extra):584 sender.logger.debug('Request context is about to close down. '585 'Response: %s', response)586587 from flask import request_finished588 request_finished.connect(log_response, app)589590.. data:: got_request_exception591592 This signal is sent when an exception happens during request processing.593 It is sent *before* the standard exception handling kicks in and even594 in debug mode, where no exception handling happens. The exception595 itself is passed to the subscriber as `exception`.596597 Example subscriber::598599 def log_exception(sender, exception, **extra):600 sender.logger.debug('Got exception during processing: %s', exception)601602 from flask import got_request_exception603 got_request_exception.connect(log_exception, app)604605.. data:: request_tearing_down606607 This signal is sent when the request is tearing down. This is always608 called, even if an exception is caused. Currently functions listening609 to this signal are called after the regular teardown handlers, but this610 is not something you can rely on.611612 Example subscriber::613614 def close_db_connection(sender, **extra):615 session.close()616617 from flask import request_tearing_down618 request_tearing_down.connect(close_db_connection, app)619620 As of Flask 0.9, this will also be passed an `exc` keyword argument621 that has a reference to the exception that caused the teardown if622 there was one.623624.. data:: appcontext_tearing_down625626 This signal is sent when the app context is tearing down. This is always627 called, even if an exception is caused. Currently functions listening628 to this signal are called after the regular teardown handlers, but this629 is not something you can rely on.630631 Example subscriber::632633 def close_db_connection(sender, **extra):634 session.close()635636 from flask import appcontext_tearing_down637 appcontext_tearing_down.connect(close_db_connection, app)638639 This will also be passed an `exc` keyword argument that has a reference640 to the exception that caused the teardown if there was one.641642.. data:: appcontext_pushed643644 This signal is sent when an application context is pushed. The sender645 is the application. This is usually useful for unittests in order to646 temporarily hook in information. For instance it can be used to647 set a resource early onto the `g` object.648649 Example usage::650651 from contextlib import contextmanager652 from flask import appcontext_pushed653654 @contextmanager655 def user_set(app, user):656 def handler(sender, **kwargs):657 g.user = user658 with appcontext_pushed.connected_to(handler, app):659 yield660661 And in the testcode::662663 def test_user_me(self):664 with user_set(app, 'john'):665 c = app.test_client()666 resp = c.get('/users/me')667 assert resp.data == 'username=john'668669 .. versionadded:: 0.10670671.. data:: appcontext_popped672673 This signal is sent when an application context is popped. The sender674 is the application. This usually falls in line with the675 :data:`appcontext_tearing_down` signal.676677 .. versionadded:: 0.10678679680.. data:: message_flashed681682 This signal is sent when the application is flashing a message. The683 messages is sent as `message` keyword argument and the category as684 `category`.685686 Example subscriber::687688 recorded = []689 def record(sender, message, category, **extra):690 recorded.append((message, category))691692 from flask import message_flashed693 message_flashed.connect(record, app)694695 .. versionadded:: 0.10696697.. class:: signals.Namespace698699 An alias for :class:`blinker.base.Namespace` if blinker is available,700 otherwise a dummy class that creates fake signals. This class is701 available for Flask extensions that want to provide the same fallback702 system as Flask itself.703704 .. method:: signal(name, doc=None)705706 Creates a new signal for this namespace if blinker is available,707 otherwise returns a fake signal that has a send method that will708 do nothing but will fail with a :exc:`RuntimeError` for all other709 operations, including connecting.710711712.. _blinker: https://pypi.python.org/pypi/blinker713714715Class-Based Views716-----------------717718.. versionadded:: 0.7719720.. currentmodule:: None721722.. autoclass:: flask.views.View723 :members:724725.. autoclass:: flask.views.MethodView726 :members:727728.. _url-route-registrations:729730URL Route Registrations731-----------------------732733Generally there are three ways to define rules for the routing system:7347351. You can use the :meth:`flask.Flask.route` decorator.7362. You can use the :meth:`flask.Flask.add_url_rule` function.7373. You can directly access the underlying Werkzeug routing system738 which is exposed as :attr:`flask.Flask.url_map`.739740Variable parts in the route can be specified with angular brackets741(``/user/<username>``). By default a variable part in the URL accepts any742string without a slash however a different converter can be specified as743well by using ``<converter:name>``.744745Variable parts are passed to the view function as keyword arguments.746747The following converters are available:748749=========== ===============================================750`string` accepts any text without a slash (the default)751`int` accepts integers752`float` like `int` but for floating point values753`path` like the default but also accepts slashes754=========== ===============================================755756Custom converters can be defined using :attr:`flask.Flask.url_map`.757758Here are some examples::759760 @app.route('/')761 def index():762 pass763764 @app.route('/<username>')765 def show_user(username):766 pass767768 @app.route('/post/<int:post_id>')769 def show_post(post_id):770 pass771772An important detail to keep in mind is how Flask deals with trailing773slashes. The idea is to keep each URL unique so the following rules774apply:7757761. If a rule ends with a slash and is requested without a slash by the777 user, the user is automatically redirected to the same page with a778 trailing slash attached.7792. If a rule does not end with a trailing slash and the user requests the780 page with a trailing slash, a 404 not found is raised.781782This is consistent with how web servers deal with static files. This783also makes it possible to use relative link targets safely.784785You can also define multiple rules for the same function. They have to be786unique however. Defaults can also be specified. Here for example is a787definition for a URL that accepts an optional page::788789 @app.route('/users/', defaults={'page': 1})790 @app.route('/users/page/<int:page>')791 def show_users(page):792 pass793794This specifies that ``/users/`` will be the URL for page one and795``/users/page/N`` will be the URL for page `N`.796797Here are the parameters that :meth:`~flask.Flask.route` and798:meth:`~flask.Flask.add_url_rule` accept. The only difference is that799with the route parameter the view function is defined with the decorator800instead of the `view_func` parameter.801802=============== ==========================================================803`rule` the URL rule as string804`endpoint` the endpoint for the registered URL rule. Flask itself805 assumes that the name of the view function is the name806 of the endpoint if not explicitly stated.807`view_func` the function to call when serving a request to the808 provided endpoint. If this is not provided one can809 specify the function later by storing it in the810 :attr:`~flask.Flask.view_functions` dictionary with the811 endpoint as key.812`defaults` A dictionary with defaults for this rule. See the813 example above for how defaults work.814`subdomain` specifies the rule for the subdomain in case subdomain815 matching is in use. If not specified the default816 subdomain is assumed.817`**options` the options to be forwarded to the underlying818 :class:`~werkzeug.routing.Rule` object. A change to819 Werkzeug is handling of method options. methods is a list820 of methods this rule should be limited to (``GET``, ``POST``821 etc.). By default a rule just listens for ``GET`` (and822 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is823 implicitly added and handled by the standard request824 handling. They have to be specified as keyword arguments.825=============== ==========================================================826827.. _view-func-options:828829View Function Options830---------------------831832For internal usage the view functions can have some attributes attached to833customize behavior the view function would normally not have control over.834The following attributes can be provided optionally to either override835some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:836837- `__name__`: The name of a function is by default used as endpoint. If838 endpoint is provided explicitly this value is used. Additionally this839 will be prefixed with the name of the blueprint by default which840 cannot be customized from the function itself.841842- `methods`: If methods are not provided when the URL rule is added,843 Flask will look on the view function object itself if a `methods`844 attribute exists. If it does, it will pull the information for the845 methods from there.846847- `provide_automatic_options`: if this attribute is set Flask will848 either force enable or disable the automatic implementation of the849 HTTP ``OPTIONS`` response. This can be useful when working with850 decorators that want to customize the ``OPTIONS`` response on a per-view851 basis.852853- `required_methods`: if this attribute is set, Flask will always add854 these methods when registering a URL rule even if the methods were855 explicitly overridden in the ``route()`` call.856857Full example::858859 def index():860 if request.method == 'OPTIONS':861 # custom options handling here862 ...863 return 'Hello World!'864 index.provide_automatic_options = False865 index.methods = ['GET', 'OPTIONS']866867 app.add_url_rule('/', index)868869.. versionadded:: 0.8870 The `provide_automatic_options` functionality was added.871872Command Line Interface873----------------------874875.. currentmodule:: flask.cli876877.. autoclass:: FlaskGroup878 :members:879880.. autoclass:: AppGroup881 :members:882883.. autoclass:: ScriptInfo884 :members:885886.. autofunction:: with_appcontext887888.. autofunction:: pass_script_info889890 Marks a function so that an instance of :class:`ScriptInfo` is passed891 as first argument to the click callback.892893.. autofunction:: script_info_option894895 A special decorator that informs a click callback to be passed the896 script info object as first argument. This is normally not useful897 unless you implement very special commands like the run command which898 does not want the application to be loaded yet.899900.. autodata:: run_command901902.. autodata:: shell_command