api.rst
This file
Path
docs/api.rst
722 lines · 21.3 KiB
Last changed by
Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
History of this fileTake it
The walk stopped after 200 commits: lines older than 6b0c8cd point at it.
Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 1–5why, one step back1API2===34.. module:: flask5Merge branch '2.2.x'David Lordbefore adoption066a35d
line 6why, one step back6This part of the documentation covers all the interfaces of Flask. ForMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 7–36why, one step back7parts 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`Merge branch '2.2.x'David Lordbefore adoption066a35d
lines 37–38why, one step back37 object. Flask parses incoming request data for you and gives you38 access to it through that global object. Internally Flask makesMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 39–41why, one step back39 sure that you always get the correct data for the active thread if you40 are in a multithreaded environment.41Merge branch '2.2.x'David Lordbefore adoption066a35d
line 42why, one step back42 This is a proxy. See :ref:`notes-on-proxies` for more information.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 43–71why, one step back4344 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.71Merge branch '2.2.x'David Lordbefore adoption066a35d
line 72why, one step back72 This is a proxy. See :ref:`notes-on-proxies` for more information.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 73–81why, one step back7374 The following attributes are interesting:7576 .. attribute:: new7778 ``True`` if the session is new, ``False`` otherwise.7980 .. attribute:: modified81Merge branch '2.2.x'David Lordbefore adoption066a35d
line 82why, one step back82 ``True`` if the session object detected a modification. Be advisedMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 83–84why, one step back83 that modifications on mutable structures are not picked up84 automatically, in that situation you have to explicitly set theMerge branch '2.2.x'David Lordbefore adoption066a35d
line 85why, one step back85 attribute to ``True`` yourself. Here an example::Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 86–95why, one step back8687 # 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 forMerge branch '2.2.x'David Lordbefore adoption066a35d
lines 96–97why, one step back96 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The97 default is 31 days. If set to ``False`` (which is the default) theMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 98–127why, one step back98 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:: Notice127Merge pull request #4722 from pallets/deprecate-config-attrsDavid Lordbefore adoptioncfd5783
lines 128–130why, one step back128 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``.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 131–157why, one step back131132133Test 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 inMerge branch '2.2.x'David Lordbefore adoption066a35d
line 158why, one step back158threaded environments. Flask provides you with a special object thatMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
line 159why, one step back159ensures it is only valid for the active request and that will returnMerge branch '2.2.x'David Lordbefore adoption066a35d
line 160why, one step back160different values for each request. In a nutshell: it does the rightMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 161–169why, one step back161thing, 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`.169Merge branch '2.0.x'David Lordbefore adoptionb6a8ccd
lines 170–172why, one step back170 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.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 173–233why, one step back173174 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.json233Merge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
lines 234–238why, one step back234Flask 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.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
line 239why, one step back239Merge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
lines 240–242why, one step back240Jinja'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.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 243–246why, one step back243244.. sourcecode:: html+jinja245246 <script>Merge branch '2.2.x'David Lordbefore adoption7464e17
line 247why, one step back247 const names = {{ names|tojson }};Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 248–259why, one step back248 renderChart(names, {{ axis_data|tojson }});249 </script>250251.. autofunction:: jsonify252253.. autofunction:: dumps254255.. autofunction:: dump256257.. autofunction:: loads258259.. autofunction:: loadMerge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab
lines 260–267why, one step back260261.. autoclass:: flask.json.provider.JSONProvider262 :members:263 :member-order: bysource264265.. autoclass:: flask.json.provider.DefaultJSONProvider266 :members:267 :member-order: bysourceMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 268–280why, one step back268269.. automodule:: flask.json.tag270271272Template Rendering273------------------274275.. currentmodule:: flask276277.. autofunction:: render_template278279.. autofunction:: render_template_string280Merge pull request #4629 from pgjones/generateDavid Lordbefore adoptionab36542
lines 281–284why, one step back281.. autofunction:: stream_template282283.. autofunction:: stream_template_string284Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 285–304why, one step back285.. autofunction:: get_template_attribute286287Configuration288-------------289290.. autoclass:: Config291 :members:292293294Stream Helpers295--------------296297.. autofunction:: stream_with_context298299Useful Internals300----------------301302.. autoclass:: flask.ctx.RequestContext303 :members:304Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
line 305why, one step back305.. data:: flask.globals.request_ctxMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
line 306why, one step back306Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
lines 307–309why, one step back307 The current :class:`~flask.ctx.RequestContext`. If a request context308 is not active, accessing attributes on this proxy will raise a309 ``RuntimeError``.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
line 310why, one step back310Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
lines 311–313why, one step back311 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.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 314–317why, one step back314315.. autoclass:: flask.ctx.AppContext316 :members:317Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
line 318why, one step back318.. data:: flask.globals.app_ctxMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
line 319why, one step back319Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
lines 320–322why, one step back320 The current :class:`~flask.ctx.AppContext`. If an app context is not321 active, accessing attributes on this proxy will raise a322 ``RuntimeError``.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
line 323why, one step back323Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae
lines 324–326why, one step back324 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.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 327–335why, one step back327328.. autoclass:: flask.blueprints.BlueprintSetupState329 :members:330331.. _core-signals-list:332333Signals334-------335Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
line 336why, one step back336Signals are provided by the `Blinker`_ library. See :doc:`signals` for an introduction.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
line 337why, one step back337Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
line 338why, one step back338.. _blinker: https://blinker.readthedocs.io/Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 339–341why, one step back339340.. data:: template_rendered341Merge branch '2.2.x'David Lordbefore adoption066a35d
line 342why, one step back342 This signal is sent when a template was successfully rendered. TheMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 343–375why, one step back343 signal is invoked with the instance of the template as `template`344 and the context as dictionary (named `context`).345346 Example subscriber::347348 def log_template_renders(sender, template, context, **extra):349 sender.logger.debug('Rendering template "%s" with context %s',350 template.name or 'string template',351 context)352353 from flask import template_rendered354 template_rendered.connect(log_template_renders, app)355356.. data:: flask.before_render_template357 :noindex:358359 This signal is sent before template rendering process. The360 signal is invoked with the instance of the template as `template`361 and the context as dictionary (named `context`).362363 Example subscriber::364365 def log_template_renders(sender, template, context, **extra):366 sender.logger.debug('Rendering template "%s" with context %s',367 template.name or 'string template',368 context)369370 from flask import before_render_template371 before_render_template.connect(log_template_renders, app)372373.. data:: request_started374375 This signal is sent when the request context is set up, beforeMerge branch '2.2.x'David Lordbefore adoption066a35d
line 376why, one step back376 any request processing happens. Because the request context is alreadyMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 377–395why, one step back377 bound, the subscriber can access the request with the standard global378 proxies such as :class:`~flask.request`.379380 Example subscriber::381382 def log_request(sender, **extra):383 sender.logger.debug('Request context is set up')384385 from flask import request_started386 request_started.connect(log_request, app)387388.. data:: request_finished389390 This signal is sent right before the response is sent to the client.391 It is passed the response to be sent named `response`.392393 Example subscriber::394395 def log_response(sender, response, **extra):Merge branch '2.2.x'David Lordbefore adoption066a35d
line 396why, one step back396 sender.logger.debug('Request context is about to close down. 'Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 397–432why, one step back397 'Response: %s', response)398399 from flask import request_finished400 request_finished.connect(log_response, app)401402.. data:: got_request_exception403404 This signal is sent when an unhandled exception happens during405 request processing, including when debugging. The exception is406 passed to the subscriber as ``exception``.407408 This signal is not sent for409 :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that410 have error handlers registered, unless the exception was raised from411 an error handler.412413 This example shows how to do some extra logging if a theoretical414 ``SecurityException`` was raised:415416 .. code-block:: python417418 from flask import got_request_exception419420 def log_security_exception(sender, exception, **extra):421 if not isinstance(exception, SecurityException):422 return423424 security_logger.exception(425 f"SecurityException at {request.url!r}",426 exc_info=exception,427 )428429 got_request_exception.connect(log_security_exception, app)430431.. data:: request_tearing_down432Merge branch '2.2.x'David Lordbefore adoption066a35d
lines 433–434why, one step back433 This signal is sent when the request is tearing down. This is always434 called, even if an exception is caused. Currently functions listeningMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 435–451why, one step back435 to this signal are called after the regular teardown handlers, but this436 is not something you can rely on.437438 Example subscriber::439440 def close_db_connection(sender, **extra):441 session.close()442443 from flask import request_tearing_down444 request_tearing_down.connect(close_db_connection, app)445446 As of Flask 0.9, this will also be passed an `exc` keyword argument447 that has a reference to the exception that caused the teardown if448 there was one.449450.. data:: appcontext_tearing_down451Merge branch '2.2.x'David Lordbefore adoption066a35d
lines 452–453why, one step back452 This signal is sent when the app context is tearing down. This is always453 called, even if an exception is caused. Currently functions listeningMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 454–469why, one step back454 to this signal are called after the regular teardown handlers, but this455 is not something you can rely on.456457 Example subscriber::458459 def close_db_connection(sender, **extra):460 session.close()461462 from flask import appcontext_tearing_down463 appcontext_tearing_down.connect(close_db_connection, app)464465 This will also be passed an `exc` keyword argument that has a reference466 to the exception that caused the teardown if there was one.467468.. data:: appcontext_pushed469Merge branch '2.2.x'David Lordbefore adoption066a35d
lines 470–472why, one step back470 This signal is sent when an application context is pushed. The sender471 is the application. This is usually useful for unittests in order to472 temporarily hook in information. For instance it can be used toMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 473–498why, one step back473 set a resource early onto the `g` object.474475 Example usage::476477 from contextlib import contextmanager478 from flask import appcontext_pushed479480 @contextmanager481 def user_set(app, user):482 def handler(sender, **kwargs):483 g.user = user484 with appcontext_pushed.connected_to(handler, app):485 yield486487 And in the testcode::488489 def test_user_me(self):490 with user_set(app, 'john'):491 c = app.test_client()492 resp = c.get('/users/me')493 assert resp.data == 'username=john'494495 .. versionadded:: 0.10496497.. data:: appcontext_popped498Merge branch '2.2.x'David Lordbefore adoption066a35d
lines 499–500why, one step back499 This signal is sent when an application context is popped. The sender500 is the application. This usually falls in line with theMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 501–506why, one step back501 :data:`appcontext_tearing_down` signal.502503 .. versionadded:: 0.10504505.. data:: message_flashed506Merge branch '2.2.x'David Lordbefore adoption066a35d
line 507why, one step back507 This signal is sent when the application is flashing a message. TheMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 508–521why, one step back508 messages is sent as `message` keyword argument and the category as509 `category`.510511 Example subscriber::512513 recorded = []514 def record(sender, message, category, **extra):515 recorded.append((message, category))516517 from flask import message_flashed518 message_flashed.connect(record, app)519520 .. versionadded:: 0.10521Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
line 522why, one step back522.. data:: signals.signals_availableMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
line 523why, one step back523Merge pull request #5058 from pallets/require-blinkerDavid Lordbefore adoptiona05c0c6
lines 524–525why, one step back524 .. deprecated:: 2.3525 Will be removed in Flask 2.4. Signals are always availableMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 526–553why, one step back526527528Class-Based Views529-----------------530531.. versionadded:: 0.7532533.. currentmodule:: None534535.. autoclass:: flask.views.View536 :members:537538.. autoclass:: flask.views.MethodView539 :members:540541.. _url-route-registrations:542543URL Route Registrations544-----------------------545546Generally there are three ways to define rules for the routing system:5475481. You can use the :meth:`flask.Flask.route` decorator.5492. You can use the :meth:`flask.Flask.add_url_rule` function.5503. You can directly access the underlying Werkzeug routing system551 which is exposed as :attr:`flask.Flask.url_map`.552553Variable parts in the route can be specified with angular bracketsMerge branch '2.2.x'David Lordbefore adoption066a35d
line 554why, one step back554(``/user/<username>``). By default a variable part in the URL accepts anyMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 555–587why, one step back555string without a slash however a different converter can be specified as556well by using ``<converter:name>``.557558Variable parts are passed to the view function as keyword arguments.559560The following converters are available:561562=========== ===============================================563`string` accepts any text without a slash (the default)564`int` accepts integers565`float` like `int` but for floating point values566`path` like the default but also accepts slashes567`any` matches one of the items provided568`uuid` accepts UUID strings569=========== ===============================================570571Custom converters can be defined using :attr:`flask.Flask.url_map`.572573Here are some examples::574575 @app.route('/')576 def index():577 pass578579 @app.route('/<username>')580 def show_user(username):581 pass582583 @app.route('/post/<int:post_id>')584 def show_post(post_id):585 pass586587An important detail to keep in mind is how Flask deals with trailingMerge branch '2.2.x'David Lordbefore adoption066a35d
line 588why, one step back588slashes. The idea is to keep each URL unique so the following rulesMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 589–596why, one step back589apply:5905911. If a rule ends with a slash and is requested without a slash by the592 user, the user is automatically redirected to the same page with a593 trailing slash attached.5942. If a rule does not end with a trailing slash and the user requests the595 page with a trailing slash, a 404 not found is raised.596Merge branch '2.2.x'David Lordbefore adoption066a35d
line 597why, one step back597This is consistent with how web servers deal with static files. ThisMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 598–599why, one step back598also makes it possible to use relative link targets safely.599Merge branch '2.2.x'David Lordbefore adoption066a35d
lines 600–601why, one step back600You can also define multiple rules for the same function. They have to be601unique however. Defaults can also be specified. Here for example is aMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 602–623why, one step back602definition for a URL that accepts an optional page::603604 @app.route('/users/', defaults={'page': 1})605 @app.route('/users/page/<int:page>')606 def show_users(page):607 pass608609This specifies that ``/users/`` will be the URL for page one and610``/users/page/N`` will be the URL for page ``N``.611612If a URL contains a default value, it will be redirected to its simpler613form with a 301 redirect. In the above example, ``/users/page/1`` will614be redirected to ``/users/``. If your route handles ``GET`` and ``POST``615requests, make sure the default route only handles ``GET``, as redirects616can't preserve form data. ::617618 @app.route('/region/', defaults={'id': 1})619 @app.route('/region/<int:id>', methods=['GET', 'POST'])620 def region(id):621 pass622623Here are the parameters that :meth:`~flask.Flask.route` andMerge branch '2.2.x'David Lordbefore adoption066a35d
line 624why, one step back624:meth:`~flask.Flask.add_url_rule` accept. The only difference is thatMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 625–629why, one step back625with the route parameter the view function is defined with the decorator626instead of the `view_func` parameter.627628=============== ==========================================================629`rule` the URL rule as stringMerge branch '2.2.x'David Lordbefore adoption066a35d
line 630why, one step back630`endpoint` the endpoint for the registered URL rule. Flask itselfMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 631–633why, one step back631 assumes that the name of the view function is the name632 of the endpoint if not explicitly stated.633`view_func` the function to call when serving a request to theMerge branch '2.2.x'David Lordbefore adoption066a35d
line 634why, one step back634 provided endpoint. If this is not provided one canMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 635–637why, one step back635 specify the function later by storing it in the636 :attr:`~flask.Flask.view_functions` dictionary with the637 endpoint as key.Merge branch '2.2.x'David Lordbefore adoption066a35d
line 638why, one step back638`defaults` A dictionary with defaults for this rule. See theMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 639–640why, one step back639 example above for how defaults work.640`subdomain` specifies the rule for the subdomain in case subdomainMerge branch '2.2.x'David Lordbefore adoption066a35d
line 641why, one step back641 matching is in use. If not specified the defaultMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 642–643why, one step back642 subdomain is assumed.643`**options` the options to be forwarded to the underlyingMerge branch '2.2.x'David Lordbefore adoption066a35d
lines 644–645why, one step back644 :class:`~werkzeug.routing.Rule` object. A change to645 Werkzeug is handling of method options. methods is a listMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
line 646why, one step back646 of methods this rule should be limited to (``GET``, ``POST``Merge branch '2.2.x'David Lordbefore adoption066a35d
lines 647–648why, one step back647 etc.). By default a rule just listens for ``GET`` (and648 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` isMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
line 649why, one step back649 implicitly added and handled by the standard requestMerge branch '2.2.x'David Lordbefore adoption066a35d
line 650why, one step back650 handling. They have to be specified as keyword arguments.Merge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 651–661why, one step back651=============== ==========================================================652653654View Function Options655---------------------656657For internal usage the view functions can have some attributes attached to658customize behavior the view function would normally not have control over.659The following attributes can be provided optionally to either override660some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:661Merge branch '2.2.x'David Lordbefore adoption066a35d
lines 662–663why, one step back662- `__name__`: The name of a function is by default used as endpoint. If663 endpoint is provided explicitly this value is used. Additionally thisMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 664–668why, one step back664 will be prefixed with the name of the blueprint by default which665 cannot be customized from the function itself.666667- `methods`: If methods are not provided when the URL rule is added,668 Flask will look on the view function object itself if a `methods`Merge branch '2.2.x'David Lordbefore adoption066a35d
line 669why, one step back669 attribute exists. If it does, it will pull the information for theMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 670–673why, one step back670 methods from there.671672- `provide_automatic_options`: if this attribute is set Flask will673 either force enable or disable the automatic implementation of theMerge branch '2.2.x'David Lordbefore adoption066a35d
line 674why, one step back674 HTTP ``OPTIONS`` response. This can be useful when working withMerge branch '2.0.x'David Lordbefore adoption6b0c8cd
lines 675–722why, one step back675 decorators that want to customize the ``OPTIONS`` response on a per-view676 basis.677678- `required_methods`: if this attribute is set, Flask will always add679 these methods when registering a URL rule even if the methods were680 explicitly overridden in the ``route()`` call.681682Full example::683684 def index():685 if request.method == 'OPTIONS':686 # custom options handling here687 ...688 return 'Hello World!'689 index.provide_automatic_options = False690 index.methods = ['GET', 'OPTIONS']691692 app.add_url_rule('/', index)693694.. versionadded:: 0.8695 The `provide_automatic_options` functionality was added.696697Command Line Interface698----------------------699700.. currentmodule:: flask.cli701702.. autoclass:: FlaskGroup703 :members:704705.. autoclass:: AppGroup706 :members:707708.. autoclass:: ScriptInfo709 :members:710711.. autofunction:: load_dotenv712713.. autofunction:: with_appcontext714715.. autofunction:: pass_script_info716717 Marks a function so that an instance of :class:`ScriptInfo` is passed718 as first argument to the click callback.719720.. autodata:: run_command721722.. autodata:: shell_command