api.rst
This file
Path
docs/api.rst
834 lines · 24.7 KiB
Last changed by
Merge pull request #3408 from lamby/943674-flask-please-make-the-build-reproducibleDavid Lordbefore adoption1234eb0
History of this fileTake it
1.. _api:23API4===56.. module:: flask78This part of the documentation covers all the interfaces of Flask. For9parts where Flask depends on external libraries, we document the most10important right here and provide links to the canonical documentation.111213Application Object14------------------1516.. autoclass:: Flask17 :members:18 :inherited-members:192021Blueprint Objects22-----------------2324.. autoclass:: Blueprint25 :members:26 :inherited-members:2728Incoming Request Data29---------------------3031.. autoclass:: Request32 :members:33 :inherited-members:34 :exclude-members: json_module3536 .. attribute:: environ3738 The underlying WSGI environment.3940 .. attribute:: path41 .. attribute:: full_path42 .. attribute:: script_root43 .. attribute:: url44 .. attribute:: base_url45 .. attribute:: url_root4647 Provides different ways to look at the current :rfc:`3987`.48 Imagine your application is listening on the following application49 root::5051 http://www.example.com/myapplication5253 And a user requests the following URI::5455 http://www.example.com/myapplication/%CF%80/page.html?x=y5657 In this case the values of the above mentioned attributes would be58 the following:5960 ============= ======================================================61 `path` ``u'/π/page.html'``62 `full_path` ``u'/π/page.html?x=y'``63 `script_root` ``u'/myapplication'``64 `base_url` ``u'http://www.example.com/myapplication/π/page.html'``65 `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``66 `url_root` ``u'http://www.example.com/myapplication/'``67 ============= ======================================================686970.. attribute:: request7172 To access incoming request data, you can use the global `request`73 object. Flask parses incoming request data for you and gives you74 access to it through that global object. Internally Flask makes75 sure that you always get the correct data for the active thread if you76 are in a multithreaded environment.7778 This is a proxy. See :ref:`notes-on-proxies` for more information.7980 The request object is an instance of a :class:`~werkzeug.wrappers.Request`81 subclass and provides all of the attributes Werkzeug defines. This82 just shows a quick overview of the most important ones.838485Response Objects86----------------8788.. autoclass:: flask.Response89 :members: set_cookie, max_cookie_size, data, mimetype, is_json, get_json9091 .. attribute:: headers9293 A :class:`~werkzeug.datastructures.Headers` object representing the response headers.9495 .. attribute:: status9697 A string with a response status.9899 .. attribute:: status_code100101 The response status as integer.102103104Sessions105--------106107If you have set :attr:`Flask.secret_key` (or configured it from108:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes109it possible to remember information from one request to another. The way Flask110does this is by using a signed cookie. The user can look at the session111contents, but can't modify it unless they know the secret key, so make sure to112set that to something complex and unguessable.113114To access the current session you can use the :class:`session` object:115116.. class:: session117118 The session object works pretty much like an ordinary dict, with the119 difference that it keeps track of modifications.120121 This is a proxy. See :ref:`notes-on-proxies` for more information.122123 The following attributes are interesting:124125 .. attribute:: new126127 ``True`` if the session is new, ``False`` otherwise.128129 .. attribute:: modified130131 ``True`` if the session object detected a modification. Be advised132 that modifications on mutable structures are not picked up133 automatically, in that situation you have to explicitly set the134 attribute to ``True`` yourself. Here an example::135136 # this change is not picked up because a mutable object (here137 # a list) is changed.138 session['objects'].append(42)139 # so mark it as modified yourself140 session.modified = True141142 .. attribute:: permanent143144 If set to ``True`` the session lives for145 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The146 default is 31 days. If set to ``False`` (which is the default) the147 session will be deleted when the user closes the browser.148149150Session Interface151-----------------152153.. versionadded:: 0.8154155The session interface provides a simple way to replace the session156implementation that Flask is using.157158.. currentmodule:: flask.sessions159160.. autoclass:: SessionInterface161 :members:162163.. autoclass:: SecureCookieSessionInterface164 :members:165166.. autoclass:: SecureCookieSession167 :members:168169.. autoclass:: NullSession170 :members:171172.. autoclass:: SessionMixin173 :members:174175.. admonition:: Notice176177 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer178 starting with Flask 0.8. Either catch this down yourself or use179 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the180 app which converts the result to an integer automatically.181182183Test Client184-----------185186.. currentmodule:: flask.testing187188.. autoclass:: FlaskClient189 :members:190191192Test CLI Runner193---------------194195.. currentmodule:: flask.testing196197.. autoclass:: FlaskCliRunner198 :members:199200201Application Globals202-------------------203204.. currentmodule:: flask205206To share data that is valid for one request only from one function to207another, a global variable is not good enough because it would break in208threaded environments. Flask provides you with a special object that209ensures it is only valid for the active request and that will return210different values for each request. In a nutshell: it does the right211thing, like it does for :class:`request` and :class:`session`.212213.. data:: g214215 A namespace object that can store data during an216 :doc:`application context </appcontext>`. This is an instance of217 :attr:`Flask.app_ctx_globals_class`, which defaults to218 :class:`ctx._AppCtxGlobals`.219220 This is a good place to store resources during a request. During221 testing, you can use the :ref:`faking-resources` pattern to222 pre-configure such resources.223224 This is a proxy. See :ref:`notes-on-proxies` for more information.225226 .. versionchanged:: 0.10227 Bound to the application context instead of the request context.228229.. autoclass:: flask.ctx._AppCtxGlobals230 :members:231232233Useful Functions and Classes234----------------------------235236.. data:: current_app237238 A proxy to the application handling the current request. This is239 useful to access the application without needing to import it, or if240 it can't be imported, such as when using the application factory241 pattern or in blueprints and extensions.242243 This is only available when an244 :doc:`application context </appcontext>` is pushed. This happens245 automatically during requests and CLI commands. It can be controlled246 manually with :meth:`~flask.Flask.app_context`.247248 This is a proxy. See :ref:`notes-on-proxies` for more information.249250.. autofunction:: has_request_context251252.. autofunction:: copy_current_request_context253254.. autofunction:: has_app_context255256.. autofunction:: url_for257258.. autofunction:: abort259260.. autofunction:: redirect261262.. autofunction:: make_response263264.. autofunction:: after_this_request265266.. autofunction:: send_file267268.. autofunction:: send_from_directory269270.. autofunction:: safe_join271272.. autofunction:: escape273274.. autoclass:: Markup275 :members: escape, unescape, striptags276277Message Flashing278----------------279280.. autofunction:: flash281282.. autofunction:: get_flashed_messages283284JSON Support285------------286287.. module:: flask.json288289Flask uses ``simplejson`` for the JSON implementation. Since simplejson290is provided by both the standard library as well as extension, Flask will291try simplejson first and then fall back to the stdlib json module. On top292of that it will delegate access to the current application's JSON encoders293and decoders for easier customization.294295So for starters instead of doing::296297 try:298 import simplejson as json299 except ImportError:300 import json301302You can instead just do this::303304 from flask import json305306For usage examples, read the :mod:`json` documentation in the standard307library. The following extensions are by default applied to the stdlib's308JSON module:3093101. ``datetime`` objects are serialized as :rfc:`822` strings.3112. Any object with an ``__html__`` method (like :class:`~flask.Markup`)312 will have that method called and then the return value is serialized313 as string.314315The :func:`~htmlsafe_dumps` function of this json module is also available316as a filter called ``|tojson`` in Jinja2. Note that in versions of Flask prior317to Flask 0.10, you must disable escaping with ``|safe`` if you intend to use318``|tojson`` output inside ``script`` tags. In Flask 0.10 and above, this319happens automatically (but it's harmless to include ``|safe`` anyway).320321.. sourcecode:: html+jinja322323 <script type=text/javascript>324 doSomethingWith({{ user.username|tojson|safe }});325 </script>326327.. admonition:: Auto-Sort JSON Keys328329 The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be330 set to false to stop Flask from auto-sorting keys. By default sorting331 is enabled and outside of the app context sorting is turned on.332333 Notice that disabling key sorting can cause issues when using content334 based HTTP caches and Python's hash randomization feature.335336.. autofunction:: jsonify337338.. autofunction:: dumps339340.. autofunction:: dump341342.. autofunction:: loads343344.. autofunction:: load345346.. autoclass:: JSONEncoder347 :members:348349.. autoclass:: JSONDecoder350 :members:351352.. automodule:: flask.json.tag353354Template Rendering355------------------356357.. currentmodule:: flask358359.. autofunction:: render_template360361.. autofunction:: render_template_string362363.. autofunction:: get_template_attribute364365Configuration366-------------367368.. autoclass:: Config369 :members:370371372Stream Helpers373--------------374375.. autofunction:: stream_with_context376377Useful Internals378----------------379380.. autoclass:: flask.ctx.RequestContext381 :members:382383.. data:: _request_ctx_stack384385 The internal :class:`~werkzeug.local.LocalStack` that holds386 :class:`~flask.ctx.RequestContext` instances. Typically, the387 :data:`request` and :data:`session` proxies should be accessed388 instead of the stack. It may be useful to access the stack in389 extension code.390391 The following attributes are always present on each layer of the392 stack:393394 `app`395 the active Flask application.396397 `url_adapter`398 the URL adapter that was used to match the request.399400 `request`401 the current request object.402403 `session`404 the active session object.405406 `g`407 an object with all the attributes of the :data:`flask.g` object.408409 `flashes`410 an internal cache for the flashed messages.411412 Example usage::413414 from flask import _request_ctx_stack415416 def get_session():417 ctx = _request_ctx_stack.top418 if ctx is not None:419 return ctx.session420421.. autoclass:: flask.ctx.AppContext422 :members:423424.. data:: _app_ctx_stack425426 The internal :class:`~werkzeug.local.LocalStack` that holds427 :class:`~flask.ctx.AppContext` instances. Typically, the428 :data:`current_app` and :data:`g` proxies should be accessed instead429 of the stack. Extensions can access the contexts on the stack as a430 namespace to store data.431432 .. versionadded:: 0.9433434.. autoclass:: flask.blueprints.BlueprintSetupState435 :members:436437.. _core-signals-list:438439Signals440-------441442.. versionadded:: 0.6443444.. data:: signals.signals_available445446 ``True`` if the signaling system is available. This is the case447 when `blinker`_ is installed.448449The following signals exist in Flask:450451.. data:: template_rendered452453 This signal is sent when a template was successfully rendered. The454 signal is invoked with the instance of the template as `template`455 and the context as dictionary (named `context`).456457 Example subscriber::458459 def log_template_renders(sender, template, context, **extra):460 sender.logger.debug('Rendering template "%s" with context %s',461 template.name or 'string template',462 context)463464 from flask import template_rendered465 template_rendered.connect(log_template_renders, app)466467.. data:: flask.before_render_template468 :noindex:469470 This signal is sent before template rendering process. The471 signal is invoked with the instance of the template as `template`472 and the context as dictionary (named `context`).473474 Example subscriber::475476 def log_template_renders(sender, template, context, **extra):477 sender.logger.debug('Rendering template "%s" with context %s',478 template.name or 'string template',479 context)480481 from flask import before_render_template482 before_render_template.connect(log_template_renders, app)483484.. data:: request_started485486 This signal is sent when the request context is set up, before487 any request processing happens. Because the request context is already488 bound, the subscriber can access the request with the standard global489 proxies such as :class:`~flask.request`.490491 Example subscriber::492493 def log_request(sender, **extra):494 sender.logger.debug('Request context is set up')495496 from flask import request_started497 request_started.connect(log_request, app)498499.. data:: request_finished500501 This signal is sent right before the response is sent to the client.502 It is passed the response to be sent named `response`.503504 Example subscriber::505506 def log_response(sender, response, **extra):507 sender.logger.debug('Request context is about to close down. '508 'Response: %s', response)509510 from flask import request_finished511 request_finished.connect(log_response, app)512513.. data:: got_request_exception514515 This signal is sent when an exception happens during request processing.516 It is sent *before* the standard exception handling kicks in and even517 in debug mode, where no exception handling happens. The exception518 itself is passed to the subscriber as `exception`.519520 Example subscriber::521522 def log_exception(sender, exception, **extra):523 sender.logger.debug('Got exception during processing: %s', exception)524525 from flask import got_request_exception526 got_request_exception.connect(log_exception, app)527528.. data:: request_tearing_down529530 This signal is sent when the request is tearing down. This is always531 called, even if an exception is caused. Currently functions listening532 to this signal are called after the regular teardown handlers, but this533 is not something you can rely on.534535 Example subscriber::536537 def close_db_connection(sender, **extra):538 session.close()539540 from flask import request_tearing_down541 request_tearing_down.connect(close_db_connection, app)542543 As of Flask 0.9, this will also be passed an `exc` keyword argument544 that has a reference to the exception that caused the teardown if545 there was one.546547.. data:: appcontext_tearing_down548549 This signal is sent when the app context is tearing down. This is always550 called, even if an exception is caused. Currently functions listening551 to this signal are called after the regular teardown handlers, but this552 is not something you can rely on.553554 Example subscriber::555556 def close_db_connection(sender, **extra):557 session.close()558559 from flask import appcontext_tearing_down560 appcontext_tearing_down.connect(close_db_connection, app)561562 This will also be passed an `exc` keyword argument that has a reference563 to the exception that caused the teardown if there was one.564565.. data:: appcontext_pushed566567 This signal is sent when an application context is pushed. The sender568 is the application. This is usually useful for unittests in order to569 temporarily hook in information. For instance it can be used to570 set a resource early onto the `g` object.571572 Example usage::573574 from contextlib import contextmanager575 from flask import appcontext_pushed576577 @contextmanager578 def user_set(app, user):579 def handler(sender, **kwargs):580 g.user = user581 with appcontext_pushed.connected_to(handler, app):582 yield583584 And in the testcode::585586 def test_user_me(self):587 with user_set(app, 'john'):588 c = app.test_client()589 resp = c.get('/users/me')590 assert resp.data == 'username=john'591592 .. versionadded:: 0.10593594.. data:: appcontext_popped595596 This signal is sent when an application context is popped. The sender597 is the application. This usually falls in line with the598 :data:`appcontext_tearing_down` signal.599600 .. versionadded:: 0.10601602603.. data:: message_flashed604605 This signal is sent when the application is flashing a message. The606 messages is sent as `message` keyword argument and the category as607 `category`.608609 Example subscriber::610611 recorded = []612 def record(sender, message, category, **extra):613 recorded.append((message, category))614615 from flask import message_flashed616 message_flashed.connect(record, app)617618 .. versionadded:: 0.10619620.. class:: signals.Namespace621622 An alias for :class:`blinker.base.Namespace` if blinker is available,623 otherwise a dummy class that creates fake signals. This class is624 available for Flask extensions that want to provide the same fallback625 system as Flask itself.626627 .. method:: signal(name, doc=None)628629 Creates a new signal for this namespace if blinker is available,630 otherwise returns a fake signal that has a send method that will631 do nothing but will fail with a :exc:`RuntimeError` for all other632 operations, including connecting.633634635.. _blinker: https://pypi.org/project/blinker/636637.. _class-based-views:638639Class-Based Views640-----------------641642.. versionadded:: 0.7643644.. currentmodule:: None645646.. autoclass:: flask.views.View647 :members:648649.. autoclass:: flask.views.MethodView650 :members:651652.. _url-route-registrations:653654URL Route Registrations655-----------------------656657Generally there are three ways to define rules for the routing system:6586591. You can use the :meth:`flask.Flask.route` decorator.6602. You can use the :meth:`flask.Flask.add_url_rule` function.6613. You can directly access the underlying Werkzeug routing system662 which is exposed as :attr:`flask.Flask.url_map`.663664Variable parts in the route can be specified with angular brackets665(``/user/<username>``). By default a variable part in the URL accepts any666string without a slash however a different converter can be specified as667well by using ``<converter:name>``.668669Variable parts are passed to the view function as keyword arguments.670671The following converters are available:672673=========== ===============================================674`string` accepts any text without a slash (the default)675`int` accepts integers676`float` like `int` but for floating point values677`path` like the default but also accepts slashes678`any` matches one of the items provided679`uuid` accepts UUID strings680=========== ===============================================681682Custom converters can be defined using :attr:`flask.Flask.url_map`.683684Here are some examples::685686 @app.route('/')687 def index():688 pass689690 @app.route('/<username>')691 def show_user(username):692 pass693694 @app.route('/post/<int:post_id>')695 def show_post(post_id):696 pass697698An important detail to keep in mind is how Flask deals with trailing699slashes. The idea is to keep each URL unique so the following rules700apply:7017021. If a rule ends with a slash and is requested without a slash by the703 user, the user is automatically redirected to the same page with a704 trailing slash attached.7052. If a rule does not end with a trailing slash and the user requests the706 page with a trailing slash, a 404 not found is raised.707708This is consistent with how web servers deal with static files. This709also makes it possible to use relative link targets safely.710711You can also define multiple rules for the same function. They have to be712unique however. Defaults can also be specified. Here for example is a713definition for a URL that accepts an optional page::714715 @app.route('/users/', defaults={'page': 1})716 @app.route('/users/page/<int:page>')717 def show_users(page):718 pass719720This specifies that ``/users/`` will be the URL for page one and721``/users/page/N`` will be the URL for page ``N``.722723If a URL contains a default value, it will be redirected to its simpler724form with a 301 redirect. In the above example, ``/users/page/1`` will725be redirected to ``/users/``. If your route handles ``GET`` and ``POST``726requests, make sure the default route only handles ``GET``, as redirects727can't preserve form data. ::728729 @app.route('/region/', defaults={'id': 1})730 @app.route('/region/<int:id>', methods=['GET', 'POST'])731 def region(id):732 pass733734Here are the parameters that :meth:`~flask.Flask.route` and735:meth:`~flask.Flask.add_url_rule` accept. The only difference is that736with the route parameter the view function is defined with the decorator737instead of the `view_func` parameter.738739=============== ==========================================================740`rule` the URL rule as string741`endpoint` the endpoint for the registered URL rule. Flask itself742 assumes that the name of the view function is the name743 of the endpoint if not explicitly stated.744`view_func` the function to call when serving a request to the745 provided endpoint. If this is not provided one can746 specify the function later by storing it in the747 :attr:`~flask.Flask.view_functions` dictionary with the748 endpoint as key.749`defaults` A dictionary with defaults for this rule. See the750 example above for how defaults work.751`subdomain` specifies the rule for the subdomain in case subdomain752 matching is in use. If not specified the default753 subdomain is assumed.754`**options` the options to be forwarded to the underlying755 :class:`~werkzeug.routing.Rule` object. A change to756 Werkzeug is handling of method options. methods is a list757 of methods this rule should be limited to (``GET``, ``POST``758 etc.). By default a rule just listens for ``GET`` (and759 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is760 implicitly added and handled by the standard request761 handling. They have to be specified as keyword arguments.762=============== ==========================================================763764.. _view-func-options:765766View Function Options767---------------------768769For internal usage the view functions can have some attributes attached to770customize behavior the view function would normally not have control over.771The following attributes can be provided optionally to either override772some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:773774- `__name__`: The name of a function is by default used as endpoint. If775 endpoint is provided explicitly this value is used. Additionally this776 will be prefixed with the name of the blueprint by default which777 cannot be customized from the function itself.778779- `methods`: If methods are not provided when the URL rule is added,780 Flask will look on the view function object itself if a `methods`781 attribute exists. If it does, it will pull the information for the782 methods from there.783784- `provide_automatic_options`: if this attribute is set Flask will785 either force enable or disable the automatic implementation of the786 HTTP ``OPTIONS`` response. This can be useful when working with787 decorators that want to customize the ``OPTIONS`` response on a per-view788 basis.789790- `required_methods`: if this attribute is set, Flask will always add791 these methods when registering a URL rule even if the methods were792 explicitly overridden in the ``route()`` call.793794Full example::795796 def index():797 if request.method == 'OPTIONS':798 # custom options handling here799 ...800 return 'Hello World!'801 index.provide_automatic_options = False802 index.methods = ['GET', 'OPTIONS']803804 app.add_url_rule('/', index)805806.. versionadded:: 0.8807 The `provide_automatic_options` functionality was added.808809Command Line Interface810----------------------811812.. currentmodule:: flask.cli813814.. autoclass:: FlaskGroup815 :members:816817.. autoclass:: AppGroup818 :members:819820.. autoclass:: ScriptInfo821 :members:822823.. autofunction:: load_dotenv824825.. autofunction:: with_appcontext826827.. autofunction:: pass_script_info828829 Marks a function so that an instance of :class:`ScriptInfo` is passed830 as first argument to the click callback.831832.. autodata:: run_command833834.. autodata:: shell_command