api.rst
This file
Path
docs/api.rst
750 lines · 22.0 KiB
Last changed by
Merge pull request #4907 from rayanth/patch-1David Lordbefore adoptiondcdcac2
History of this fileTake it
1API2===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:32 :exclude-members: json_module3334.. attribute:: request3536 To access incoming request data, you can use the global `request`37 object. Flask parses incoming request data for you and gives you38 access to it through that global object. Internally Flask makes39 sure that you always get the correct data for the active thread if you40 are in a multithreaded environment.4142 This is a proxy. See :ref:`notes-on-proxies` for more information.4344 The request object is an instance of a :class:`~flask.Request`.454647Response Objects48----------------4950.. autoclass:: flask.Response51 :members:52 :inherited-members:53 :exclude-members: json_module5455Sessions56--------5758If you have set :attr:`Flask.secret_key` (or configured it from59:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes60it possible to remember information from one request to another. The way Flask61does this is by using a signed cookie. The user can look at the session62contents, but can't modify it unless they know the secret key, so make sure to63set that to something complex and unguessable.6465To access the current session you can use the :class:`session` object:6667.. class:: session6869 The session object works pretty much like an ordinary dict, with the70 difference that it keeps track of modifications.7172 This is a proxy. See :ref:`notes-on-proxies` for more information.7374 The following attributes are interesting:7576 .. attribute:: new7778 ``True`` if the session is new, ``False`` otherwise.7980 .. attribute:: modified8182 ``True`` if the session object detected a modification. Be advised83 that modifications on mutable structures are not picked up84 automatically, in that situation you have to explicitly set the85 attribute to ``True`` yourself. Here an example::8687 # this change is not picked up because a mutable object (here88 # a list) is changed.89 session['objects'].append(42)90 # so mark it as modified yourself91 session.modified = True9293 .. attribute:: permanent9495 If set to ``True`` the session lives for96 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The97 default is 31 days. If set to ``False`` (which is the default) the98 session will be deleted when the user closes the browser.99100101Session Interface102-----------------103104.. versionadded:: 0.8105106The session interface provides a simple way to replace the session107implementation that Flask is using.108109.. currentmodule:: flask.sessions110111.. autoclass:: SessionInterface112 :members:113114.. autoclass:: SecureCookieSessionInterface115 :members:116117.. autoclass:: SecureCookieSession118 :members:119120.. autoclass:: NullSession121 :members:122123.. autoclass:: SessionMixin124 :members:125126.. admonition:: Notice127128 The :data:`PERMANENT_SESSION_LIFETIME` config can be an integer or ``timedelta``.129 The :attr:`~flask.Flask.permanent_session_lifetime` attribute is always a130 ``timedelta``.131132133Test Client134-----------135136.. currentmodule:: flask.testing137138.. autoclass:: FlaskClient139 :members:140141142Test CLI Runner143---------------144145.. currentmodule:: flask.testing146147.. autoclass:: FlaskCliRunner148 :members:149150151Application Globals152-------------------153154.. currentmodule:: flask155156To share data that is valid for one request only from one function to157another, a global variable is not good enough because it would break in158threaded environments. Flask provides you with a special object that159ensures it is only valid for the active request and that will return160different values for each request. In a nutshell: it does the right161thing, like it does for :class:`request` and :class:`session`.162163.. data:: g164165 A namespace object that can store data during an166 :doc:`application context </appcontext>`. This is an instance of167 :attr:`Flask.app_ctx_globals_class`, which defaults to168 :class:`ctx._AppCtxGlobals`.169170 This is a good place to store resources during a request. For171 example, a ``before_request`` function could load a user object from172 a session id, then set ``g.user`` to be used in the view function.173174 This is a proxy. See :ref:`notes-on-proxies` for more information.175176 .. versionchanged:: 0.10177 Bound to the application context instead of the request context.178179.. autoclass:: flask.ctx._AppCtxGlobals180 :members:181182183Useful Functions and Classes184----------------------------185186.. data:: current_app187188 A proxy to the application handling the current request. This is189 useful to access the application without needing to import it, or if190 it can't be imported, such as when using the application factory191 pattern or in blueprints and extensions.192193 This is only available when an194 :doc:`application context </appcontext>` is pushed. This happens195 automatically during requests and CLI commands. It can be controlled196 manually with :meth:`~flask.Flask.app_context`.197198 This is a proxy. See :ref:`notes-on-proxies` for more information.199200.. autofunction:: has_request_context201202.. autofunction:: copy_current_request_context203204.. autofunction:: has_app_context205206.. autofunction:: url_for207208.. autofunction:: abort209210.. autofunction:: redirect211212.. autofunction:: make_response213214.. autofunction:: after_this_request215216.. autofunction:: send_file217218.. autofunction:: send_from_directory219220.. autofunction:: escape221222.. autoclass:: Markup223 :members: escape, unescape, striptags224225Message Flashing226----------------227228.. autofunction:: flash229230.. autofunction:: get_flashed_messages231232233JSON Support234------------235236.. module:: flask.json237238Flask uses Python's built-in :mod:`json` module for handling JSON by239default. The JSON implementation can be changed by assigning a different240provider to :attr:`flask.Flask.json_provider_class` or241:attr:`flask.Flask.json`. The functions provided by ``flask.json`` will242use methods on ``app.json`` if an app context is active.243244Jinja's ``|tojson`` filter is configured to use the app's JSON provider.245The filter marks the output with ``|safe``. Use it to render data inside246HTML ``<script>`` tags.247248.. sourcecode:: html+jinja249250 <script>251 const names = {{ names|tojson }};252 renderChart(names, {{ axis_data|tojson }});253 </script>254255.. autofunction:: jsonify256257.. autofunction:: dumps258259.. autofunction:: dump260261.. autofunction:: loads262263.. autofunction:: load264265.. autoclass:: flask.json.provider.JSONProvider266 :members:267 :member-order: bysource268269.. autoclass:: flask.json.provider.DefaultJSONProvider270 :members:271 :member-order: bysource272273.. autoclass:: JSONEncoder274 :members:275276.. autoclass:: JSONDecoder277 :members:278279.. automodule:: flask.json.tag280281282Template Rendering283------------------284285.. currentmodule:: flask286287.. autofunction:: render_template288289.. autofunction:: render_template_string290291.. autofunction:: stream_template292293.. autofunction:: stream_template_string294295.. autofunction:: get_template_attribute296297Configuration298-------------299300.. autoclass:: Config301 :members:302303304Stream Helpers305--------------306307.. autofunction:: stream_with_context308309Useful Internals310----------------311312.. autoclass:: flask.ctx.RequestContext313 :members:314315.. data:: flask.globals.request_ctx316317 The current :class:`~flask.ctx.RequestContext`. If a request context318 is not active, accessing attributes on this proxy will raise a319 ``RuntimeError``.320321 This is an internal object that is essential to how Flask handles322 requests. Accessing this should not be needed in most cases. Most323 likely you want :data:`request` and :data:`session` instead.324325.. autoclass:: flask.ctx.AppContext326 :members:327328.. data:: flask.globals.app_ctx329330 The current :class:`~flask.ctx.AppContext`. If an app context is not331 active, accessing attributes on this proxy will raise a332 ``RuntimeError``.333334 This is an internal object that is essential to how Flask handles335 requests. Accessing this should not be needed in most cases. Most336 likely you want :data:`current_app` and :data:`g` instead.337338.. autoclass:: flask.blueprints.BlueprintSetupState339 :members:340341.. _core-signals-list:342343Signals344-------345346.. versionadded:: 0.6347348.. data:: signals.signals_available349350 ``True`` if the signaling system is available. This is the case351 when `blinker`_ is installed.352353The following signals exist in Flask:354355.. data:: template_rendered356357 This signal is sent when a template was successfully rendered. The358 signal is invoked with the instance of the template as `template`359 and the context as dictionary (named `context`).360361 Example subscriber::362363 def log_template_renders(sender, template, context, **extra):364 sender.logger.debug('Rendering template "%s" with context %s',365 template.name or 'string template',366 context)367368 from flask import template_rendered369 template_rendered.connect(log_template_renders, app)370371.. data:: flask.before_render_template372 :noindex:373374 This signal is sent before template rendering process. The375 signal is invoked with the instance of the template as `template`376 and the context as dictionary (named `context`).377378 Example subscriber::379380 def log_template_renders(sender, template, context, **extra):381 sender.logger.debug('Rendering template "%s" with context %s',382 template.name or 'string template',383 context)384385 from flask import before_render_template386 before_render_template.connect(log_template_renders, app)387388.. data:: request_started389390 This signal is sent when the request context is set up, before391 any request processing happens. Because the request context is already392 bound, the subscriber can access the request with the standard global393 proxies such as :class:`~flask.request`.394395 Example subscriber::396397 def log_request(sender, **extra):398 sender.logger.debug('Request context is set up')399400 from flask import request_started401 request_started.connect(log_request, app)402403.. data:: request_finished404405 This signal is sent right before the response is sent to the client.406 It is passed the response to be sent named `response`.407408 Example subscriber::409410 def log_response(sender, response, **extra):411 sender.logger.debug('Request context is about to close down. '412 'Response: %s', response)413414 from flask import request_finished415 request_finished.connect(log_response, app)416417.. data:: got_request_exception418419 This signal is sent when an unhandled exception happens during420 request processing, including when debugging. The exception is421 passed to the subscriber as ``exception``.422423 This signal is not sent for424 :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that425 have error handlers registered, unless the exception was raised from426 an error handler.427428 This example shows how to do some extra logging if a theoretical429 ``SecurityException`` was raised:430431 .. code-block:: python432433 from flask import got_request_exception434435 def log_security_exception(sender, exception, **extra):436 if not isinstance(exception, SecurityException):437 return438439 security_logger.exception(440 f"SecurityException at {request.url!r}",441 exc_info=exception,442 )443444 got_request_exception.connect(log_security_exception, app)445446.. data:: request_tearing_down447448 This signal is sent when the request is tearing down. This is always449 called, even if an exception is caused. Currently functions listening450 to this signal are called after the regular teardown handlers, but this451 is not something you can rely on.452453 Example subscriber::454455 def close_db_connection(sender, **extra):456 session.close()457458 from flask import request_tearing_down459 request_tearing_down.connect(close_db_connection, app)460461 As of Flask 0.9, this will also be passed an `exc` keyword argument462 that has a reference to the exception that caused the teardown if463 there was one.464465.. data:: appcontext_tearing_down466467 This signal is sent when the app context is tearing down. This is always468 called, even if an exception is caused. Currently functions listening469 to this signal are called after the regular teardown handlers, but this470 is not something you can rely on.471472 Example subscriber::473474 def close_db_connection(sender, **extra):475 session.close()476477 from flask import appcontext_tearing_down478 appcontext_tearing_down.connect(close_db_connection, app)479480 This will also be passed an `exc` keyword argument that has a reference481 to the exception that caused the teardown if there was one.482483.. data:: appcontext_pushed484485 This signal is sent when an application context is pushed. The sender486 is the application. This is usually useful for unittests in order to487 temporarily hook in information. For instance it can be used to488 set a resource early onto the `g` object.489490 Example usage::491492 from contextlib import contextmanager493 from flask import appcontext_pushed494495 @contextmanager496 def user_set(app, user):497 def handler(sender, **kwargs):498 g.user = user499 with appcontext_pushed.connected_to(handler, app):500 yield501502 And in the testcode::503504 def test_user_me(self):505 with user_set(app, 'john'):506 c = app.test_client()507 resp = c.get('/users/me')508 assert resp.data == 'username=john'509510 .. versionadded:: 0.10511512.. data:: appcontext_popped513514 This signal is sent when an application context is popped. The sender515 is the application. This usually falls in line with the516 :data:`appcontext_tearing_down` signal.517518 .. versionadded:: 0.10519520521.. data:: message_flashed522523 This signal is sent when the application is flashing a message. The524 messages is sent as `message` keyword argument and the category as525 `category`.526527 Example subscriber::528529 recorded = []530 def record(sender, message, category, **extra):531 recorded.append((message, category))532533 from flask import message_flashed534 message_flashed.connect(record, app)535536 .. versionadded:: 0.10537538.. class:: signals.Namespace539540 An alias for :class:`blinker.base.Namespace` if blinker is available,541 otherwise a dummy class that creates fake signals. This class is542 available for Flask extensions that want to provide the same fallback543 system as Flask itself.544545 .. method:: signal(name, doc=None)546547 Creates a new signal for this namespace if blinker is available,548 otherwise returns a fake signal that has a send method that will549 do nothing but will fail with a :exc:`RuntimeError` for all other550 operations, including connecting.551552553.. _blinker: https://pypi.org/project/blinker/554555556Class-Based Views557-----------------558559.. versionadded:: 0.7560561.. currentmodule:: None562563.. autoclass:: flask.views.View564 :members:565566.. autoclass:: flask.views.MethodView567 :members:568569.. _url-route-registrations:570571URL Route Registrations572-----------------------573574Generally there are three ways to define rules for the routing system:5755761. You can use the :meth:`flask.Flask.route` decorator.5772. You can use the :meth:`flask.Flask.add_url_rule` function.5783. You can directly access the underlying Werkzeug routing system579 which is exposed as :attr:`flask.Flask.url_map`.580581Variable parts in the route can be specified with angular brackets582(``/user/<username>``). By default a variable part in the URL accepts any583string without a slash however a different converter can be specified as584well by using ``<converter:name>``.585586Variable parts are passed to the view function as keyword arguments.587588The following converters are available:589590=========== ===============================================591`string` accepts any text without a slash (the default)592`int` accepts integers593`float` like `int` but for floating point values594`path` like the default but also accepts slashes595`any` matches one of the items provided596`uuid` accepts UUID strings597=========== ===============================================598599Custom converters can be defined using :attr:`flask.Flask.url_map`.600601Here are some examples::602603 @app.route('/')604 def index():605 pass606607 @app.route('/<username>')608 def show_user(username):609 pass610611 @app.route('/post/<int:post_id>')612 def show_post(post_id):613 pass614615An important detail to keep in mind is how Flask deals with trailing616slashes. The idea is to keep each URL unique so the following rules617apply:6186191. If a rule ends with a slash and is requested without a slash by the620 user, the user is automatically redirected to the same page with a621 trailing slash attached.6222. If a rule does not end with a trailing slash and the user requests the623 page with a trailing slash, a 404 not found is raised.624625This is consistent with how web servers deal with static files. This626also makes it possible to use relative link targets safely.627628You can also define multiple rules for the same function. They have to be629unique however. Defaults can also be specified. Here for example is a630definition for a URL that accepts an optional page::631632 @app.route('/users/', defaults={'page': 1})633 @app.route('/users/page/<int:page>')634 def show_users(page):635 pass636637This specifies that ``/users/`` will be the URL for page one and638``/users/page/N`` will be the URL for page ``N``.639640If a URL contains a default value, it will be redirected to its simpler641form with a 301 redirect. In the above example, ``/users/page/1`` will642be redirected to ``/users/``. If your route handles ``GET`` and ``POST``643requests, make sure the default route only handles ``GET``, as redirects644can't preserve form data. ::645646 @app.route('/region/', defaults={'id': 1})647 @app.route('/region/<int:id>', methods=['GET', 'POST'])648 def region(id):649 pass650651Here are the parameters that :meth:`~flask.Flask.route` and652:meth:`~flask.Flask.add_url_rule` accept. The only difference is that653with the route parameter the view function is defined with the decorator654instead of the `view_func` parameter.655656=============== ==========================================================657`rule` the URL rule as string658`endpoint` the endpoint for the registered URL rule. Flask itself659 assumes that the name of the view function is the name660 of the endpoint if not explicitly stated.661`view_func` the function to call when serving a request to the662 provided endpoint. If this is not provided one can663 specify the function later by storing it in the664 :attr:`~flask.Flask.view_functions` dictionary with the665 endpoint as key.666`defaults` A dictionary with defaults for this rule. See the667 example above for how defaults work.668`subdomain` specifies the rule for the subdomain in case subdomain669 matching is in use. If not specified the default670 subdomain is assumed.671`**options` the options to be forwarded to the underlying672 :class:`~werkzeug.routing.Rule` object. A change to673 Werkzeug is handling of method options. methods is a list674 of methods this rule should be limited to (``GET``, ``POST``675 etc.). By default a rule just listens for ``GET`` (and676 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is677 implicitly added and handled by the standard request678 handling. They have to be specified as keyword arguments.679=============== ==========================================================680681682View Function Options683---------------------684685For internal usage the view functions can have some attributes attached to686customize behavior the view function would normally not have control over.687The following attributes can be provided optionally to either override688some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:689690- `__name__`: The name of a function is by default used as endpoint. If691 endpoint is provided explicitly this value is used. Additionally this692 will be prefixed with the name of the blueprint by default which693 cannot be customized from the function itself.694695- `methods`: If methods are not provided when the URL rule is added,696 Flask will look on the view function object itself if a `methods`697 attribute exists. If it does, it will pull the information for the698 methods from there.699700- `provide_automatic_options`: if this attribute is set Flask will701 either force enable or disable the automatic implementation of the702 HTTP ``OPTIONS`` response. This can be useful when working with703 decorators that want to customize the ``OPTIONS`` response on a per-view704 basis.705706- `required_methods`: if this attribute is set, Flask will always add707 these methods when registering a URL rule even if the methods were708 explicitly overridden in the ``route()`` call.709710Full example::711712 def index():713 if request.method == 'OPTIONS':714 # custom options handling here715 ...716 return 'Hello World!'717 index.provide_automatic_options = False718 index.methods = ['GET', 'OPTIONS']719720 app.add_url_rule('/', index)721722.. versionadded:: 0.8723 The `provide_automatic_options` functionality was added.724725Command Line Interface726----------------------727728.. currentmodule:: flask.cli729730.. autoclass:: FlaskGroup731 :members:732733.. autoclass:: AppGroup734 :members:735736.. autoclass:: ScriptInfo737 :members:738739.. autofunction:: load_dotenv740741.. autofunction:: with_appcontext742743.. autofunction:: pass_script_info744745 Marks a function so that an instance of :class:`ScriptInfo` is passed746 as first argument to the click callback.747748.. autodata:: run_command749750.. autodata:: shell_command