Skip to content
Myr

fix provide_automatic_options override

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent d3b78fd · Browse files · 7 files+96 added−86 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+96 added−86 removed

  • tests:+85 added−77 removed
  • other:+11 added−9 removed

7 files+96 added−86 removed

modified:docs/config.rst+1 added-1 removed
443 unmodified lines
444445.. versionchanged:: 2.3446 ``ENV`` was removed.447448.. versionadded:: 3.10448.. versionadded:: 3.1449 Added :data:`PROVIDE_AUTOMATIC_OPTIONS` to control the default450 addition of autogenerated OPTIONS responses.451452
387 unmodified lines
modified:src/flask/sansio/app.py+8 added-8 removed
625 unmodified lines
626627 # Methods that should always be added628 required_methods: set[str] = set(getattr(view_func, "required_methods", ()))629630 # starting with Flask 0.8 the view_func object can disable and631 # force-enable the automatic options handling.630 if provide_automatic_options is None:631 provide_automatic_options = getattr(632 view_func, "provide_automatic_options", None633 )634637 if provide_automatic_options is None:638 if "OPTIONS" not in methods and self.config["PROVIDE_AUTOMATIC_OPTIONS"]:639 provide_automatic_options = True640 required_methods.add("OPTIONS")641 else:642 provide_automatic_options = False635 if provide_automatic_options is None:636 provide_automatic_options = (637 "OPTIONS" not in methods638 and self.config["PROVIDE_AUTOMATIC_OPTIONS"]639 )640641 if provide_automatic_options:642 required_methods.add("OPTIONS")643644 # Add the required methods now.645 methods |= required_methods646647 rule_obj = self.url_rule_class(rule, methods=methods, **options)
363 unmodified lines
modified:tests/test_basic.py+37 added-38 removed
18 unmodified lines
19from werkzeug.routing import BuildError20from werkzeug.routing import RequestRedirect2122import flask23from flask.testing import FlaskClient2425require_cpython_gc = pytest.mark.skipif(26 python_implementation() != "CPython",27 reason="Requires CPython GC behavior",
39 unmodified lines
67 with pytest.raises(TypeError):68 app.get("/", methods=["GET", "POST"])697070def test_provide_automatic_options_attr():71 app = flask.Flask(__name__)71def test_provide_automatic_options_attr_disable(72 app: flask.Flask, client: FlaskClient73) -> None:74 """Automatic options can be disabled by the view func attribute."""7576 def index():77 return "Hello World!"7879 index.provide_automatic_options = False77 app.route("/")(index)78 rv = app.test_client().open("/", method="OPTIONS")80 app.add_url_rule("/", view_func=index)81 rv = client.options()82 assert rv.status_code == 4058381 app = flask.Flask(__name__)8485def test_provide_automatic_options_attr_enable(86 app: flask.Flask, client: FlaskClient87) -> None:88 """When default automatic options is disabled in config, it can still be89 enabled by the view function attribute.90 """91 app.config["PROVIDE_AUTOMATIC_OPTIONS"] = False9283 def index2():93 def index():94 return "Hello World!"9586 index2.provide_automatic_options = True87 app.route("/", methods=["OPTIONS"])(index2)88 rv = app.test_client().open("/", method="OPTIONS")89 assert sorted(rv.allow) == ["OPTIONS"]96 index.provide_automatic_options = True97 app.add_url_rule("/", view_func=index)98 rv = client.options()99 assert rv.allow == {"GET", "HEAD", "OPTIONS"}10010192def test_provide_automatic_options_kwarg(app, client):102def test_provide_automatic_options_arg_disable(103 app: flask.Flask, client: FlaskClient104) -> None:105 """Automatic options can be disabled by the route argument."""106107 @app.get("/", provide_automatic_options=False)108 def index():94 return flask.request.method109 return "Hello World!"11096 def more():97 return flask.request.method9899 app.add_url_rule("/", view_func=index, provide_automatic_options=False)100 app.add_url_rule(101 "/more",102 view_func=more,103 methods=["GET", "POST"],104 provide_automatic_options=False,105 )106 assert client.get("/").data == b"GET"107108 rv = client.post("/")111 rv = client.options()112 assert rv.status_code == 405110 assert sorted(rv.allow) == ["GET", "HEAD"]113112 rv = client.open("/", method="OPTIONS")113 assert rv.status_code == 405114115 rv = client.head("/")116 assert rv.status_code == 200117 assert not rv.data # head truncates118 assert client.post("/more").data == b"POST"119 assert client.get("/more").data == b"GET"115def test_provide_automatic_options_method_disable(116 app: flask.Flask, client: FlaskClient117) -> None:118 """Automatic options is ignored if the route handles options."""119121 rv = client.delete("/more")122 assert rv.status_code == 405123 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]120 @app.route("/", methods=["OPTIONS"])121 def index():122 return "", {"X-Test": "test"}123125 rv = client.open("/more", method="OPTIONS")126 assert rv.status_code == 405124 rv = client.options()125 assert rv.headers["X-Test"] == "test"126127128def test_request_dispatching(app, client):129 @app.route("/")
1819 unmodified lines
modified:tests/test_blueprints.py+7 added-16 removed
218 unmodified lines
219 with flask.Flask(__name__).test_request_context():220 assert flask.render_template("nested/nested.txt") == "I'm nested"221222223def test_default_static_max_age(app):223def test_default_static_max_age(app: flask.Flask) -> None:224 class MyBlueprint(flask.Blueprint):225 def get_send_file_max_age(self, filename):226 return 100227228 blueprint = MyBlueprint("blueprint", __name__, static_folder="static")228 blueprint = MyBlueprint(229 "blueprint", __name__, url_prefix="/bp", static_folder="static"230 )231 app.register_blueprint(blueprint)232231 # try/finally, in case other tests use this app for Blueprint tests.232 max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]233 try:234 with app.test_request_context():235 unexpected_max_age = 3600236 if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == unexpected_max_age:237 unexpected_max_age = 7200238 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = unexpected_max_age239 rv = blueprint.send_static_file("index.html")240 cc = parse_cache_control_header(rv.headers["Cache-Control"])241 assert cc.max_age == 100233 with app.test_request_context(), blueprint.send_static_file("index.html") as rv:234 cc = parse_cache_control_header(rv.headers["Cache-Control"])235 assert cc.max_age == 100242 rv.close()243 finally:244 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default236237238def test_templates_list(test_apps):239 from blueprintapp import app
879 unmodified lines
modified:tests/test_cli.py+8 added-2 removed
481 unmodified lines
482 self.expect_order(483 ["yyy_get_post", "static", "aaa_post"],484 invoke(["routes", "-s", "rule"]).output,485 )486 match_order = [r.endpoint for r in app.url_map.iter_rules()]486 match_order = [487 r.endpoint488 for r in app.url_map.iter_rules()489 if r.endpoint != "_automatic_options"490 ]491 self.expect_order(match_order, invoke(["routes", "-s", "match"]).output)492493 def test_all_methods(self, invoke):494 output = invoke(["routes"]).output491 assert "GET, HEAD, OPTIONS, POST" not in output495 assert "HEAD" not in output496 assert "OPTIONS" not in output497498 output = invoke(["routes", "--all-methods"]).output499 assert "GET, HEAD, OPTIONS, POST" in output500501 def test_no_routes(self, runner):
207 unmodified lines
modified:tests/test_views.py+33 added-21 removed
1import pytest2from werkzeug.http import parse_set_header34import flask.views5from flask.testing import FlaskClient678def common_test(app):9 c = app.test_client()
88 unmodified lines
98 assert rv.headers["X-Parachute"] == "awesome"99 assert rv.data == b"Awesome"100101101def test_view_provide_automatic_options_attr():102 app = flask.Flask(__name__)102def test_view_provide_automatic_options_attr_disable(103 app: flask.Flask, client: FlaskClient104) -> None:105 """Automatic options can be disabled by the view class attribute."""106104 class Index1(flask.views.View):107 class Index(flask.views.View):108 provide_automatic_options = False109110 def dispatch_request(self):111 return "Hello World!"112110 app.add_url_rule("/", view_func=Index1.as_view("index"))111 c = app.test_client()112 rv = c.open("/", method="OPTIONS")113 app.add_url_rule("/", view_func=Index.as_view("index"))114 rv = client.options()115 assert rv.status_code == 405116115 app = flask.Flask(__name__)117117 class Index2(flask.views.View):118 methods = ["OPTIONS"]118def test_view_provide_automatic_options_attr_enable(119 app: flask.Flask, client: FlaskClient120) -> None:121 """When default automatic options is disabled in config, it can still be122 enabled by the view class attribute.123 """124 app.config["PROVIDE_AUTOMATIC_OPTIONS"] = False125126 class Index(flask.views.View):127 provide_automatic_options = True128129 def dispatch_request(self):130 return "Hello World!"131124 app.add_url_rule("/", view_func=Index2.as_view("index"))125 c = app.test_client()126 rv = c.open("/", method="OPTIONS")127 assert sorted(rv.allow) == ["OPTIONS"]132 app.add_url_rule("/", view_func=Index.as_view("index"))133 rv = client.options("/")134 assert rv.allow == {"GET", "HEAD", "OPTIONS"}135129 app = flask.Flask(__name__)136137def test_provide_automatic_options_method_disable(138 app: flask.Flask, client: FlaskClient139) -> None:140 """Automatic options is ignored if the route handles options."""141131 class Index3(flask.views.View):142 class Index(flask.views.View):143 methods = ["OPTIONS"]144145 def dispatch_request(self):133 return "Hello World!"146 return "", {"X-Test": "test"}147135 app.add_url_rule("/", view_func=Index3.as_view("index"))136 c = app.test_client()137 rv = c.open("/", method="OPTIONS")138 assert "OPTIONS" in rv.allow148 app.add_url_rule("/", view_func=Index.as_view("index"))149 rv = client.options()150 assert rv.headers["X-Test"] == "test"151152153def test_implicit_head(app, client):154 class Index(flask.views.MethodView):
36 unmodified lines
191192 app.add_url_rule("/", view_func=Index.as_view("index"))193194 with pytest.raises(AssertionError):183 app.add_url_rule("/", view_func=Index.as_view("index"))195 app.add_url_rule("/other", view_func=Index.as_view("index"))196197 # But these tests should still pass. We just log a warning.198 common_test(app)199
73 unmodified lines
modified:CHANGES.rst+2 added
21 unmodified lines
22 This tells the client to always switch to ``GET``, rather than only23 switching ``POST`` to ``GET``. This preserves the current behavior of24 ``GET`` and ``POST`` redirects, and is also correct for frontend libraries25 such as HTMX. :issue:`5895`26- ``provide_automatic_options=True`` can be used to enable it for a view when27 it's disabled in config. Previously, only disabling worked. :issue:`5916`282930Version 3.1.231-------------
1622 unmodified lines