api.rst
This file
Path
docs/api.rst
775 lines · 22.7 KiB
Last changed by
Merge pull request #4190 from yuxiaoy1/docsDavid Lordbefore adoptiona0afb6f
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 ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer129 starting with Flask 0.8. Either catch this down yourself or use130 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the131 app which converts the result to an integer automatically.132133134Test Client135-----------136137.. currentmodule:: flask.testing138139.. autoclass:: FlaskClient140 :members:141142143Test CLI Runner144---------------145146.. currentmodule:: flask.testing147148.. autoclass:: FlaskCliRunner149 :members:150151152Application Globals153-------------------154155.. currentmodule:: flask156157To share data that is valid for one request only from one function to158another, a global variable is not good enough because it would break in159threaded environments. Flask provides you with a special object that160ensures it is only valid for the active request and that will return161different values for each request. In a nutshell: it does the right162thing, like it does for :class:`request` and :class:`session`.163164.. data:: g165166 A namespace object that can store data during an167 :doc:`application context </appcontext>`. This is an instance of168 :attr:`Flask.app_ctx_globals_class`, which defaults to169 :class:`ctx._AppCtxGlobals`.170171 This is a good place to store resources during a request. During172 testing, you can use the :ref:`faking-resources` pattern to173 pre-configure such resources.174175 This is a proxy. See :ref:`notes-on-proxies` for more information.176177 .. versionchanged:: 0.10178 Bound to the application context instead of the request context.179180.. autoclass:: flask.ctx._AppCtxGlobals181 :members:182183184Useful Functions and Classes185----------------------------186187.. data:: current_app188189 A proxy to the application handling the current request. This is190 useful to access the application without needing to import it, or if191 it can't be imported, such as when using the application factory192 pattern or in blueprints and extensions.193194 This is only available when an195 :doc:`application context </appcontext>` is pushed. This happens196 automatically during requests and CLI commands. It can be controlled197 manually with :meth:`~flask.Flask.app_context`.198199 This is a proxy. See :ref:`notes-on-proxies` for more information.200201.. autofunction:: has_request_context202203.. autofunction:: copy_current_request_context204205.. autofunction:: has_app_context206207.. autofunction:: url_for208209.. autofunction:: abort210211.. autofunction:: redirect212213.. autofunction:: make_response214215.. autofunction:: after_this_request216217.. autofunction:: send_file218219.. autofunction:: send_from_directory220221.. autofunction:: safe_join222223.. autofunction:: escape224225.. autoclass:: Markup226 :members: escape, unescape, striptags227228Message Flashing229----------------230231.. autofunction:: flash232233.. autofunction:: get_flashed_messages234235236JSON Support237------------238239.. module:: flask.json240241Flask uses the built-in :mod:`json` module for handling JSON. It will242use the current blueprint's or application's JSON encoder and decoder243for easier customization. By default it handles some extra data types:244245- :class:`datetime.datetime` and :class:`datetime.date` are serialized246 to :rfc:`822` strings. This is the same as the HTTP date format.247- :class:`uuid.UUID` is serialized to a string.248- :class:`dataclasses.dataclass` is passed to249 :func:`dataclasses.asdict`.250- :class:`~markupsafe.Markup` (or any object with a ``__html__``251 method) will call the ``__html__`` method to get a string.252253Jinja's ``|tojson`` filter is configured to use Flask's :func:`dumps`254function. The filter marks the output with ``|safe`` automatically. Use255the filter to render data inside ``<script>`` tags.256257.. sourcecode:: html+jinja258259 <script>260 const names = {{ names|tosjon }};261 renderChart(names, {{ axis_data|tojson }});262 </script>263264.. autofunction:: jsonify265266.. autofunction:: dumps267268.. autofunction:: dump269270.. autofunction:: loads271272.. autofunction:: load273274.. autoclass:: JSONEncoder275 :members:276277.. autoclass:: JSONDecoder278 :members:279280.. automodule:: flask.json.tag281282283Template Rendering284------------------285286.. currentmodule:: flask287288.. autofunction:: render_template289290.. autofunction:: render_template_string291292.. autofunction:: get_template_attribute293294Configuration295-------------296297.. autoclass:: Config298 :members:299300301Stream Helpers302--------------303304.. autofunction:: stream_with_context305306Useful Internals307----------------308309.. autoclass:: flask.ctx.RequestContext310 :members:311312.. data:: _request_ctx_stack313314 The internal :class:`~werkzeug.local.LocalStack` that holds315 :class:`~flask.ctx.RequestContext` instances. Typically, the316 :data:`request` and :data:`session` proxies should be accessed317 instead of the stack. It may be useful to access the stack in318 extension code.319320 The following attributes are always present on each layer of the321 stack:322323 `app`324 the active Flask application.325326 `url_adapter`327 the URL adapter that was used to match the request.328329 `request`330 the current request object.331332 `session`333 the active session object.334335 `g`336 an object with all the attributes of the :data:`flask.g` object.337338 `flashes`339 an internal cache for the flashed messages.340341 Example usage::342343 from flask import _request_ctx_stack344345 def get_session():346 ctx = _request_ctx_stack.top347 if ctx is not None:348 return ctx.session349350.. autoclass:: flask.ctx.AppContext351 :members:352353.. data:: _app_ctx_stack354355 The internal :class:`~werkzeug.local.LocalStack` that holds356 :class:`~flask.ctx.AppContext` instances. Typically, the357 :data:`current_app` and :data:`g` proxies should be accessed instead358 of the stack. Extensions can access the contexts on the stack as a359 namespace to store data.360361 .. versionadded:: 0.9362363.. autoclass:: flask.blueprints.BlueprintSetupState364 :members:365366.. _core-signals-list:367368Signals369-------370371.. versionadded:: 0.6372373.. data:: signals.signals_available374375 ``True`` if the signaling system is available. This is the case376 when `blinker`_ is installed.377378The following signals exist in Flask:379380.. data:: template_rendered381382 This signal is sent when a template was successfully rendered. The383 signal is invoked with the instance of the template as `template`384 and the context as dictionary (named `context`).385386 Example subscriber::387388 def log_template_renders(sender, template, context, **extra):389 sender.logger.debug('Rendering template "%s" with context %s',390 template.name or 'string template',391 context)392393 from flask import template_rendered394 template_rendered.connect(log_template_renders, app)395396.. data:: flask.before_render_template397 :noindex:398399 This signal is sent before template rendering process. The400 signal is invoked with the instance of the template as `template`401 and the context as dictionary (named `context`).402403 Example subscriber::404405 def log_template_renders(sender, template, context, **extra):406 sender.logger.debug('Rendering template "%s" with context %s',407 template.name or 'string template',408 context)409410 from flask import before_render_template411 before_render_template.connect(log_template_renders, app)412413.. data:: request_started414415 This signal is sent when the request context is set up, before416 any request processing happens. Because the request context is already417 bound, the subscriber can access the request with the standard global418 proxies such as :class:`~flask.request`.419420 Example subscriber::421422 def log_request(sender, **extra):423 sender.logger.debug('Request context is set up')424425 from flask import request_started426 request_started.connect(log_request, app)427428.. data:: request_finished429430 This signal is sent right before the response is sent to the client.431 It is passed the response to be sent named `response`.432433 Example subscriber::434435 def log_response(sender, response, **extra):436 sender.logger.debug('Request context is about to close down. '437 'Response: %s', response)438439 from flask import request_finished440 request_finished.connect(log_response, app)441442.. data:: got_request_exception443444 This signal is sent when an unhandled exception happens during445 request processing, including when debugging. The exception is446 passed to the subscriber as ``exception``.447448 This signal is not sent for449 :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that450 have error handlers registered, unless the exception was raised from451 an error handler.452453 This example shows how to do some extra logging if a theoretical454 ``SecurityException`` was raised:455456 .. code-block:: python457458 from flask import got_request_exception459460 def log_security_exception(sender, exception, **extra):461 if not isinstance(exception, SecurityException):462 return463464 security_logger.exception(465 f"SecurityException at {request.url!r}",466 exc_info=exception,467 )468469 got_request_exception.connect(log_security_exception, app)470471.. data:: request_tearing_down472473 This signal is sent when the request is tearing down. This is always474 called, even if an exception is caused. Currently functions listening475 to this signal are called after the regular teardown handlers, but this476 is not something you can rely on.477478 Example subscriber::479480 def close_db_connection(sender, **extra):481 session.close()482483 from flask import request_tearing_down484 request_tearing_down.connect(close_db_connection, app)485486 As of Flask 0.9, this will also be passed an `exc` keyword argument487 that has a reference to the exception that caused the teardown if488 there was one.489490.. data:: appcontext_tearing_down491492 This signal is sent when the app context is tearing down. This is always493 called, even if an exception is caused. Currently functions listening494 to this signal are called after the regular teardown handlers, but this495 is not something you can rely on.496497 Example subscriber::498499 def close_db_connection(sender, **extra):500 session.close()501502 from flask import appcontext_tearing_down503 appcontext_tearing_down.connect(close_db_connection, app)504505 This will also be passed an `exc` keyword argument that has a reference506 to the exception that caused the teardown if there was one.507508.. data:: appcontext_pushed509510 This signal is sent when an application context is pushed. The sender511 is the application. This is usually useful for unittests in order to512 temporarily hook in information. For instance it can be used to513 set a resource early onto the `g` object.514515 Example usage::516517 from contextlib import contextmanager518 from flask import appcontext_pushed519520 @contextmanager521 def user_set(app, user):522 def handler(sender, **kwargs):523 g.user = user524 with appcontext_pushed.connected_to(handler, app):525 yield526527 And in the testcode::528529 def test_user_me(self):530 with user_set(app, 'john'):531 c = app.test_client()532 resp = c.get('/users/me')533 assert resp.data == 'username=john'534535 .. versionadded:: 0.10536537.. data:: appcontext_popped538539 This signal is sent when an application context is popped. The sender540 is the application. This usually falls in line with the541 :data:`appcontext_tearing_down` signal.542543 .. versionadded:: 0.10544545546.. data:: message_flashed547548 This signal is sent when the application is flashing a message. The549 messages is sent as `message` keyword argument and the category as550 `category`.551552 Example subscriber::553554 recorded = []555 def record(sender, message, category, **extra):556 recorded.append((message, category))557558 from flask import message_flashed559 message_flashed.connect(record, app)560561 .. versionadded:: 0.10562563.. class:: signals.Namespace564565 An alias for :class:`blinker.base.Namespace` if blinker is available,566 otherwise a dummy class that creates fake signals. This class is567 available for Flask extensions that want to provide the same fallback568 system as Flask itself.569570 .. method:: signal(name, doc=None)571572 Creates a new signal for this namespace if blinker is available,573 otherwise returns a fake signal that has a send method that will574 do nothing but will fail with a :exc:`RuntimeError` for all other575 operations, including connecting.576577578.. _blinker: https://pypi.org/project/blinker/579580581Class-Based Views582-----------------583584.. versionadded:: 0.7585586.. currentmodule:: None587588.. autoclass:: flask.views.View589 :members:590591.. autoclass:: flask.views.MethodView592 :members:593594.. _url-route-registrations:595596URL Route Registrations597-----------------------598599Generally there are three ways to define rules for the routing system:6006011. You can use the :meth:`flask.Flask.route` decorator.6022. You can use the :meth:`flask.Flask.add_url_rule` function.6033. You can directly access the underlying Werkzeug routing system604 which is exposed as :attr:`flask.Flask.url_map`.605606Variable parts in the route can be specified with angular brackets607(``/user/<username>``). By default a variable part in the URL accepts any608string without a slash however a different converter can be specified as609well by using ``<converter:name>``.610611Variable parts are passed to the view function as keyword arguments.612613The following converters are available:614615=========== ===============================================616`string` accepts any text without a slash (the default)617`int` accepts integers618`float` like `int` but for floating point values619`path` like the default but also accepts slashes620`any` matches one of the items provided621`uuid` accepts UUID strings622=========== ===============================================623624Custom converters can be defined using :attr:`flask.Flask.url_map`.625626Here are some examples::627628 @app.route('/')629 def index():630 pass631632 @app.route('/<username>')633 def show_user(username):634 pass635636 @app.route('/post/<int:post_id>')637 def show_post(post_id):638 pass639640An important detail to keep in mind is how Flask deals with trailing641slashes. The idea is to keep each URL unique so the following rules642apply:6436441. If a rule ends with a slash and is requested without a slash by the645 user, the user is automatically redirected to the same page with a646 trailing slash attached.6472. If a rule does not end with a trailing slash and the user requests the648 page with a trailing slash, a 404 not found is raised.649650This is consistent with how web servers deal with static files. This651also makes it possible to use relative link targets safely.652653You can also define multiple rules for the same function. They have to be654unique however. Defaults can also be specified. Here for example is a655definition for a URL that accepts an optional page::656657 @app.route('/users/', defaults={'page': 1})658 @app.route('/users/page/<int:page>')659 def show_users(page):660 pass661662This specifies that ``/users/`` will be the URL for page one and663``/users/page/N`` will be the URL for page ``N``.664665If a URL contains a default value, it will be redirected to its simpler666form with a 301 redirect. In the above example, ``/users/page/1`` will667be redirected to ``/users/``. If your route handles ``GET`` and ``POST``668requests, make sure the default route only handles ``GET``, as redirects669can't preserve form data. ::670671 @app.route('/region/', defaults={'id': 1})672 @app.route('/region/<int:id>', methods=['GET', 'POST'])673 def region(id):674 pass675676Here are the parameters that :meth:`~flask.Flask.route` and677:meth:`~flask.Flask.add_url_rule` accept. The only difference is that678with the route parameter the view function is defined with the decorator679instead of the `view_func` parameter.680681=============== ==========================================================682`rule` the URL rule as string683`endpoint` the endpoint for the registered URL rule. Flask itself684 assumes that the name of the view function is the name685 of the endpoint if not explicitly stated.686`view_func` the function to call when serving a request to the687 provided endpoint. If this is not provided one can688 specify the function later by storing it in the689 :attr:`~flask.Flask.view_functions` dictionary with the690 endpoint as key.691`defaults` A dictionary with defaults for this rule. See the692 example above for how defaults work.693`subdomain` specifies the rule for the subdomain in case subdomain694 matching is in use. If not specified the default695 subdomain is assumed.696`**options` the options to be forwarded to the underlying697 :class:`~werkzeug.routing.Rule` object. A change to698 Werkzeug is handling of method options. methods is a list699 of methods this rule should be limited to (``GET``, ``POST``700 etc.). By default a rule just listens for ``GET`` (and701 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is702 implicitly added and handled by the standard request703 handling. They have to be specified as keyword arguments.704=============== ==========================================================705706707View Function Options708---------------------709710For internal usage the view functions can have some attributes attached to711customize behavior the view function would normally not have control over.712The following attributes can be provided optionally to either override713some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:714715- `__name__`: The name of a function is by default used as endpoint. If716 endpoint is provided explicitly this value is used. Additionally this717 will be prefixed with the name of the blueprint by default which718 cannot be customized from the function itself.719720- `methods`: If methods are not provided when the URL rule is added,721 Flask will look on the view function object itself if a `methods`722 attribute exists. If it does, it will pull the information for the723 methods from there.724725- `provide_automatic_options`: if this attribute is set Flask will726 either force enable or disable the automatic implementation of the727 HTTP ``OPTIONS`` response. This can be useful when working with728 decorators that want to customize the ``OPTIONS`` response on a per-view729 basis.730731- `required_methods`: if this attribute is set, Flask will always add732 these methods when registering a URL rule even if the methods were733 explicitly overridden in the ``route()`` call.734735Full example::736737 def index():738 if request.method == 'OPTIONS':739 # custom options handling here740 ...741 return 'Hello World!'742 index.provide_automatic_options = False743 index.methods = ['GET', 'OPTIONS']744745 app.add_url_rule('/', index)746747.. versionadded:: 0.8748 The `provide_automatic_options` functionality was added.749750Command Line Interface751----------------------752753.. currentmodule:: flask.cli754755.. autoclass:: FlaskGroup756 :members:757758.. autoclass:: AppGroup759 :members:760761.. autoclass:: ScriptInfo762 :members:763764.. autofunction:: load_dotenv765766.. autofunction:: with_appcontext767768.. autofunction:: pass_script_info769770 Marks a function so that an instance of :class:`ScriptInfo` is passed771 as first argument to the click callback.772773.. autodata:: run_command774775.. autodata:: shell_command