api.rst
This file
Path
docs/api.rst
830 lines · 24.6 KiB
Last changed by
remove unused ref directivesDavid Lordbefore adoption171aabc
History of this fileTake it
The walk stopped after 200 commits: lines older than 324b4ea point at it.
Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 1–31why, one step back1API2===34.. module:: flask56This part of the documentation covers all the interfaces of Flask. For7parts where Flask depends on external libraries, we document the most8important right here and provide links to the canonical documentation.91011Application Object12------------------1314.. autoclass:: Flask15 :members:16 :inherited-members:171819Blueprint Objects20-----------------2122.. autoclass:: Blueprint23 :members:24 :inherited-members:2526Incoming Request Data27---------------------2829.. autoclass:: Request30 :members:31 :inherited-members:Merge pull request #3408 from lamby/943674-flask-please-make-the-build-reproducibleDavid Lordbefore adoption1234eb0
line 32why, one step back32 :exclude-members: json_moduleMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 33–44why, one step back3334 .. attribute:: environ3536 The underlying WSGI environment.3738 .. attribute:: path39 .. attribute:: full_path40 .. attribute:: script_root41 .. attribute:: url42 .. attribute:: base_url43 .. attribute:: url_root44Merge branch '1.0.x'David Lordbefore adoption1351d0a
lines 45–47why, one step back45 Provides different ways to look at the current :rfc:`3987`.46 Imagine your application is listening on the following application47 root::Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 48–58why, one step back4849 http://www.example.com/myapplication5051 And a user requests the following URI::5253 http://www.example.com/myapplication/%CF%80/page.html?x=y5455 In this case the values of the above mentioned attributes would be56 the following:5758 ============= ======================================================Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
lines 59–64why, one step back59 `path` ``'/π/page.html'``60 `full_path` ``'/π/page.html?x=y'``61 `script_root` ``'/myapplication'``62 `base_url` ``'http://www.example.com/myapplication/π/page.html'``63 `url` ``'http://www.example.com/myapplication/π/page.html?x=y'``64 `url_root` ``'http://www.example.com/myapplication/'``Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 65–116why, one step back65 ============= ======================================================666768.. attribute:: request6970 To access incoming request data, you can use the global `request`71 object. Flask parses incoming request data for you and gives you72 access to it through that global object. Internally Flask makes73 sure that you always get the correct data for the active thread if you74 are in a multithreaded environment.7576 This is a proxy. See :ref:`notes-on-proxies` for more information.7778 The request object is an instance of a :class:`~werkzeug.wrappers.Request`79 subclass and provides all of the attributes Werkzeug defines. This80 just shows a quick overview of the most important ones.818283Response Objects84----------------8586.. autoclass:: flask.Response87 :members: set_cookie, max_cookie_size, data, mimetype, is_json, get_json8889 .. attribute:: headers9091 A :class:`~werkzeug.datastructures.Headers` object representing the response headers.9293 .. attribute:: status9495 A string with a response status.9697 .. attribute:: status_code9899 The response status as integer.100101102Sessions103--------104105If you have set :attr:`Flask.secret_key` (or configured it from106:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes107it possible to remember information from one request to another. The way Flask108does this is by using a signed cookie. The user can look at the session109contents, but can't modify it unless they know the secret key, so make sure to110set that to something complex and unguessable.111112To access the current session you can use the :class:`session` object:113114.. class:: session115116 The session object works pretty much like an ordinary dict, with theMerge pull request #2839 from jlara310/masterDavid Lordbefore adoptionf4b0f64
line 117why, one step back117 difference that it keeps track of modifications.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 118–313why, one step back118119 This is a proxy. See :ref:`notes-on-proxies` for more information.120121 The following attributes are interesting:122123 .. attribute:: new124125 ``True`` if the session is new, ``False`` otherwise.126127 .. attribute:: modified128129 ``True`` if the session object detected a modification. Be advised130 that modifications on mutable structures are not picked up131 automatically, in that situation you have to explicitly set the132 attribute to ``True`` yourself. Here an example::133134 # this change is not picked up because a mutable object (here135 # a list) is changed.136 session['objects'].append(42)137 # so mark it as modified yourself138 session.modified = True139140 .. attribute:: permanent141142 If set to ``True`` the session lives for143 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The144 default is 31 days. If set to ``False`` (which is the default) the145 session will be deleted when the user closes the browser.146147148Session Interface149-----------------150151.. versionadded:: 0.8152153The session interface provides a simple way to replace the session154implementation that Flask is using.155156.. currentmodule:: flask.sessions157158.. autoclass:: SessionInterface159 :members:160161.. autoclass:: SecureCookieSessionInterface162 :members:163164.. autoclass:: SecureCookieSession165 :members:166167.. autoclass:: NullSession168 :members:169170.. autoclass:: SessionMixin171 :members:172173.. admonition:: Notice174175 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer176 starting with Flask 0.8. Either catch this down yourself or use177 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the178 app which converts the result to an integer automatically.179180181Test Client182-----------183184.. currentmodule:: flask.testing185186.. autoclass:: FlaskClient187 :members:188189190Test CLI Runner191---------------192193.. currentmodule:: flask.testing194195.. autoclass:: FlaskCliRunner196 :members:197198199Application Globals200-------------------201202.. currentmodule:: flask203204To share data that is valid for one request only from one function to205another, a global variable is not good enough because it would break in206threaded environments. Flask provides you with a special object that207ensures it is only valid for the active request and that will return208different values for each request. In a nutshell: it does the right209thing, like it does for :class:`request` and :class:`session`.210211.. data:: g212213 A namespace object that can store data during an214 :doc:`application context </appcontext>`. This is an instance of215 :attr:`Flask.app_ctx_globals_class`, which defaults to216 :class:`ctx._AppCtxGlobals`.217218 This is a good place to store resources during a request. During219 testing, you can use the :ref:`faking-resources` pattern to220 pre-configure such resources.221222 This is a proxy. See :ref:`notes-on-proxies` for more information.223224 .. versionchanged:: 0.10225 Bound to the application context instead of the request context.226227.. autoclass:: flask.ctx._AppCtxGlobals228 :members:229230231Useful Functions and Classes232----------------------------233234.. data:: current_app235236 A proxy to the application handling the current request. This is237 useful to access the application without needing to import it, or if238 it can't be imported, such as when using the application factory239 pattern or in blueprints and extensions.240241 This is only available when an242 :doc:`application context </appcontext>` is pushed. This happens243 automatically during requests and CLI commands. It can be controlled244 manually with :meth:`~flask.Flask.app_context`.245246 This is a proxy. See :ref:`notes-on-proxies` for more information.247248.. autofunction:: has_request_context249250.. autofunction:: copy_current_request_context251252.. autofunction:: has_app_context253254.. autofunction:: url_for255256.. autofunction:: abort257258.. autofunction:: redirect259260.. autofunction:: make_response261262.. autofunction:: after_this_request263264.. autofunction:: send_file265266.. autofunction:: send_from_directory267268.. autofunction:: safe_join269270.. autofunction:: escape271272.. autoclass:: Markup273 :members: escape, unescape, striptags274275Message Flashing276----------------277278.. autofunction:: flash279280.. autofunction:: get_flashed_messages281282JSON Support283------------284285.. module:: flask.json286287Flask uses ``simplejson`` for the JSON implementation. Since simplejson288is provided by both the standard library as well as extension, Flask will289try simplejson first and then fall back to the stdlib json module. On top290of that it will delegate access to the current application's JSON encoders291and decoders for easier customization.292293So for starters instead of doing::294295 try:296 import simplejson as json297 except ImportError:298 import json299300You can instead just do this::301302 from flask import json303304For usage examples, read the :mod:`json` documentation in the standard305library. The following extensions are by default applied to the stdlib's306JSON module:3073081. ``datetime`` objects are serialized as :rfc:`822` strings.3092. Any object with an ``__html__`` method (like :class:`~flask.Markup`)310 will have that method called and then the return value is serialized311 as string.312313The :func:`~htmlsafe_dumps` function of this json module is also availableMerge branch '1.0-maintenance'David Lordbefore adoption3b45b82
lines 314–317why, one step back314as a filter called ``|tojson`` in Jinja2. Note that in versions of Flask prior315to Flask 0.10, you must disable escaping with ``|safe`` if you intend to use316``|tojson`` output inside ``script`` tags. In Flask 0.10 and above, this317happens automatically (but it's harmless to include ``|safe`` anyway).Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 318–326why, one step back318319.. sourcecode:: html+jinja320321 <script type=text/javascript>322 doSomethingWith({{ user.username|tojson|safe }});323 </script>324325.. admonition:: Auto-Sort JSON Keys326remove unused ref directivesDavid Lordbefore adoption171aabc
lines 327–328why, one step back327 The configuration variable :data:`JSON_SORT_KEYS` can be set to328 ``False`` to stop Flask from auto-sorting keys. By default sortingMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 329–330why, one step back329 is enabled and outside of the app context sorting is turned on.330remove unused ref directivesDavid Lordbefore adoption171aabc
lines 331–332why, one step back331 Notice that disabling key sorting can cause issues when using332 content based HTTP caches and Python's hash randomization feature.Merge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 333–717why, one step back333334.. autofunction:: jsonify335336.. autofunction:: dumps337338.. autofunction:: dump339340.. autofunction:: loads341342.. autofunction:: load343344.. autoclass:: JSONEncoder345 :members:346347.. autoclass:: JSONDecoder348 :members:349350.. automodule:: flask.json.tag351352Template Rendering353------------------354355.. currentmodule:: flask356357.. autofunction:: render_template358359.. autofunction:: render_template_string360361.. autofunction:: get_template_attribute362363Configuration364-------------365366.. autoclass:: Config367 :members:368369370Stream Helpers371--------------372373.. autofunction:: stream_with_context374375Useful Internals376----------------377378.. autoclass:: flask.ctx.RequestContext379 :members:380381.. data:: _request_ctx_stack382383 The internal :class:`~werkzeug.local.LocalStack` that holds384 :class:`~flask.ctx.RequestContext` instances. Typically, the385 :data:`request` and :data:`session` proxies should be accessed386 instead of the stack. It may be useful to access the stack in387 extension code.388389 The following attributes are always present on each layer of the390 stack:391392 `app`393 the active Flask application.394395 `url_adapter`396 the URL adapter that was used to match the request.397398 `request`399 the current request object.400401 `session`402 the active session object.403404 `g`405 an object with all the attributes of the :data:`flask.g` object.406407 `flashes`408 an internal cache for the flashed messages.409410 Example usage::411412 from flask import _request_ctx_stack413414 def get_session():415 ctx = _request_ctx_stack.top416 if ctx is not None:417 return ctx.session418419.. autoclass:: flask.ctx.AppContext420 :members:421422.. data:: _app_ctx_stack423424 The internal :class:`~werkzeug.local.LocalStack` that holds425 :class:`~flask.ctx.AppContext` instances. Typically, the426 :data:`current_app` and :data:`g` proxies should be accessed instead427 of the stack. Extensions can access the contexts on the stack as a428 namespace to store data.429430 .. versionadded:: 0.9431432.. autoclass:: flask.blueprints.BlueprintSetupState433 :members:434435.. _core-signals-list:436437Signals438-------439440.. versionadded:: 0.6441442.. data:: signals.signals_available443444 ``True`` if the signaling system is available. This is the case445 when `blinker`_ is installed.446447The following signals exist in Flask:448449.. data:: template_rendered450451 This signal is sent when a template was successfully rendered. The452 signal is invoked with the instance of the template as `template`453 and the context as dictionary (named `context`).454455 Example subscriber::456457 def log_template_renders(sender, template, context, **extra):458 sender.logger.debug('Rendering template "%s" with context %s',459 template.name or 'string template',460 context)461462 from flask import template_rendered463 template_rendered.connect(log_template_renders, app)464465.. data:: flask.before_render_template466 :noindex:467468 This signal is sent before template rendering process. The469 signal is invoked with the instance of the template as `template`470 and the context as dictionary (named `context`).471472 Example subscriber::473474 def log_template_renders(sender, template, context, **extra):475 sender.logger.debug('Rendering template "%s" with context %s',476 template.name or 'string template',477 context)478479 from flask import before_render_template480 before_render_template.connect(log_template_renders, app)481482.. data:: request_started483484 This signal is sent when the request context is set up, before485 any request processing happens. Because the request context is already486 bound, the subscriber can access the request with the standard global487 proxies such as :class:`~flask.request`.488489 Example subscriber::490491 def log_request(sender, **extra):492 sender.logger.debug('Request context is set up')493494 from flask import request_started495 request_started.connect(log_request, app)496497.. data:: request_finished498499 This signal is sent right before the response is sent to the client.500 It is passed the response to be sent named `response`.501502 Example subscriber::503504 def log_response(sender, response, **extra):505 sender.logger.debug('Request context is about to close down. '506 'Response: %s', response)507508 from flask import request_finished509 request_finished.connect(log_response, app)510511.. data:: got_request_exception512513 This signal is sent when an exception happens during request processing.514 It is sent *before* the standard exception handling kicks in and even515 in debug mode, where no exception handling happens. The exception516 itself is passed to the subscriber as `exception`.517518 Example subscriber::519520 def log_exception(sender, exception, **extra):521 sender.logger.debug('Got exception during processing: %s', exception)522523 from flask import got_request_exception524 got_request_exception.connect(log_exception, app)525526.. data:: request_tearing_down527528 This signal is sent when the request is tearing down. This is always529 called, even if an exception is caused. Currently functions listening530 to this signal are called after the regular teardown handlers, but this531 is not something you can rely on.532533 Example subscriber::534535 def close_db_connection(sender, **extra):536 session.close()537538 from flask import request_tearing_down539 request_tearing_down.connect(close_db_connection, app)540541 As of Flask 0.9, this will also be passed an `exc` keyword argument542 that has a reference to the exception that caused the teardown if543 there was one.544545.. data:: appcontext_tearing_down546547 This signal is sent when the app context is tearing down. This is always548 called, even if an exception is caused. Currently functions listening549 to this signal are called after the regular teardown handlers, but this550 is not something you can rely on.551552 Example subscriber::553554 def close_db_connection(sender, **extra):555 session.close()556557 from flask import appcontext_tearing_down558 appcontext_tearing_down.connect(close_db_connection, app)559560 This will also be passed an `exc` keyword argument that has a reference561 to the exception that caused the teardown if there was one.562563.. data:: appcontext_pushed564565 This signal is sent when an application context is pushed. The sender566 is the application. This is usually useful for unittests in order to567 temporarily hook in information. For instance it can be used to568 set a resource early onto the `g` object.569570 Example usage::571572 from contextlib import contextmanager573 from flask import appcontext_pushed574575 @contextmanager576 def user_set(app, user):577 def handler(sender, **kwargs):578 g.user = user579 with appcontext_pushed.connected_to(handler, app):580 yield581582 And in the testcode::583584 def test_user_me(self):585 with user_set(app, 'john'):586 c = app.test_client()587 resp = c.get('/users/me')588 assert resp.data == 'username=john'589590 .. versionadded:: 0.10591592.. data:: appcontext_popped593594 This signal is sent when an application context is popped. The sender595 is the application. This usually falls in line with the596 :data:`appcontext_tearing_down` signal.597598 .. versionadded:: 0.10599600601.. data:: message_flashed602603 This signal is sent when the application is flashing a message. The604 messages is sent as `message` keyword argument and the category as605 `category`.606607 Example subscriber::608609 recorded = []610 def record(sender, message, category, **extra):611 recorded.append((message, category))612613 from flask import message_flashed614 message_flashed.connect(record, app)615616 .. versionadded:: 0.10617618.. class:: signals.Namespace619620 An alias for :class:`blinker.base.Namespace` if blinker is available,621 otherwise a dummy class that creates fake signals. This class is622 available for Flask extensions that want to provide the same fallback623 system as Flask itself.624625 .. method:: signal(name, doc=None)626627 Creates a new signal for this namespace if blinker is available,628 otherwise returns a fake signal that has a send method that will629 do nothing but will fail with a :exc:`RuntimeError` for all other630 operations, including connecting.631632633.. _blinker: https://pypi.org/project/blinker/634635636Class-Based Views637-----------------638639.. versionadded:: 0.7640641.. currentmodule:: None642643.. autoclass:: flask.views.View644 :members:645646.. autoclass:: flask.views.MethodView647 :members:648649.. _url-route-registrations:650651URL Route Registrations652-----------------------653654Generally there are three ways to define rules for the routing system:6556561. You can use the :meth:`flask.Flask.route` decorator.6572. You can use the :meth:`flask.Flask.add_url_rule` function.6583. You can directly access the underlying Werkzeug routing system659 which is exposed as :attr:`flask.Flask.url_map`.660661Variable parts in the route can be specified with angular brackets662(``/user/<username>``). By default a variable part in the URL accepts any663string without a slash however a different converter can be specified as664well by using ``<converter:name>``.665666Variable parts are passed to the view function as keyword arguments.667668The following converters are available:669670=========== ===============================================671`string` accepts any text without a slash (the default)672`int` accepts integers673`float` like `int` but for floating point values674`path` like the default but also accepts slashes675`any` matches one of the items provided676`uuid` accepts UUID strings677=========== ===============================================678679Custom converters can be defined using :attr:`flask.Flask.url_map`.680681Here are some examples::682683 @app.route('/')684 def index():685 pass686687 @app.route('/<username>')688 def show_user(username):689 pass690691 @app.route('/post/<int:post_id>')692 def show_post(post_id):693 pass694695An important detail to keep in mind is how Flask deals with trailing696slashes. The idea is to keep each URL unique so the following rules697apply:6986991. If a rule ends with a slash and is requested without a slash by the700 user, the user is automatically redirected to the same page with a701 trailing slash attached.7022. If a rule does not end with a trailing slash and the user requests the703 page with a trailing slash, a 404 not found is raised.704705This is consistent with how web servers deal with static files. This706also makes it possible to use relative link targets safely.707708You can also define multiple rules for the same function. They have to be709unique however. Defaults can also be specified. Here for example is a710definition for a URL that accepts an optional page::711712 @app.route('/users/', defaults={'page': 1})713 @app.route('/users/page/<int:page>')714 def show_users(page):715 pass716717This specifies that ``/users/`` will be the URL for page one andMerge branch '1.0-maintenance'David Lordbefore adoption1fa9185
lines 718–726why, one step back718``/users/page/N`` will be the URL for page ``N``.719720If a URL contains a default value, it will be redirected to its simpler721form with a 301 redirect. In the above example, ``/users/page/1`` will722be redirected to ``/users/``. If your route handles ``GET`` and ``POST``723requests, make sure the default route only handles ``GET``, as redirects724can't preserve form data. ::725726 @app.route('/region/', defaults={'id': 1})Merge branch '1.0.x'David Lordbefore adoption2236ba9
line 727why, one step back727 @app.route('/region/<int:id>', methods=['GET', 'POST'])Merge branch '1.0-maintenance'David Lordbefore adoption1fa9185
lines 728–729why, one step back728 def region(id):729 passMerge pull request #2711 from pope1ni/session-serializer-fixesDavid Lordbefore adoption324b4ea
lines 730–830why, one step back730731Here are the parameters that :meth:`~flask.Flask.route` and732:meth:`~flask.Flask.add_url_rule` accept. The only difference is that733with the route parameter the view function is defined with the decorator734instead of the `view_func` parameter.735736=============== ==========================================================737`rule` the URL rule as string738`endpoint` the endpoint for the registered URL rule. Flask itself739 assumes that the name of the view function is the name740 of the endpoint if not explicitly stated.741`view_func` the function to call when serving a request to the742 provided endpoint. If this is not provided one can743 specify the function later by storing it in the744 :attr:`~flask.Flask.view_functions` dictionary with the745 endpoint as key.746`defaults` A dictionary with defaults for this rule. See the747 example above for how defaults work.748`subdomain` specifies the rule for the subdomain in case subdomain749 matching is in use. If not specified the default750 subdomain is assumed.751`**options` the options to be forwarded to the underlying752 :class:`~werkzeug.routing.Rule` object. A change to753 Werkzeug is handling of method options. methods is a list754 of methods this rule should be limited to (``GET``, ``POST``755 etc.). By default a rule just listens for ``GET`` (and756 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is757 implicitly added and handled by the standard request758 handling. They have to be specified as keyword arguments.759=============== ==========================================================760761762View Function Options763---------------------764765For internal usage the view functions can have some attributes attached to766customize behavior the view function would normally not have control over.767The following attributes can be provided optionally to either override768some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:769770- `__name__`: The name of a function is by default used as endpoint. If771 endpoint is provided explicitly this value is used. Additionally this772 will be prefixed with the name of the blueprint by default which773 cannot be customized from the function itself.774775- `methods`: If methods are not provided when the URL rule is added,776 Flask will look on the view function object itself if a `methods`777 attribute exists. If it does, it will pull the information for the778 methods from there.779780- `provide_automatic_options`: if this attribute is set Flask will781 either force enable or disable the automatic implementation of the782 HTTP ``OPTIONS`` response. This can be useful when working with783 decorators that want to customize the ``OPTIONS`` response on a per-view784 basis.785786- `required_methods`: if this attribute is set, Flask will always add787 these methods when registering a URL rule even if the methods were788 explicitly overridden in the ``route()`` call.789790Full example::791792 def index():793 if request.method == 'OPTIONS':794 # custom options handling here795 ...796 return 'Hello World!'797 index.provide_automatic_options = False798 index.methods = ['GET', 'OPTIONS']799800 app.add_url_rule('/', index)801802.. versionadded:: 0.8803 The `provide_automatic_options` functionality was added.804805Command Line Interface806----------------------807808.. currentmodule:: flask.cli809810.. autoclass:: FlaskGroup811 :members:812813.. autoclass:: AppGroup814 :members:815816.. autoclass:: ScriptInfo817 :members:818819.. autofunction:: load_dotenv820821.. autofunction:: with_appcontext822823.. autofunction:: pass_script_info824825 Marks a function so that an instance of :class:`ScriptInfo` is passed826 as first argument to the click callback.827828.. autodata:: run_command829830.. autodata:: shell_command