fix provide_automatic_options override (#5917)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents d3b78fd, e82db2c · 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
Provenance
- Commit
12e95c9- Tree
3d03484- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
d3b78fd- Parent 2
e82db2c
7 files changed+96 added−86 removed
modified:docs/config.rst+1 added-1 removed
443 unmodified lines444 445 .. versionchanged:: 2.3446 ``ENV`` was removed.447 448-.. versionadded:: 3.10448+.. versionadded:: 3.1449 Added :data:`PROVIDE_AUTOMATIC_OPTIONS` to control the default450 addition of autogenerated OPTIONS responses.451 452 387 unmodified linesmodified:src/flask/sansio/app.py+8 added-8 removed
625 unmodified lines626 627 # Methods that should always be added628 required_methods: set[str] = set(getattr(view_func, "required_methods", ()))629 630- # 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 )634 637- 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+ )640 641+ if provide_automatic_options:642+ required_methods.add("OPTIONS")643+644 # Add the required methods now.645 methods |= required_methods646 647 rule_obj = self.url_rule_class(rule, methods=methods, **options)363 unmodified linesmodified:tests/test_basic.py+37 added-38 removed
18 unmodified lines19 from werkzeug.routing import BuildError20 from werkzeug.routing import RequestRedirect21 22 import flask23+from flask.testing import FlaskClient24 25 require_cpython_gc = pytest.mark.skipif(26 python_implementation() != "CPython",27 reason="Requires CPython GC behavior",39 unmodified lines67 with pytest.raises(TypeError):68 app.get("/", methods=["GET", "POST"])69 70 70-def test_provide_automatic_options_attr():71- app = flask.Flask(__name__)71+def test_provide_automatic_options_attr_disable(72+ app: flask.Flask, client: FlaskClient73+) -> None:74+ """Automatic options can be disabled by the view func attribute."""75 76 def index():77 return "Hello World!"78 79 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 == 40583 81- app = flask.Flask(__name__)84 85+def 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"] = False92+83- def index2():93+ def index():94 return "Hello World!"95 86- 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"}100 101 92-def test_provide_automatic_options_kwarg(app, client):102+def test_provide_automatic_options_arg_disable(103+ app: flask.Flask, client: FlaskClient104+) -> None:105+ """Automatic options can be disabled by the route argument."""106+107+ @app.get("/", provide_automatic_options=False)108 def index():94- return flask.request.method109+ return "Hello World!"110 96- def more():97- return flask.request.method98-99- 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"107-108- rv = client.post("/")111+ rv = client.options()112 assert rv.status_code == 405110- assert sorted(rv.allow) == ["GET", "HEAD"]113 112- rv = client.open("/", method="OPTIONS")113- assert rv.status_code == 405114 115- 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"115+def test_provide_automatic_options_method_disable(116+ app: flask.Flask, client: FlaskClient117+) -> None:118+ """Automatic options is ignored if the route handles options."""119 121- 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"}123 125- rv = client.open("/more", method="OPTIONS")126- assert rv.status_code == 405124+ rv = client.options()125+ assert rv.headers["X-Test"] == "test"126 127 128 def test_request_dispatching(app, client):129 @app.route("/")1819 unmodified linesmodified:tests/test_blueprints.py+7 added-16 removed
218 unmodified lines219 with flask.Flask(__name__).test_request_context():220 assert flask.render_template("nested/nested.txt") == "I'm nested"221 222 223-def test_default_static_max_age(app):223+def 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 100227 228- 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)232 231- # 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_default236 237 238 def test_templates_list(test_apps):239 from blueprintapp import app879 unmodified linesmodified:tests/test_cli.py+8 added-2 removed
481 unmodified lines482 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)492 493 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 output497+498 output = invoke(["routes", "--all-methods"]).output499 assert "GET, HEAD, OPTIONS, POST" in output500 501 def test_no_routes(self, runner):207 unmodified linesmodified:tests/test_views.py+33 added-21 removed
1 import pytest2 from werkzeug.http import parse_set_header3 4 import flask.views5+from flask.testing import FlaskClient6 7 8 def common_test(app):9 c = app.test_client()88 unmodified lines98 assert rv.headers["X-Parachute"] == "awesome"99 assert rv.data == b"Awesome"100 101 101-def test_view_provide_automatic_options_attr():102- app = flask.Flask(__name__)102+def 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."""106 104- class Index1(flask.views.View):107+ class Index(flask.views.View):108 provide_automatic_options = False109 110 def dispatch_request(self):111 return "Hello World!"112 110- 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 == 405116 115- app = flask.Flask(__name__)117 117- class Index2(flask.views.View):118- methods = ["OPTIONS"]118+def 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"] = False125+126+ class Index(flask.views.View):127 provide_automatic_options = True128 129 def dispatch_request(self):130 return "Hello World!"131 124- 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"}135 129- app = flask.Flask(__name__)136 137+def test_provide_automatic_options_method_disable(138+ app: flask.Flask, client: FlaskClient139+) -> None:140+ """Automatic options is ignored if the route handles options."""141+131- class Index3(flask.views.View):142+ class Index(flask.views.View):143+ methods = ["OPTIONS"]144+145 def dispatch_request(self):133- return "Hello World!"146+ return "", {"X-Test": "test"}147 135- 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"151 152 153 def test_implicit_head(app, client):154 class Index(flask.views.MethodView):36 unmodified lines191 192 app.add_url_rule("/", view_func=Index.as_view("index"))193 194 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"))196 197 # But these tests should still pass. We just log a warning.198 common_test(app)199 73 unmodified linesmodified:CHANGES.rst+2 added
21 unmodified lines22 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`28 29 30 Version 3.1.231 -------------1622 unmodified lines