api.rst
This file
Path
docs/api.rst
882 lines · 26.6 KiB
Last changed by
Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a
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 This is a proxy. See :ref:`notes-on-proxies` for more information.293294295Useful Functions and Classes296----------------------------297298.. data:: current_app299300 Points to the application handling the request. This is useful for301 extensions that want to support multiple applications running side302 by side. This is powered by the application context and not by the303 request context, so you can change the value of this proxy by304 using the :meth:`~flask.Flask.app_context` method.305306 This is a proxy. See :ref:`notes-on-proxies` for more information.307308.. autofunction:: has_request_context309310.. autofunction:: copy_current_request_context311312.. autofunction:: has_app_context313314.. autofunction:: url_for315316.. function:: abort(code)317318 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given319 status code. For example to abort request handling with a page not320 found exception, you would call ``abort(404)``.321322 :param code: the HTTP error code.323324.. autofunction:: redirect325326.. autofunction:: make_response327328.. autofunction:: after_this_request329330.. autofunction:: send_file331332.. autofunction:: send_from_directory333334.. autofunction:: safe_join335336.. autofunction:: escape337338.. autoclass:: Markup339 :members: escape, unescape, striptags340341Message Flashing342----------------343344.. autofunction:: flash345346.. autofunction:: get_flashed_messages347348JSON Support349------------350351.. module:: flask.json352353Flask uses ``simplejson`` for the JSON implementation. Since simplejson354is provided by both the standard library as well as extension, Flask will355try simplejson first and then fall back to the stdlib json module. On top356of that it will delegate access to the current application's JSON encoders357and decoders for easier customization.358359So for starters instead of doing::360361 try:362 import simplejson as json363 except ImportError:364 import json365366You can instead just do this::367368 from flask import json369370For usage examples, read the :mod:`json` documentation in the standard371library. The following extensions are by default applied to the stdlib's372JSON module:3733741. ``datetime`` objects are serialized as :rfc:`822` strings.3752. Any object with an ``__html__`` method (like :class:`~flask.Markup`)376 will have that method called and then the return value is serialized377 as string.378379The :func:`~htmlsafe_dumps` function of this json module is also available380as filter called ``|tojson`` in Jinja2. Note that inside ``script``381tags no escaping must take place, so make sure to disable escaping382with ``|safe`` if you intend to use it inside ``script`` tags unless383you are using Flask 0.10 which implies that:384385.. sourcecode:: html+jinja386387 <script type=text/javascript>388 doSomethingWith({{ user.username|tojson|safe }});389 </script>390391.. admonition:: Auto-Sort JSON Keys392393 The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be394 set to false to stop Flask from auto-sorting keys. By default sorting395 is enabled and outside of the app context sorting is turned on.396397 Notice that disabling key sorting can cause issues when using content398 based HTTP caches and Python's hash randomization feature.399400.. autofunction:: jsonify401402.. autofunction:: dumps403404.. autofunction:: dump405406.. autofunction:: loads407408.. autofunction:: load409410.. autoclass:: JSONEncoder411 :members:412413.. autoclass:: JSONDecoder414 :members:415416Template Rendering417------------------418419.. currentmodule:: flask420421.. autofunction:: render_template422423.. autofunction:: render_template_string424425.. autofunction:: get_template_attribute426427Configuration428-------------429430.. autoclass:: Config431 :members:432433Extensions434----------435436.. data:: flask.ext437438 This module acts as redirect import module to Flask extensions. It was439 added in 0.8 as the canonical way to import Flask extensions and makes440 it possible for us to have more flexibility in how we distribute441 extensions.442443 If you want to use an extension named “Flask-Foo” you would import it444 from :data:`~flask.ext` as follows::445446 from flask.ext import foo447448 .. versionadded:: 0.8449450Stream Helpers451--------------452453.. autofunction:: stream_with_context454455Useful Internals456----------------457458.. autoclass:: flask.ctx.RequestContext459 :members:460461.. data:: _request_ctx_stack462463 The internal :class:`~werkzeug.local.LocalStack` that is used to implement464 all the context local objects used in Flask. This is a documented465 instance and can be used by extensions and application code but the466 use is discouraged in general.467468 The following attributes are always present on each layer of the469 stack:470471 `app`472 the active Flask application.473474 `url_adapter`475 the URL adapter that was used to match the request.476477 `request`478 the current request object.479480 `session`481 the active session object.482483 `g`484 an object with all the attributes of the :data:`flask.g` object.485486 `flashes`487 an internal cache for the flashed messages.488489 Example usage::490491 from flask import _request_ctx_stack492493 def get_session():494 ctx = _request_ctx_stack.top495 if ctx is not None:496 return ctx.session497498.. autoclass:: flask.ctx.AppContext499 :members:500501.. data:: _app_ctx_stack502503 Works similar to the request context but only binds the application.504 This is mainly there for extensions to store data.505506 .. versionadded:: 0.9507508.. autoclass:: flask.blueprints.BlueprintSetupState509 :members:510511.. _core-signals-list:512513Signals514-------515516.. versionadded:: 0.6517518.. data:: signals.signals_available519520 ``True`` if the signaling system is available. This is the case521 when `blinker`_ is installed.522523The following signals exist in Flask:524525.. data:: template_rendered526527 This signal is sent when a template was successfully rendered. The528 signal is invoked with the instance of the template as `template`529 and the context as dictionary (named `context`).530531 Example subscriber::532533 def log_template_renders(sender, template, context, **extra):534 sender.logger.debug('Rendering template "%s" with context %s',535 template.name or 'string template',536 context)537538 from flask import template_rendered539 template_rendered.connect(log_template_renders, app)540541.. data:: request_started542543 This signal is sent when the request context is set up, before544 any request processing happens. Because the request context is already545 bound, the subscriber can access the request with the standard global546 proxies such as :class:`~flask.request`.547548 Example subscriber::549550 def log_request(sender, **extra):551 sender.logger.debug('Request context is set up')552553 from flask import request_started554 request_started.connect(log_request, app)555556.. data:: request_finished557558 This signal is sent right before the response is sent to the client.559 It is passed the response to be sent named `response`.560561 Example subscriber::562563 def log_response(sender, response, **extra):564 sender.logger.debug('Request context is about to close down. '565 'Response: %s', response)566567 from flask import request_finished568 request_finished.connect(log_response, app)569570.. data:: got_request_exception571572 This signal is sent when an exception happens during request processing.573 It is sent *before* the standard exception handling kicks in and even574 in debug mode, where no exception handling happens. The exception575 itself is passed to the subscriber as `exception`.576577 Example subscriber::578579 def log_exception(sender, exception, **extra):580 sender.logger.debug('Got exception during processing: %s', exception)581582 from flask import got_request_exception583 got_request_exception.connect(log_exception, app)584585.. data:: request_tearing_down586587 This signal is sent when the request is tearing down. This is always588 called, even if an exception is caused. Currently functions listening589 to this signal are called after the regular teardown handlers, but this590 is not something you can rely on.591592 Example subscriber::593594 def close_db_connection(sender, **extra):595 session.close()596597 from flask import request_tearing_down598 request_tearing_down.connect(close_db_connection, app)599600 As of Flask 0.9, this will also be passed an `exc` keyword argument601 that has a reference to the exception that caused the teardown if602 there was one.603604.. data:: appcontext_tearing_down605606 This signal is sent when the app context is tearing down. This is always607 called, even if an exception is caused. Currently functions listening608 to this signal are called after the regular teardown handlers, but this609 is not something you can rely on.610611 Example subscriber::612613 def close_db_connection(sender, **extra):614 session.close()615616 from flask import appcontext_tearing_down617 appcontext_tearing_down.connect(close_db_connection, app)618619 This will also be passed an `exc` keyword argument that has a reference620 to the exception that caused the teardown if there was one.621622.. data:: appcontext_pushed623624 This signal is sent when an application context is pushed. The sender625 is the application. This is usually useful for unittests in order to626 temporarily hook in information. For instance it can be used to627 set a resource early onto the `g` object.628629 Example usage::630631 from contextlib import contextmanager632 from flask import appcontext_pushed633634 @contextmanager635 def user_set(app, user):636 def handler(sender, **kwargs):637 g.user = user638 with appcontext_pushed.connected_to(handler, app):639 yield640641 And in the testcode::642643 def test_user_me(self):644 with user_set(app, 'john'):645 c = app.test_client()646 resp = c.get('/users/me')647 assert resp.data == 'username=john'648649 .. versionadded:: 0.10650651.. data:: appcontext_popped652653 This signal is sent when an application context is popped. The sender654 is the application. This usually falls in line with the655 :data:`appcontext_tearing_down` signal.656657 .. versionadded:: 0.10658659660.. data:: message_flashed661662 This signal is sent when the application is flashing a message. The663 messages is sent as `message` keyword argument and the category as664 `category`.665666 Example subscriber::667668 recorded = []669 def record(sender, message, category, **extra):670 recorded.append((message, category))671672 from flask import message_flashed673 message_flashed.connect(record, app)674675 .. versionadded:: 0.10676677.. class:: signals.Namespace678679 An alias for :class:`blinker.base.Namespace` if blinker is available,680 otherwise a dummy class that creates fake signals. This class is681 available for Flask extensions that want to provide the same fallback682 system as Flask itself.683684 .. method:: signal(name, doc=None)685686 Creates a new signal for this namespace if blinker is available,687 otherwise returns a fake signal that has a send method that will688 do nothing but will fail with a :exc:`RuntimeError` for all other689 operations, including connecting.690691692.. _blinker: https://pypi.python.org/pypi/blinker693694695Class-Based Views696-----------------697698.. versionadded:: 0.7699700.. currentmodule:: None701702.. autoclass:: flask.views.View703 :members:704705.. autoclass:: flask.views.MethodView706 :members:707708.. _url-route-registrations:709710URL Route Registrations711-----------------------712713Generally there are three ways to define rules for the routing system:7147151. You can use the :meth:`flask.Flask.route` decorator.7162. You can use the :meth:`flask.Flask.add_url_rule` function.7173. You can directly access the underlying Werkzeug routing system718 which is exposed as :attr:`flask.Flask.url_map`.719720Variable parts in the route can be specified with angular brackets721(``/user/<username>``). By default a variable part in the URL accepts any722string without a slash however a different converter can be specified as723well by using ``<converter:name>``.724725Variable parts are passed to the view function as keyword arguments.726727The following converters are available:728729=========== ===============================================730`string` accepts any text without a slash (the default)731`int` accepts integers732`float` like `int` but for floating point values733`path` like the default but also accepts slashes734=========== ===============================================735736Custom converters can be defined using :attr:`flask.Flask.url_map`.737738Here are some examples::739740 @app.route('/')741 def index():742 pass743744 @app.route('/<username>')745 def show_user(username):746 pass747748 @app.route('/post/<int:post_id>')749 def show_post(post_id):750 pass751752An important detail to keep in mind is how Flask deals with trailing753slashes. The idea is to keep each URL unique so the following rules754apply:7557561. If a rule ends with a slash and is requested without a slash by the757 user, the user is automatically redirected to the same page with a758 trailing slash attached.7592. If a rule does not end with a trailing slash and the user requests the760 page with a trailing slash, a 404 not found is raised.761762This is consistent with how web servers deal with static files. This763also makes it possible to use relative link targets safely.764765You can also define multiple rules for the same function. They have to be766unique however. Defaults can also be specified. Here for example is a767definition for a URL that accepts an optional page::768769 @app.route('/users/', defaults={'page': 1})770 @app.route('/users/page/<int:page>')771 def show_users(page):772 pass773774This specifies that ``/users/`` will be the URL for page one and775``/users/page/N`` will be the URL for page `N`.776777Here are the parameters that :meth:`~flask.Flask.route` and778:meth:`~flask.Flask.add_url_rule` accept. The only difference is that779with the route parameter the view function is defined with the decorator780instead of the `view_func` parameter.781782=============== ==========================================================783`rule` the URL rule as string784`endpoint` the endpoint for the registered URL rule. Flask itself785 assumes that the name of the view function is the name786 of the endpoint if not explicitly stated.787`view_func` the function to call when serving a request to the788 provided endpoint. If this is not provided one can789 specify the function later by storing it in the790 :attr:`~flask.Flask.view_functions` dictionary with the791 endpoint as key.792`defaults` A dictionary with defaults for this rule. See the793 example above for how defaults work.794`subdomain` specifies the rule for the subdomain in case subdomain795 matching is in use. If not specified the default796 subdomain is assumed.797`**options` the options to be forwarded to the underlying798 :class:`~werkzeug.routing.Rule` object. A change to799 Werkzeug is handling of method options. methods is a list800 of methods this rule should be limited to (``GET``, ``POST``801 etc.). By default a rule just listens for ``GET`` (and802 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is803 implicitly added and handled by the standard request804 handling. They have to be specified as keyword arguments.805=============== ==========================================================806807.. _view-func-options:808809View Function Options810---------------------811812For internal usage the view functions can have some attributes attached to813customize behavior the view function would normally not have control over.814The following attributes can be provided optionally to either override815some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:816817- `__name__`: The name of a function is by default used as endpoint. If818 endpoint is provided explicitly this value is used. Additionally this819 will be prefixed with the name of the blueprint by default which820 cannot be customized from the function itself.821822- `methods`: If methods are not provided when the URL rule is added,823 Flask will look on the view function object itself if a `methods`824 attribute exists. If it does, it will pull the information for the825 methods from there.826827- `provide_automatic_options`: if this attribute is set Flask will828 either force enable or disable the automatic implementation of the829 HTTP ``OPTIONS`` response. This can be useful when working with830 decorators that want to customize the ``OPTIONS`` response on a per-view831 basis.832833- `required_methods`: if this attribute is set, Flask will always add834 these methods when registering a URL rule even if the methods were835 explicitly overridden in the ``route()`` call.836837Full example::838839 def index():840 if request.method == 'OPTIONS':841 # custom options handling here842 ...843 return 'Hello World!'844 index.provide_automatic_options = False845 index.methods = ['GET', 'OPTIONS']846847 app.add_url_rule('/', index)848849.. versionadded:: 0.8850 The `provide_automatic_options` functionality was added.851852Command Line Interface853----------------------854855.. currentmodule:: flask.cli856857.. autoclass:: FlaskGroup858 :members:859860.. autoclass:: AppGroup861 :members:862863.. autoclass:: ScriptInfo864 :members:865866.. autofunction:: with_appcontext867868.. autofunction:: pass_script_info869870 Marks a function so that an instance of :class:`ScriptInfo` is passed871 as first argument to the click callback.872873.. autofunction:: script_info_option874875 A special decorator that informs a click callback to be passed the876 script info object as first argument. This is normally not useful877 unless you implement very special commands like the run command which878 does not want the application to be loaded yet.879880.. autodata:: run_command881882.. autodata:: shell_command