From 49efc4423398e4895cb22a772c4aa4269b4eaa78 Mon Sep 17 00:00:00 2001 From: David Lord Date: Sat, 5 Jan 2019 12:49:59 -0800 Subject: [PATCH] clear KeyError in production for Werkzeug 0.15 --- flask/app.py | 21 +++++++++++---------- tests/test_basic.py | 2 +- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/flask/app.py b/flask/app.py index 87c59003..1d7050b7 100644 --- a/flask/app.py +++ b/flask/app.py @@ -1698,16 +1698,17 @@ class Flask(_PackageBoundObject): # we cannot prevent users from trashing it themselves in a custom # trap_http_exception method so that's their fault then. - # MultiDict passes the key to the exception, but that's ignored - # when generating the response message. Set an informative - # description for key errors in debug mode or when trapping errors. - if ( - (self.debug or self.config['TRAP_BAD_REQUEST_ERRORS']) - and isinstance(e, BadRequestKeyError) - # only set it if it's still the default description - and e.description is BadRequestKeyError.description - ): - e.description = "KeyError: '{0}'".format(*e.args) + if isinstance(e, BadRequestKeyError): + if self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]: + # Werkzeug < 0.15 doesn't add the KeyError to the 400 + # message, add it in manually. + description = e.get_description() + + if e.args[0] not in description: + e.description = "KeyError: '{}'".format(*e.args) + else: + # Werkzeug >= 0.15 does add it, remove it in production + e.args = () if isinstance(e, HTTPException) and not self.trap_http_exception(e): return self.handle_http_exception(e) diff --git a/tests/test_basic.py b/tests/test_basic.py index c0168ae3..08b4058c 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -1045,7 +1045,7 @@ def test_trapping_of_bad_request_key_errors(app, client): with pytest.raises(KeyError) as e: client.get("/key") assert e.errisinstance(BadRequest) - assert 'missing_key' in e.value.description + assert 'missing_key' in e.value.get_description() rv = client.get('/abort') assert rv.status_code == 400