api.rst
This file
Path
docs/api.rst
719 lines · 21.5 KiB
Last changed by
Imply the |safe on tojson in templates and change escaping logicArmin Ronacherbefore adoptionef72b78
History of this fileTake it
The walk stopped after 200 commits: lines older than 1a9e082 point at it.
tweaks to styleOri Livnehbefore adoption1a9e082
lines 1–217why, 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:: 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:217Merge branch 'json-sessions'Armin Ronacherbefore adoptione1a5761
lines 218–220why, one step back218.. autoclass:: SecureCookieSession219 :members:220tweaks to styleOri Livnehbefore adoption1a9e082
lines 221–226why, one step back221.. autoclass:: NullSession222 :members:223224.. autoclass:: SessionMixin225 :members:226Added uuid support for new session serialization and documented itArmin Ronacherbefore adoption18673ba
lines 227–238why, one step back227.. autodata:: session_json_serializer228229 This object provides dumping and loading methods similar to simplejson230 but it also tags certain builtin Python objects that commonly appear in231 sessions. Currently the following extended values are supported in232 the JSON it dumps:233234 - :class:`~markupsafe.Markup` objects235 - :class:`~uuid.UUID` objects236 - :class:`~datetime.datetime` objects237 - :class:`tuple`\s238tweaks to styleOri Livnehbefore adoption1a9e082
lines 239–272why, one step back239.. admonition:: Notice240241 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer242 starting with Flask 0.8. Either catch this down yourself or use243 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the244 app which converts the result to an integer automatically.245246247Test Client248-----------249250.. currentmodule:: flask.testing251252.. autoclass:: FlaskClient253 :members:254255256Application Globals257-------------------258259.. currentmodule:: flask260261To share data that is valid for one request only from one function to262another, a global variable is not good enough because it would break in263threaded environments. Flask provides you with a special object that264ensures it is only valid for the active request and that will return265different values for each request. In a nutshell: it does the right266thing, like it does for :class:`request` and :class:`session`.267268.. data:: g269270 Just store on this whatever you want. For example a database271 connection or the user that is currently logged in.272flask.g is now on the app context and not the request contextArmin Ronacherbefore adoption1949c4a
lines 273–276why, one step back273 Starting with Flask 0.10 this is stored on the application context and274 no longer on the request context which means it becomes available if275 only the application context is bound and not yet a request.276tweaks to styleOri Livnehbefore adoption1a9e082
lines 277–286why, one step back277 This is a proxy. See :ref:`notes-on-proxies` for more information.278279280Useful Functions and Classes281----------------------------282283.. data:: current_app284285 Points to the application handling the request. This is useful for286 extensions that want to support multiple applications running sideUpdated docs for the app context.Armin Ronacherbefore adoption0207e90
lines 287–289why, one step back287 by side. This is powered by the application context and not by the288 request context, so you can change the value of this proxy by289 using the :meth:`~flask.Flask.app_context` method.tweaks to styleOri Livnehbefore adoption1a9e082
lines 290–294why, one step back290291 This is a proxy. See :ref:`notes-on-proxies` for more information.292293.. autofunction:: has_request_context294Added flask.copy_current_request_context which simplies working with greenletsArmin Ronacherbefore adoption0973536
lines 295–296why, one step back295.. autofunction:: copy_current_request_context296Updated docs for the app context.Armin Ronacherbefore adoption0207e90
lines 297–298why, one step back297.. autofunction:: has_app_context298tweaks to styleOri Livnehbefore adoption1a9e082
lines 299–312why, one step back299.. autofunction:: url_for300301.. function:: abort(code)302303 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given304 status code. For example to abort request handling with a page not305 found exception, you would call ``abort(404)``.306307 :param code: the HTTP error code.308309.. autofunction:: redirect310311.. autofunction:: make_response312Added after_this_request decorator.Armin Ronacherbefore adoption086348e
lines 313–314why, one step back313.. autofunction:: after_this_request314tweaks to styleOri Livnehbefore adoption1a9e082
lines 315–332why, one step back315.. autofunction:: send_file316317.. autofunction:: send_from_directory318319.. autofunction:: safe_join320321.. autofunction:: escape322323.. autoclass:: Markup324 :members: escape, unescape, striptags325326Message Flashing327----------------328329.. autofunction:: flash330331.. autofunction:: get_flashed_messages332Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
lines 333–334why, one step back333JSON Support334------------tweaks to styleOri Livnehbefore adoption1a9e082
line 335why, one step back335Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
line 336why, one step back336.. module:: flask.jsontweaks to styleOri Livnehbefore adoption1a9e082
line 337why, one step back337Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
lines 338–342why, one step back338Flask uses ``simplejson`` for the JSON implementation. Since simplejson339is provided both by the standard library as well as extension Flask will340try simplejson first and then fall back to the stdlib json module. On top341of that it will delegate access to the current application's JSOn encoders342and decoders for easier customization.tweaks to styleOri Livnehbefore adoption1a9e082
line 343why, one step back343Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
line 344why, one step back344So for starters instead of doing::tweaks to styleOri Livnehbefore adoption1a9e082
line 345why, one step back345Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
lines 346–349why, one step back346 try:347 import simplejson as json348 except ImportError:349 import jsontweaks to styleOri Livnehbefore adoption1a9e082
line 350why, one step back350Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
line 351why, one step back351You can instead just do this::tweaks to styleOri Livnehbefore adoption1a9e082
line 352why, one step back352Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
line 353why, one step back353 from flask import jsontweaks to styleOri Livnehbefore adoption1a9e082
line 354why, one step back354Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
lines 355–357why, one step back355For usage examples, read the :mod:`json` documentation in the standard356lirbary. The following extensions are by default applied to the stdlib's357JSON module:tweaks to styleOri Livnehbefore adoption1a9e082
line 358why, one step back358Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
lines 359–362why, one step back3591. ``datetime`` objects are serialized as :rfc:`822` strings.3602. Any object with an ``__html__`` method (like :class:`~flask.Markup`)361 will ahve that method called and then the return value is serialized362 as string.tweaks to styleOri Livnehbefore adoption1a9e082
line 363why, one step back363Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
lines 364–366why, one step back364The :func:`~htmlsafe_dumps` function of this json module is also available365as filter called ``|tojson`` in Jinja2. Note that inside `script`366tags no escaping must take place, so make sure to disable escapingImply the |safe on tojson in templates and change escaping logicArmin Ronacherbefore adoptionef72b78
lines 367–368why, one step back367with ``|safe`` if you intend to use it inside `script` tags unless368you are using Flask 0.10 which implies that:tweaks to styleOri Livnehbefore adoption1a9e082
line 369why, one step back369Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
line 370why, one step back370.. sourcecode:: html+jinjatweaks to styleOri Livnehbefore adoption1a9e082
line 371why, one step back371Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
lines 372–391why, one step back372 <script type=text/javascript>373 doSomethingWith({{ user.username|tojson|safe }});374 </script>375376.. autofunction:: jsonify377378.. autofunction:: dumps379380.. autofunction:: dump381382.. autofunction:: loads383384.. autofunction:: load385386.. autoclass:: JSONEncoder387 :members:388389.. autoclass:: JSONDecoder390 :members:391tweaks to styleOri Livnehbefore adoption1a9e082
lines 392–393why, one step back392Template Rendering393------------------Added wrapper module around simplejson/json for much simplified customization.Armin Ronacherbefore adoptionb146d82
lines 394–395why, one step back394395.. currentmodule:: flasktweaks to styleOri Livnehbefore adoption1a9e082
lines 396–425why, one step back396397.. autofunction:: render_template398399.. autofunction:: render_template_string400401.. autofunction:: get_template_attribute402403Configuration404-------------405406.. autoclass:: Config407 :members:408409Extensions410----------411412.. data:: flask.ext413414 This module acts as redirect import module to Flask extensions. It was415 added in 0.8 as the canonical way to import Flask extensions and makes416 it possible for us to have more flexibility in how we distribute417 extensions.418419 If you want to use an extension named “Flask-Foo” you would import it420 from :data:`~flask.ext` as follows::421422 from flask.ext import foo423424 .. versionadded:: 0.8425Added flask.stream_with_contextArmin Ronacherbefore adoptiond521899
lines 426–430why, one step back426Stream Helpers427--------------428429.. autofunction:: stream_with_context430tweaks to styleOri Livnehbefore adoption1a9e082
lines 431–472why, one step back431Useful Internals432----------------433434.. autoclass:: flask.ctx.RequestContext435 :members:436437.. data:: _request_ctx_stack438439 The internal :class:`~werkzeug.local.LocalStack` that is used to implement440 all the context local objects used in Flask. This is a documented441 instance and can be used by extensions and application code but the442 use is discouraged in general.443444 The following attributes are always present on each layer of the445 stack:446447 `app`448 the active Flask application.449450 `url_adapter`451 the URL adapter that was used to match the request.452453 `request`454 the current request object.455456 `session`457 the active session object.458459 `g`460 an object with all the attributes of the :data:`flask.g` object.461462 `flashes`463 an internal cache for the flashed messages.464465 Example usage::466467 from flask import _request_ctx_stack468469 def get_session():470 ctx = _request_ctx_stack.top471 if ctx is not None:472 return ctx.sessionUpdated docs for the app context.Armin Ronacherbefore adoption0207e90
lines 473–482why, one step back473474.. autoclass:: flask.ctx.AppContext475 :members:476477.. data:: _app_ctx_stack478479 Works similar to the request context but only binds the application.480 This is mainly there for extensions to store data.481482 .. versionadded:: 0.9tweaks to styleOri Livnehbefore adoption1a9e082
lines 483–526why, one step back483484.. autoclass:: flask.blueprints.BlueprintSetupState485 :members:486487Signals488-------489490.. when modifying this list, also update the one in signals.rst491492.. versionadded:: 0.6493494.. data:: signals_available495496 `True` if the signalling system is available. This is the case497 when `blinker`_ is installed.498499.. data:: template_rendered500501 This signal is sent when a template was successfully rendered. The502 signal is invoked with the instance of the template as `template`503 and the context as dictionary (named `context`).504505.. data:: request_started506507 This signal is sent before any request processing started but when the508 request context was set up. Because the request context is already509 bound, the subscriber can access the request with the standard global510 proxies such as :class:`~flask.request`.511512.. data:: request_finished513514 This signal is sent right before the response is sent to the client.515 It is passed the response to be sent named `response`.516517.. data:: got_request_exception518519 This signal is sent when an exception happens during request processing.520 It is sent *before* the standard exception handling kicks in and even521 in debug mode, where no exception handling happens. The exception522 itself is passed to the subscriber as `exception`.523524.. data:: request_tearing_down525526 This signal is sent when the application is tearing down the request.Added documentation for appcontext and teardown handlersArmin Ronacherbefore adoption9bed20c
lines 527–538why, one step back527 This is always called, even if an error happened. An `exc` keyword528 argument is passed with the exception that caused the teardown.529530 .. versionchanged:: 0.9531 The `exc` parameter was added.532533.. data:: appcontext_tearing_down534535 This signal is sent when the application is tearing down the536 application context. This is always called, even if an error happened.537 An `exc` keyword argument is passed with the exception that caused the538 teardown.tweaks to styleOri Livnehbefore adoption1a9e082
line 539why, one step back539Documented new signal message_flashedArmin Ronacherbefore adoption0faed95
lines 540–547why, one step back540.. data:: message_flashed541542 This signal is sent when the application is flashing a message. The543 messages is sent as `message` keyword argument and the category as544 `category`.545546 .. versionadded:: 0.10547tweaks to styleOri Livnehbefore adoption1a9e082
lines 548–565why, one step back548.. currentmodule:: None549550.. class:: flask.signals.Namespace551552 An alias for :class:`blinker.base.Namespace` if blinker is available,553 otherwise a dummy class that creates fake signals. This class is554 available for Flask extensions that want to provide the same fallback555 system as Flask itself.556557 .. method:: signal(name, doc=None)558559 Creates a new signal for this namespace if blinker is available,560 otherwise returns a fake signal that has a send method that will561 do nothing but will fail with a :exc:`RuntimeError` for all other562 operations, including connecting.563564.. _blinker: http://pypi.python.org/pypi/blinker565Merge pull request #392 from FND/docsRon DuPlainbefore adoption7ba5196
line 566why, one step back566Class-Based Viewstweaks to styleOri Livnehbefore adoption1a9e082
lines 567–600why, one step back567-----------------568569.. versionadded:: 0.7570571.. currentmodule:: None572573.. autoclass:: flask.views.View574 :members:575576.. autoclass:: flask.views.MethodView577 :members:578579.. _url-route-registrations:580581URL Route Registrations582-----------------------583584Generally there are three ways to define rules for the routing system:5855861. You can use the :meth:`flask.Flask.route` decorator.5872. You can use the :meth:`flask.Flask.add_url_rule` function.5883. You can directly access the underlying Werkzeug routing system589 which is exposed as :attr:`flask.Flask.url_map`.590591Variable parts in the route can be specified with angular brackets592(``/user/<username>``). By default a variable part in the URL accepts any593string without a slash however a different converter can be specified as594well by using ``<converter:name>``.595596Variable parts are passed to the view function as keyword arguments.597598The following converters are available:599600=========== ===============================================Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption3249eeb
line 601why, one step back601`string` accepts any text without a slash (the default)tweaks to styleOri Livnehbefore adoption1a9e082
lines 602–651why, one step back602`int` accepts integers603`float` like `int` but for floating point values604`path` like the default but also accepts slashes605=========== ===============================================606607Here are some examples::608609 @app.route('/')610 def index():611 pass612613 @app.route('/<username>')614 def show_user(username):615 pass616617 @app.route('/post/<int:post_id>')618 def show_post(post_id):619 pass620621An important detail to keep in mind is how Flask deals with trailing622slashes. The idea is to keep each URL unique so the following rules623apply:6246251. If a rule ends with a slash and is requested without a slash by the626 user, the user is automatically redirected to the same page with a627 trailing slash attached.6282. If a rule does not end with a trailing slash and the user requests the629 page with a trailing slash, a 404 not found is raised.630631This is consistent with how web servers deal with static files. This632also makes it possible to use relative link targets safely.633634You can also define multiple rules for the same function. They have to be635unique however. Defaults can also be specified. Here for example is a636definition for a URL that accepts an optional page::637638 @app.route('/users/', defaults={'page': 1})639 @app.route('/users/page/<int:page>')640 def show_users(page):641 pass642643This specifies that ``/users/`` will be the URL for page one and644``/users/page/N`` will be the URL for page `N`.645646Here are the parameters that :meth:`~flask.Flask.route` and647:meth:`~flask.Flask.add_url_rule` accept. The only difference is that648with the route parameter the view function is defined with the decorator649instead of the `view_func` parameter.650651=============== ==========================================================Merge pull request #493 from kuyanatan/patch-1Ron DuPlainbefore adoptionfd62cd8
line 652why, one step back652`rule` the URL rule as stringtweaks to styleOri Livnehbefore adoption1a9e082
lines 653–701why, one step back653`endpoint` the endpoint for the registered URL rule. Flask itself654 assumes that the name of the view function is the name655 of the endpoint if not explicitly stated.656`view_func` the function to call when serving a request to the657 provided endpoint. If this is not provided one can658 specify the function later by storing it in the659 :attr:`~flask.Flask.view_functions` dictionary with the660 endpoint as key.661`defaults` A dictionary with defaults for this rule. See the662 example above for how defaults work.663`subdomain` specifies the rule for the subdomain in case subdomain664 matching is in use. If not specified the default665 subdomain is assumed.666`**options` the options to be forwarded to the underlying667 :class:`~werkzeug.routing.Rule` object. A change to668 Werkzeug is handling of method options. methods is a list669 of methods this rule should be limited to (`GET`, `POST`670 etc.). By default a rule just listens for `GET` (and671 implicitly `HEAD`). Starting with Flask 0.6, `OPTIONS` is672 implicitly added and handled by the standard request673 handling. They have to be specified as keyword arguments.674=============== ==========================================================675676.. _view-func-options:677678View Function Options679---------------------680681For internal usage the view functions can have some attributes attached to682customize behavior the view function would normally not have control over.683The following attributes can be provided optionally to either override684some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:685686- `__name__`: The name of a function is by default used as endpoint. If687 endpoint is provided explicitly this value is used. Additionally this688 will be prefixed with the name of the blueprint by default which689 cannot be customized from the function itself.690691- `methods`: If methods are not provided when the URL rule is added,692 Flask will look on the view function object itself is an `methods`693 attribute exists. If it does, it will pull the information for the694 methods from there.695696- `provide_automatic_options`: if this attribute is set Flask will697 either force enable or disable the automatic implementation of the698 HTTP `OPTIONS` response. This can be useful when working with699 decorators that want to customize the `OPTIONS` response on a per-view700 basis.701Added required_methodsArmin Ronacherbefore adoptiondbfd406
lines 702–705why, one step back702- `required_methods`: if this attribute is set, Flask will always add703 these methods when registering a URL rule even if the methods were704 explicitly overriden in the ``route()`` call.705tweaks to styleOri Livnehbefore adoption1a9e082
lines 706–719why, one step back706Full example::707708 def index():709 if request.method == 'OPTIONS':710 # custom options handling here711 ...712 return 'Hello World!'713 index.provide_automatic_options = False714 index.methods = ['GET', 'OPTIONS']715716 app.add_url_rule('/', index)717718.. versionadded:: 0.8719 The `provide_automatic_options` functionality was added.