Merge pull request #4492 from pallets/debug-messages
Before adoption: this commit came in with the history the project adopted, so no landing records it.
update some debug message behavior
authored by David Lord · committed by GitHub · parents 598afa0, 6578b49 · Browse files · 4 files·+61 added−46 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+61 added−46 removed
- tests:+15 added−13 removed
- other:+46 added−33 removed
Provenance
- Commit
ce7b884- Tree
bdd1b66- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
598afa0- Parent 2
6578b49
4 files changed+61 added−46 removed
modified:src/flask/app.py+14 added-5 removed
1455 unmodified lines1456 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1457 )1458 1459 def raise_routing_exception(self, request: Request) -> "te.NoReturn":1460- """Exceptions that are recording during routing are reraised with1461- this method. During debug we are not reraising redirect requests1462- for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising1463- a different error instead to help debug situations.1460+ """Intercept routing exceptions and possibly do something else.1461 1462+ In debug mode, intercept a routing redirect and replace it with1463+ an error if the body will be discarded.1464+1465+ With modern Werkzeug this shouldn't occur, since it now uses a1466+ 308 status which tells the browser to resend the method and1467+ body.1468+1469+ .. versionchanged:: 2.11470+ Don't intercept 307 and 308 redirects.1471+1472+ :meta private:1473 :internal:1474 """1475 if (1476 not self.debug1477 or not isinstance(request.routing_exception, RequestRedirect)1470- or request.method in ("GET", "HEAD", "OPTIONS")1478+ or request.routing_exception.code in {307, 308}1479+ or request.method in {"GET", "HEAD", "OPTIONS"}1480 ):1481 raise request.routing_exception # type: ignore1482 1483 from .debughelpers import FormDataRoutingRedirect612 unmodified linesmodified:src/flask/debughelpers.py+24 added-22 removed
39 unmodified lines40 return self.msg41 42 43 class FormDataRoutingRedirect(AssertionError):44- """This exception is raised by Flask in debug mode if it detects a45- redirect caused by the routing system when the request method is not46- GET, HEAD or OPTIONS. Reasoning: form data will be dropped.44+ """This exception is raised in debug mode if a routing redirect45+ would cause the browser to drop the method or body. This happens46+ when method is not GET, HEAD or OPTIONS and the status code is not47+ 307 or 308.48 """49 50 def __init__(self, request):51 exc = request.routing_exception52 buf = [52- f"A request was sent to this URL ({request.url}) but a"53- " redirect was issued automatically by the routing system"54- f" to {exc.new_url!r}."53+ f"A request was sent to '{request.url}', but routing issued"54+ f" a redirect to the canonical URL '{exc.new_url}'."55 ]56 57- # In case just a slash was appended we can be extra helpful58- if f"{request.base_url}/" == exc.new_url.split("?")[0]:57+ if f"{request.base_url}/" == exc.new_url.partition("?")[0]:58 buf.append(60- " The URL was defined with a trailing slash so Flask"61- " will automatically redirect to the URL with the"62- " trailing slash if it was accessed without one."59+ " The URL was defined with a trailing slash. Flask"60+ " will redirect to the URL with a trailing slash if it"61+ " was accessed without one."62 )63 64 buf.append(66- " Make sure to directly send your"67- f" {request.method}-request to this URL since we can't make"68- " browsers or HTTP clients redirect with form data reliably"69- " or without user interaction."65+ " Send requests to the canonical URL, or use 307 or 308 for"66+ " routing redirects. Otherwise, browsers will drop form"67+ " data.\n\n"68+ "This exception is only raised in debug mode."69 )71- buf.append("\n\nNote: this exception is only raised in debug mode")72- AssertionError.__init__(self, "".join(buf).encode("utf-8"))70+ super().__init__("".join(buf))71 72 73 def attach_enctype_error_multidict(request):76- """Since Flask 0.8 we're monkeypatching the files object in case a77- request is detected that does not use multipart form data but the files78- object is accessed.74+ """Patch ``request.files.__getitem__`` to raise a descriptive error75+ about ``enctype=multipart/form-data``.76+77+ :param request: The request to patch.78+ :meta private:79 """80 oldcls = request.files.__class__81 82 class newcls(oldcls):83 def __getitem__(self, key):84 try:85- return oldcls.__getitem__(self, key)85+ return super().__getitem__(key)86 except KeyError as e:87 if key not in request.form:88 raise89 90- raise DebugFilesKeyError(request, key) from e90+ raise DebugFilesKeyError(request, key).with_traceback(91+ e.__traceback__92+ ) from None93 94 newcls.__name__ = oldcls.__name__95 newcls.__module__ = oldcls.__module__96 request.files.__class__ = newcls78 unmodified linesmodified:src/flask/wrappers.py+8 added-6 removed
7 unmodified lines8 from .globals import current_app9 from .helpers import _split_blueprint_path10 11 if t.TYPE_CHECKING:12- import typing_extensions as te12 from werkzeug.routing import Rule13 14 15 class Request(RequestBase):92 unmodified lines108 109 return _split_blueprint_path(name)110 111 def _load_form_data(self) -> None:113- RequestBase._load_form_data(self)112+ super()._load_form_data()113 114 # In debug mode we're replacing the files multidict with an ad-hoc115 # subclass that raises a different error for key errors.116 if (5 unmodified lines122 from .debughelpers import attach_enctype_error_multidict123 124 attach_enctype_error_multidict(self)125 127- def on_json_loading_failed(self, e: Exception) -> "te.NoReturn":128- if current_app and current_app.debug:129- raise BadRequest(f"Failed to decode JSON object: {e}")126+ def on_json_loading_failed(self, e: ValueError) -> t.Any:127+ try:128+ return super().on_json_loading_failed(e)129+ except BadRequest as e:130+ if current_app and current_app.debug:131+ raise132 131- raise BadRequest()133+ raise BadRequest() from e134 135 136 class Response(ResponseBase):137 """The response object that is used by default in Flask. Works like the32 unmodified linesmodified:tests/test_basic.py+15 added-13 removed
13 unmodified lines14 from werkzeug.exceptions import Forbidden15 from werkzeug.exceptions import NotFound16 from werkzeug.http import parse_date17 from werkzeug.routing import BuildError18+from werkzeug.routing import RequestRedirect19 20 import flask21 22 1701 unmodified lines1724 t.join()1725 assert app.got_first_request1726 1727 1727-def test_routing_redirect_debugging(app, client):1728- app.debug = True1729-1728+def test_routing_redirect_debugging(monkeypatch, app, client):1729 @app.route("/foo/", methods=["GET", "POST"])1730 def foo():1731 return "success"1732 1734- with client:1735- with pytest.raises(AssertionError) as e:1736- client.post("/foo", data={})1737- assert "http://localhost/foo/" in str(e.value)1738- assert "Make sure to directly send your POST-request to this URL" in str(1739- e.value1740- )1733+ app.debug = False1734+ rv = client.post("/foo", data={}, follow_redirects=True)1735+ assert rv.data == b"success"1736 1742- rv = client.get("/foo", data={}, follow_redirects=True)1743- assert rv.data == b"success"1737+ app.debug = True1738 1745- app.debug = False1739 with client:1740 rv = client.post("/foo", data={}, follow_redirects=True)1741 assert rv.data == b"success"1742+ rv = client.get("/foo", data={}, follow_redirects=True)1743+ assert rv.data == b"success"1744 1745+ monkeypatch.setattr(RequestRedirect, "code", 301)1746 1747+ with client, pytest.raises(AssertionError) as e:1748+ client.post("/foo", data={})1749+1750+ assert "canonical URL 'http://localhost/foo/'" in str(e.value)1751+1752+1753 def test_route_decorator_custom_endpoint(app, client):1754 app.debug = True1755 1756 @app.route("/foo/")279 unmodified lines