api.rst
This file
Path
docs/api.rst
740 lines · 21.9 KiB
Last changed by
Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
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_directory219220221Message Flashing222----------------223224.. autofunction:: flash225226.. autofunction:: get_flashed_messages227228229JSON Support230------------231232.. module:: flask.json233234Flask uses Python's built-in :mod:`json` module for handling JSON by235default. The JSON implementation can be changed by assigning a different236provider to :attr:`flask.Flask.json_provider_class` or237:attr:`flask.Flask.json`. The functions provided by ``flask.json`` will238use methods on ``app.json`` if an app context is active.239240Jinja's ``|tojson`` filter is configured to use the app's JSON provider.241The filter marks the output with ``|safe``. Use it to render data inside242HTML ``<script>`` tags.243244.. sourcecode:: html+jinja245246 <script>247 const names = {{ names|tojson }};248 renderChart(names, {{ axis_data|tojson }});249 </script>250251.. autofunction:: jsonify252253.. autofunction:: dumps254255.. autofunction:: dump256257.. autofunction:: loads258259.. autofunction:: load260261.. autoclass:: flask.json.provider.JSONProvider262 :members:263 :member-order: bysource264265.. autoclass:: flask.json.provider.DefaultJSONProvider266 :members:267 :member-order: bysource268269.. automodule:: flask.json.tag270271272Template Rendering273------------------274275.. currentmodule:: flask276277.. autofunction:: render_template278279.. autofunction:: render_template_string280281.. autofunction:: stream_template282283.. autofunction:: stream_template_string284285.. autofunction:: get_template_attribute286287Configuration288-------------289290.. autoclass:: Config291 :members:292293294Stream Helpers295--------------296297.. autofunction:: stream_with_context298299Useful Internals300----------------301302.. autoclass:: flask.ctx.RequestContext303 :members:304305.. data:: flask.globals.request_ctx306307 The current :class:`~flask.ctx.RequestContext`. If a request context308 is not active, accessing attributes on this proxy will raise a309 ``RuntimeError``.310311 This is an internal object that is essential to how Flask handles312 requests. Accessing this should not be needed in most cases. Most313 likely you want :data:`request` and :data:`session` instead.314315.. autoclass:: flask.ctx.AppContext316 :members:317318.. data:: flask.globals.app_ctx319320 The current :class:`~flask.ctx.AppContext`. If an app context is not321 active, accessing attributes on this proxy will raise a322 ``RuntimeError``.323324 This is an internal object that is essential to how Flask handles325 requests. Accessing this should not be needed in most cases. Most326 likely you want :data:`current_app` and :data:`g` instead.327328.. autoclass:: flask.blueprints.BlueprintSetupState329 :members:330331.. _core-signals-list:332333Signals334-------335336.. versionadded:: 0.6337338.. data:: signals.signals_available339340 ``True`` if the signaling system is available. This is the case341 when `blinker`_ is installed.342343The following signals exist in Flask:344345.. data:: template_rendered346347 This signal is sent when a template was successfully rendered. The348 signal is invoked with the instance of the template as `template`349 and the context as dictionary (named `context`).350351 Example subscriber::352353 def log_template_renders(sender, template, context, **extra):354 sender.logger.debug('Rendering template "%s" with context %s',355 template.name or 'string template',356 context)357358 from flask import template_rendered359 template_rendered.connect(log_template_renders, app)360361.. data:: flask.before_render_template362 :noindex:363364 This signal is sent before template rendering process. The365 signal is invoked with the instance of the template as `template`366 and the context as dictionary (named `context`).367368 Example subscriber::369370 def log_template_renders(sender, template, context, **extra):371 sender.logger.debug('Rendering template "%s" with context %s',372 template.name or 'string template',373 context)374375 from flask import before_render_template376 before_render_template.connect(log_template_renders, app)377378.. data:: request_started379380 This signal is sent when the request context is set up, before381 any request processing happens. Because the request context is already382 bound, the subscriber can access the request with the standard global383 proxies such as :class:`~flask.request`.384385 Example subscriber::386387 def log_request(sender, **extra):388 sender.logger.debug('Request context is set up')389390 from flask import request_started391 request_started.connect(log_request, app)392393.. data:: request_finished394395 This signal is sent right before the response is sent to the client.396 It is passed the response to be sent named `response`.397398 Example subscriber::399400 def log_response(sender, response, **extra):401 sender.logger.debug('Request context is about to close down. '402 'Response: %s', response)403404 from flask import request_finished405 request_finished.connect(log_response, app)406407.. data:: got_request_exception408409 This signal is sent when an unhandled exception happens during410 request processing, including when debugging. The exception is411 passed to the subscriber as ``exception``.412413 This signal is not sent for414 :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that415 have error handlers registered, unless the exception was raised from416 an error handler.417418 This example shows how to do some extra logging if a theoretical419 ``SecurityException`` was raised:420421 .. code-block:: python422423 from flask import got_request_exception424425 def log_security_exception(sender, exception, **extra):426 if not isinstance(exception, SecurityException):427 return428429 security_logger.exception(430 f"SecurityException at {request.url!r}",431 exc_info=exception,432 )433434 got_request_exception.connect(log_security_exception, app)435436.. data:: request_tearing_down437438 This signal is sent when the request is tearing down. This is always439 called, even if an exception is caused. Currently functions listening440 to this signal are called after the regular teardown handlers, but this441 is not something you can rely on.442443 Example subscriber::444445 def close_db_connection(sender, **extra):446 session.close()447448 from flask import request_tearing_down449 request_tearing_down.connect(close_db_connection, app)450451 As of Flask 0.9, this will also be passed an `exc` keyword argument452 that has a reference to the exception that caused the teardown if453 there was one.454455.. data:: appcontext_tearing_down456457 This signal is sent when the app context is tearing down. This is always458 called, even if an exception is caused. Currently functions listening459 to this signal are called after the regular teardown handlers, but this460 is not something you can rely on.461462 Example subscriber::463464 def close_db_connection(sender, **extra):465 session.close()466467 from flask import appcontext_tearing_down468 appcontext_tearing_down.connect(close_db_connection, app)469470 This will also be passed an `exc` keyword argument that has a reference471 to the exception that caused the teardown if there was one.472473.. data:: appcontext_pushed474475 This signal is sent when an application context is pushed. The sender476 is the application. This is usually useful for unittests in order to477 temporarily hook in information. For instance it can be used to478 set a resource early onto the `g` object.479480 Example usage::481482 from contextlib import contextmanager483 from flask import appcontext_pushed484485 @contextmanager486 def user_set(app, user):487 def handler(sender, **kwargs):488 g.user = user489 with appcontext_pushed.connected_to(handler, app):490 yield491492 And in the testcode::493494 def test_user_me(self):495 with user_set(app, 'john'):496 c = app.test_client()497 resp = c.get('/users/me')498 assert resp.data == 'username=john'499500 .. versionadded:: 0.10501502.. data:: appcontext_popped503504 This signal is sent when an application context is popped. The sender505 is the application. This usually falls in line with the506 :data:`appcontext_tearing_down` signal.507508 .. versionadded:: 0.10509510511.. data:: message_flashed512513 This signal is sent when the application is flashing a message. The514 messages is sent as `message` keyword argument and the category as515 `category`.516517 Example subscriber::518519 recorded = []520 def record(sender, message, category, **extra):521 recorded.append((message, category))522523 from flask import message_flashed524 message_flashed.connect(record, app)525526 .. versionadded:: 0.10527528.. class:: signals.Namespace529530 An alias for :class:`blinker.base.Namespace` if blinker is available,531 otherwise a dummy class that creates fake signals. This class is532 available for Flask extensions that want to provide the same fallback533 system as Flask itself.534535 .. method:: signal(name, doc=None)536537 Creates a new signal for this namespace if blinker is available,538 otherwise returns a fake signal that has a send method that will539 do nothing but will fail with a :exc:`RuntimeError` for all other540 operations, including connecting.541542543.. _blinker: https://pypi.org/project/blinker/544545546Class-Based Views547-----------------548549.. versionadded:: 0.7550551.. currentmodule:: None552553.. autoclass:: flask.views.View554 :members:555556.. autoclass:: flask.views.MethodView557 :members:558559.. _url-route-registrations:560561URL Route Registrations562-----------------------563564Generally there are three ways to define rules for the routing system:5655661. You can use the :meth:`flask.Flask.route` decorator.5672. You can use the :meth:`flask.Flask.add_url_rule` function.5683. You can directly access the underlying Werkzeug routing system569 which is exposed as :attr:`flask.Flask.url_map`.570571Variable parts in the route can be specified with angular brackets572(``/user/<username>``). By default a variable part in the URL accepts any573string without a slash however a different converter can be specified as574well by using ``<converter:name>``.575576Variable parts are passed to the view function as keyword arguments.577578The following converters are available:579580=========== ===============================================581`string` accepts any text without a slash (the default)582`int` accepts integers583`float` like `int` but for floating point values584`path` like the default but also accepts slashes585`any` matches one of the items provided586`uuid` accepts UUID strings587=========== ===============================================588589Custom converters can be defined using :attr:`flask.Flask.url_map`.590591Here are some examples::592593 @app.route('/')594 def index():595 pass596597 @app.route('/<username>')598 def show_user(username):599 pass600601 @app.route('/post/<int:post_id>')602 def show_post(post_id):603 pass604605An important detail to keep in mind is how Flask deals with trailing606slashes. The idea is to keep each URL unique so the following rules607apply:6086091. If a rule ends with a slash and is requested without a slash by the610 user, the user is automatically redirected to the same page with a611 trailing slash attached.6122. If a rule does not end with a trailing slash and the user requests the613 page with a trailing slash, a 404 not found is raised.614615This is consistent with how web servers deal with static files. This616also makes it possible to use relative link targets safely.617618You can also define multiple rules for the same function. They have to be619unique however. Defaults can also be specified. Here for example is a620definition for a URL that accepts an optional page::621622 @app.route('/users/', defaults={'page': 1})623 @app.route('/users/page/<int:page>')624 def show_users(page):625 pass626627This specifies that ``/users/`` will be the URL for page one and628``/users/page/N`` will be the URL for page ``N``.629630If a URL contains a default value, it will be redirected to its simpler631form with a 301 redirect. In the above example, ``/users/page/1`` will632be redirected to ``/users/``. If your route handles ``GET`` and ``POST``633requests, make sure the default route only handles ``GET``, as redirects634can't preserve form data. ::635636 @app.route('/region/', defaults={'id': 1})637 @app.route('/region/<int:id>', methods=['GET', 'POST'])638 def region(id):639 pass640641Here are the parameters that :meth:`~flask.Flask.route` and642:meth:`~flask.Flask.add_url_rule` accept. The only difference is that643with the route parameter the view function is defined with the decorator644instead of the `view_func` parameter.645646=============== ==========================================================647`rule` the URL rule as string648`endpoint` the endpoint for the registered URL rule. Flask itself649 assumes that the name of the view function is the name650 of the endpoint if not explicitly stated.651`view_func` the function to call when serving a request to the652 provided endpoint. If this is not provided one can653 specify the function later by storing it in the654 :attr:`~flask.Flask.view_functions` dictionary with the655 endpoint as key.656`defaults` A dictionary with defaults for this rule. See the657 example above for how defaults work.658`subdomain` specifies the rule for the subdomain in case subdomain659 matching is in use. If not specified the default660 subdomain is assumed.661`**options` the options to be forwarded to the underlying662 :class:`~werkzeug.routing.Rule` object. A change to663 Werkzeug is handling of method options. methods is a list664 of methods this rule should be limited to (``GET``, ``POST``665 etc.). By default a rule just listens for ``GET`` (and666 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is667 implicitly added and handled by the standard request668 handling. They have to be specified as keyword arguments.669=============== ==========================================================670671672View Function Options673---------------------674675For internal usage the view functions can have some attributes attached to676customize behavior the view function would normally not have control over.677The following attributes can be provided optionally to either override678some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:679680- `__name__`: The name of a function is by default used as endpoint. If681 endpoint is provided explicitly this value is used. Additionally this682 will be prefixed with the name of the blueprint by default which683 cannot be customized from the function itself.684685- `methods`: If methods are not provided when the URL rule is added,686 Flask will look on the view function object itself if a `methods`687 attribute exists. If it does, it will pull the information for the688 methods from there.689690- `provide_automatic_options`: if this attribute is set Flask will691 either force enable or disable the automatic implementation of the692 HTTP ``OPTIONS`` response. This can be useful when working with693 decorators that want to customize the ``OPTIONS`` response on a per-view694 basis.695696- `required_methods`: if this attribute is set, Flask will always add697 these methods when registering a URL rule even if the methods were698 explicitly overridden in the ``route()`` call.699700Full example::701702 def index():703 if request.method == 'OPTIONS':704 # custom options handling here705 ...706 return 'Hello World!'707 index.provide_automatic_options = False708 index.methods = ['GET', 'OPTIONS']709710 app.add_url_rule('/', index)711712.. versionadded:: 0.8713 The `provide_automatic_options` functionality was added.714715Command Line Interface716----------------------717718.. currentmodule:: flask.cli719720.. autoclass:: FlaskGroup721 :members:722723.. autoclass:: AppGroup724 :members:725726.. autoclass:: ScriptInfo727 :members:728729.. autofunction:: load_dotenv730731.. autofunction:: with_appcontext732733.. autofunction:: pass_script_info734735 Marks a function so that an instance of :class:`ScriptInfo` is passed736 as first argument to the click callback.737738.. autodata:: run_command739740.. autodata:: shell_command