api.rst
This file
Path
docs/api.rst
698 lines · 20.9 KiB
Last changed by
flask.g is now on the app context and not the request contextArmin Ronacherbefore adoption1949c4a
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.. admonition:: Notice228229 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer230 starting with Flask 0.8. Either catch this down yourself or use231 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the232 app which converts the result to an integer automatically.233234235Test Client236-----------237238.. currentmodule:: flask.testing239240.. autoclass:: FlaskClient241 :members:242243244Application Globals245-------------------246247.. currentmodule:: flask248249To share data that is valid for one request only from one function to250another, a global variable is not good enough because it would break in251threaded environments. Flask provides you with a special object that252ensures it is only valid for the active request and that will return253different values for each request. In a nutshell: it does the right254thing, like it does for :class:`request` and :class:`session`.255256.. data:: g257258 Just store on this whatever you want. For example a database259 connection or the user that is currently logged in.260261 Starting with Flask 0.10 this is stored on the application context and262 no longer on the request context which means it becomes available if263 only the application context is bound and not yet a request.264265 This is a proxy. See :ref:`notes-on-proxies` for more information.266267268Useful Functions and Classes269----------------------------270271.. data:: current_app272273 Points to the application handling the request. This is useful for274 extensions that want to support multiple applications running side275 by side. This is powered by the application context and not by the276 request context, so you can change the value of this proxy by277 using the :meth:`~flask.Flask.app_context` method.278279 This is a proxy. See :ref:`notes-on-proxies` for more information.280281.. autofunction:: has_request_context282283.. autofunction:: has_app_context284285.. autofunction:: url_for286287.. function:: abort(code)288289 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given290 status code. For example to abort request handling with a page not291 found exception, you would call ``abort(404)``.292293 :param code: the HTTP error code.294295.. autofunction:: redirect296297.. autofunction:: make_response298299.. autofunction:: after_this_request300301.. autofunction:: send_file302303.. autofunction:: send_from_directory304305.. autofunction:: safe_join306307.. autofunction:: escape308309.. autoclass:: Markup310 :members: escape, unescape, striptags311312Message Flashing313----------------314315.. autofunction:: flash316317.. autofunction:: get_flashed_messages318319JSON Support320------------321322.. module:: flask.json323324Flask uses ``simplejson`` for the JSON implementation. Since simplejson325is provided both by the standard library as well as extension Flask will326try simplejson first and then fall back to the stdlib json module. On top327of that it will delegate access to the current application's JSOn encoders328and decoders for easier customization.329330So for starters instead of doing::331332 try:333 import simplejson as json334 except ImportError:335 import json336337You can instead just do this::338339 from flask import json340341For usage examples, read the :mod:`json` documentation in the standard342lirbary. The following extensions are by default applied to the stdlib's343JSON module:3443451. ``datetime`` objects are serialized as :rfc:`822` strings.3462. Any object with an ``__html__`` method (like :class:`~flask.Markup`)347 will ahve that method called and then the return value is serialized348 as string.349350The :func:`~htmlsafe_dumps` function of this json module is also available351as filter called ``|tojson`` in Jinja2. Note that inside `script`352tags no escaping must take place, so make sure to disable escaping353with ``|safe`` if you intend to use it inside `script` tags:354355.. sourcecode:: html+jinja356357 <script type=text/javascript>358 doSomethingWith({{ user.username|tojson|safe }});359 </script>360361Note that the ``|tojson`` filter escapes forward slashes properly.362363.. autofunction:: jsonify364365.. autofunction:: dumps366367.. autofunction:: dump368369.. autofunction:: loads370371.. autofunction:: load372373.. autoclass:: JSONEncoder374 :members:375376.. autoclass:: JSONDecoder377 :members:378379Template Rendering380------------------381382.. currentmodule:: flask383384.. autofunction:: render_template385386.. autofunction:: render_template_string387388.. autofunction:: get_template_attribute389390Configuration391-------------392393.. autoclass:: Config394 :members:395396Extensions397----------398399.. data:: flask.ext400401 This module acts as redirect import module to Flask extensions. It was402 added in 0.8 as the canonical way to import Flask extensions and makes403 it possible for us to have more flexibility in how we distribute404 extensions.405406 If you want to use an extension named “Flask-Foo” you would import it407 from :data:`~flask.ext` as follows::408409 from flask.ext import foo410411 .. versionadded:: 0.8412413Stream Helpers414--------------415416.. autofunction:: stream_with_context417418Useful Internals419----------------420421.. autoclass:: flask.ctx.RequestContext422 :members:423424.. data:: _request_ctx_stack425426 The internal :class:`~werkzeug.local.LocalStack` that is used to implement427 all the context local objects used in Flask. This is a documented428 instance and can be used by extensions and application code but the429 use is discouraged in general.430431 The following attributes are always present on each layer of the432 stack:433434 `app`435 the active Flask application.436437 `url_adapter`438 the URL adapter that was used to match the request.439440 `request`441 the current request object.442443 `session`444 the active session object.445446 `g`447 an object with all the attributes of the :data:`flask.g` object.448449 `flashes`450 an internal cache for the flashed messages.451452 Example usage::453454 from flask import _request_ctx_stack455456 def get_session():457 ctx = _request_ctx_stack.top458 if ctx is not None:459 return ctx.session460461.. autoclass:: flask.ctx.AppContext462 :members:463464.. data:: _app_ctx_stack465466 Works similar to the request context but only binds the application.467 This is mainly there for extensions to store data.468469 .. versionadded:: 0.9470471.. autoclass:: flask.blueprints.BlueprintSetupState472 :members:473474Signals475-------476477.. when modifying this list, also update the one in signals.rst478479.. versionadded:: 0.6480481.. data:: signals_available482483 `True` if the signalling system is available. This is the case484 when `blinker`_ is installed.485486.. data:: template_rendered487488 This signal is sent when a template was successfully rendered. The489 signal is invoked with the instance of the template as `template`490 and the context as dictionary (named `context`).491492.. data:: request_started493494 This signal is sent before any request processing started but when the495 request context was set up. Because the request context is already496 bound, the subscriber can access the request with the standard global497 proxies such as :class:`~flask.request`.498499.. data:: request_finished500501 This signal is sent right before the response is sent to the client.502 It is passed the response to be sent named `response`.503504.. data:: got_request_exception505506 This signal is sent when an exception happens during request processing.507 It is sent *before* the standard exception handling kicks in and even508 in debug mode, where no exception handling happens. The exception509 itself is passed to the subscriber as `exception`.510511.. data:: request_tearing_down512513 This signal is sent when the application is tearing down the request.514 This is always called, even if an error happened. An `exc` keyword515 argument is passed with the exception that caused the teardown.516517 .. versionchanged:: 0.9518 The `exc` parameter was added.519520.. data:: appcontext_tearing_down521522 This signal is sent when the application is tearing down the523 application context. This is always called, even if an error happened.524 An `exc` keyword argument is passed with the exception that caused the525 teardown.526527.. currentmodule:: None528529.. class:: flask.signals.Namespace530531 An alias for :class:`blinker.base.Namespace` if blinker is available,532 otherwise a dummy class that creates fake signals. This class is533 available for Flask extensions that want to provide the same fallback534 system as Flask itself.535536 .. method:: signal(name, doc=None)537538 Creates a new signal for this namespace if blinker is available,539 otherwise returns a fake signal that has a send method that will540 do nothing but will fail with a :exc:`RuntimeError` for all other541 operations, including connecting.542543.. _blinker: http://pypi.python.org/pypi/blinker544545Class-Based Views546-----------------547548.. versionadded:: 0.7549550.. currentmodule:: None551552.. autoclass:: flask.views.View553 :members:554555.. autoclass:: flask.views.MethodView556 :members:557558.. _url-route-registrations:559560URL Route Registrations561-----------------------562563Generally there are three ways to define rules for the routing system:5645651. You can use the :meth:`flask.Flask.route` decorator.5662. You can use the :meth:`flask.Flask.add_url_rule` function.5673. You can directly access the underlying Werkzeug routing system568 which is exposed as :attr:`flask.Flask.url_map`.569570Variable parts in the route can be specified with angular brackets571(``/user/<username>``). By default a variable part in the URL accepts any572string without a slash however a different converter can be specified as573well by using ``<converter:name>``.574575Variable parts are passed to the view function as keyword arguments.576577The following converters are available:578579=========== ===============================================580`string` accepts any text without a slash (the default)581`int` accepts integers582`float` like `int` but for floating point values583`path` like the default but also accepts slashes584=========== ===============================================585586Here are some examples::587588 @app.route('/')589 def index():590 pass591592 @app.route('/<username>')593 def show_user(username):594 pass595596 @app.route('/post/<int:post_id>')597 def show_post(post_id):598 pass599600An important detail to keep in mind is how Flask deals with trailing601slashes. The idea is to keep each URL unique so the following rules602apply:6036041. If a rule ends with a slash and is requested without a slash by the605 user, the user is automatically redirected to the same page with a606 trailing slash attached.6072. If a rule does not end with a trailing slash and the user requests the608 page with a trailing slash, a 404 not found is raised.609610This is consistent with how web servers deal with static files. This611also makes it possible to use relative link targets safely.612613You can also define multiple rules for the same function. They have to be614unique however. Defaults can also be specified. Here for example is a615definition for a URL that accepts an optional page::616617 @app.route('/users/', defaults={'page': 1})618 @app.route('/users/page/<int:page>')619 def show_users(page):620 pass621622This specifies that ``/users/`` will be the URL for page one and623``/users/page/N`` will be the URL for page `N`.624625Here are the parameters that :meth:`~flask.Flask.route` and626:meth:`~flask.Flask.add_url_rule` accept. The only difference is that627with the route parameter the view function is defined with the decorator628instead of the `view_func` parameter.629630=============== ==========================================================631`rule` the URL rule as string632`endpoint` the endpoint for the registered URL rule. Flask itself633 assumes that the name of the view function is the name634 of the endpoint if not explicitly stated.635`view_func` the function to call when serving a request to the636 provided endpoint. If this is not provided one can637 specify the function later by storing it in the638 :attr:`~flask.Flask.view_functions` dictionary with the639 endpoint as key.640`defaults` A dictionary with defaults for this rule. See the641 example above for how defaults work.642`subdomain` specifies the rule for the subdomain in case subdomain643 matching is in use. If not specified the default644 subdomain is assumed.645`**options` the options to be forwarded to the underlying646 :class:`~werkzeug.routing.Rule` object. A change to647 Werkzeug is handling of method options. methods is a list648 of methods this rule should be limited to (`GET`, `POST`649 etc.). By default a rule just listens for `GET` (and650 implicitly `HEAD`). Starting with Flask 0.6, `OPTIONS` is651 implicitly added and handled by the standard request652 handling. They have to be specified as keyword arguments.653=============== ==========================================================654655.. _view-func-options:656657View Function Options658---------------------659660For internal usage the view functions can have some attributes attached to661customize behavior the view function would normally not have control over.662The following attributes can be provided optionally to either override663some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:664665- `__name__`: The name of a function is by default used as endpoint. If666 endpoint is provided explicitly this value is used. Additionally this667 will be prefixed with the name of the blueprint by default which668 cannot be customized from the function itself.669670- `methods`: If methods are not provided when the URL rule is added,671 Flask will look on the view function object itself is an `methods`672 attribute exists. If it does, it will pull the information for the673 methods from there.674675- `provide_automatic_options`: if this attribute is set Flask will676 either force enable or disable the automatic implementation of the677 HTTP `OPTIONS` response. This can be useful when working with678 decorators that want to customize the `OPTIONS` response on a per-view679 basis.680681- `required_methods`: if this attribute is set, Flask will always add682 these methods when registering a URL rule even if the methods were683 explicitly overriden in the ``route()`` call.684685Full example::686687 def index():688 if request.method == 'OPTIONS':689 # custom options handling here690 ...691 return 'Hello World!'692 index.provide_automatic_options = False693 index.methods = ['GET', 'OPTIONS']694695 app.add_url_rule('/', index)696697.. versionadded:: 0.8698 The `provide_automatic_options` functionality was added.