Skip to content
Myr

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

4 files+61 added−46 removed

modified:src/flask/app.py+14 added-5 removed
1455 unmodified lines
1456 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1457 )14581459 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.14611462 In debug mode, intercept a routing redirect and replace it with1463 an error if the body will be discarded.14641465 With modern Werkzeug this shouldn't occur, since it now uses a1466 308 status which tells the browser to resend the method and1467 body.14681469 .. versionchanged:: 2.11470 Don't intercept 307 and 308 redirects.14711472 :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: ignore14821483 from .debughelpers import FormDataRoutingRedirect
612 unmodified lines
modified:src/flask/debughelpers.py+24 added-22 removed
39 unmodified lines
40 return self.msg414243class 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 """4950 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 ]5657 # 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 )6364 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))717273def 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``.7677 :param request: The request to patch.78 :meta private:79 """80 oldcls = request.files.__class__8182 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 raise8990 raise DebugFilesKeyError(request, key) from e90 raise DebugFilesKeyError(request, key).with_traceback(91 e.__traceback__92 ) from None9394 newcls.__name__ = oldcls.__name__95 newcls.__module__ = oldcls.__module__96 request.files.__class__ = newcls
78 unmodified lines
modified:src/flask/wrappers.py+8 added-6 removed
7 unmodified lines
8from .globals import current_app9from .helpers import _split_blueprint_path1011if t.TYPE_CHECKING:12 import typing_extensions as te12 from werkzeug.routing import Rule131415class Request(RequestBase):
92 unmodified lines
108109 return _split_blueprint_path(name)110111 def _load_form_data(self) -> None:113 RequestBase._load_form_data(self)112 super()._load_form_data()113114 # 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 lines
122 from .debughelpers import attach_enctype_error_multidict123124 attach_enctype_error_multidict(self)125127 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 raise132131 raise BadRequest()133 raise BadRequest() from e134135136class Response(ResponseBase):137 """The response object that is used by default in Flask. Works like the
32 unmodified lines
modified:tests/test_basic.py+15 added-13 removed
13 unmodified lines
14from werkzeug.exceptions import Forbidden15from werkzeug.exceptions import NotFound16from werkzeug.http import parse_date17from werkzeug.routing import BuildError18from werkzeug.routing import RequestRedirect1920import flask2122
1701 unmodified lines
1724 t.join()1725 assert app.got_first_request172617271727def test_routing_redirect_debugging(app, client):1728 app.debug = True17291728def test_routing_redirect_debugging(monkeypatch, app, client):1729 @app.route("/foo/", methods=["GET", "POST"])1730 def foo():1731 return "success"17321734 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"17361742 rv = client.get("/foo", data={}, follow_redirects=True)1743 assert rv.data == b"success"1737 app.debug = True17381745 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"17441745 monkeypatch.setattr(RequestRedirect, "code", 301)17461747 with client, pytest.raises(AssertionError) as e:1748 client.post("/foo", data={})17491750 assert "canonical URL 'http://localhost/foo/'" in str(e.value)175117521753def test_route_decorator_custom_endpoint(app, client):1754 app.debug = True17551756 @app.route("/foo/")
279 unmodified lines