Merge pull request #2348 from davidism/bad-request
Before adoption: this commit came in with the history the project adopted, so no landing records it.
make debugging bad key errors easier
authored by David Lord · committed by GitHub · parents fb90c31, 8f3563c · Browse files · 5 files·+43 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+43 added−8 removed
- tests:+8 added−1 removed
- other:+35 added−7 removed
Provenance
- Commit
9049755- Tree
7cce97d- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
fb90c31- Parent 2
8f3563c
5 files changed+43 added−8 removed
modified:docs/config.rst+3 added-2 removed
107 unmodified lines108 109 Trying to access a key that doesn't exist from request dicts like ``args``110 and ``form`` will return a 400 Bad Request error page. Enable this to treat111 the error as an unhandled exception instead so that you get the interactive112- debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``.112+ debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If113+ unset, it is enabled in debug mode.114 114- Default: ``False``115+ Default: ``None``116 117 .. py:data:: SECRET_KEY118 119 A secret key that will be used for securely signing the session cookie430 unmodified linesmodified:flask/app.py+27 added-4 removed
16 unmodified lines17 from threading import Lock18 19 from werkzeug.datastructures import ImmutableDict, Headers20 from werkzeug.exceptions import BadRequest, HTTPException, \21- InternalServerError, MethodNotAllowed, default_exceptions21+ InternalServerError, MethodNotAllowed, default_exceptions, \22+ BadRequestKeyError23 from werkzeug.routing import BuildError, Map, RequestRedirect, Rule24 25 from . import cli, json26 from ._compat import integer_types, reraise, string_types, text_type290 unmodified lines317 'SESSION_COOKIE_SECURE': False,318 'SESSION_REFRESH_EACH_REQUEST': True,319 'MAX_CONTENT_LENGTH': None,320 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),320- 'TRAP_BAD_REQUEST_ERRORS': False,321+ 'TRAP_BAD_REQUEST_ERRORS': None,322 'TRAP_HTTP_EXCEPTIONS': False,323 'EXPLAIN_TEMPLATE_LOADING': False,324 'PREFERRED_URL_SCHEME': 'http',325 'JSON_AS_ASCII': True,1216 unmodified lines1542 If it returns ``True`` for any exception the error handler for this1543 exception is not called and it shows up as regular exception in the1544 traceback. This is helpful for debugging implicitly raised HTTP1545 exceptions.1546+ 1547+ .. versionchanged:: 1.01548+ Bad request errors are not trapped by default in debug mode.1549 1550 .. versionadded:: 0.81551 """1552 if self.config['TRAP_HTTP_EXCEPTIONS']:1553 return True1550- if self.config['TRAP_BAD_REQUEST_ERRORS']:1554+1555+ trap_bad_request = self.config['TRAP_BAD_REQUEST_ERRORS']1556+1557+ # if unset, trap based on debug mode1558+ if (trap_bad_request is None and self.debug) or trap_bad_request:1559 return isinstance(e, BadRequest)1560+1561 return False1562 1563 def handle_user_exception(self, e):1564 """This method is called whenever an exception occurs that should be2 unmodified lines1567 this function to the :meth:`handle_http_exception` method. This1568 function will either return a response value or reraise the1569 exception with the same traceback.1570 1571+ .. versionchanged:: 1.01572+ Key errors raised from request data like ``form`` show the the bad1573+ key in debug mode rather than a generic bad request message.1574+1575 .. versionadded:: 0.71576 """1577 exc_type, exc_value, tb = sys.exc_info()1578 assert exc_value is e1566-1579 # ensure not to trash sys.exc_info() at that point in case someone1580 # wants the traceback preserved in handle_http_exception. Of course1581 # we cannot prevent users from trashing it themselves in a custom1582 # trap_http_exception method so that's their fault then.1583 1584+ # MultiDict passes the key to the exception, but that's ignored1585+ # when generating the response message. Set an informative1586+ # description for key errors in debug mode or when trapping errors.1587+ if (1588+ (self.debug or self.config['TRAP_BAD_REQUEST_ERRORS'])1589+ and isinstance(e, BadRequestKeyError)1590+ # only set it if it's still the default description1591+ and e.description is BadRequestKeyError.description1592+ ):1593+ e.description = "KeyError: '{0}'".format(*e.args)1594+1595 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1596 return self.handle_http_exception(e)1597 1598 handler = self._find_error_handler(e)542 unmodified linesmodified:tests/test_basic.py+6 added-1 removed
973 unmodified lines974 @app.route('/fail')975 def fail():976 flask.request.form['missing_key']977 978+ rv = client.get('/fail')978- assert client.get('/fail').status_code == 400979+ assert rv.status_code == 400980+ assert b'missing_key' not in rv.data981 982 app.config['TRAP_BAD_REQUEST_ERRORS'] = True983+984 with pytest.raises(KeyError) as e:985 client.get("/fail")986+987 assert e.errisinstance(BadRequest)988+ assert 'missing_key' in e.value.description989 990 991 def test_trapping_of_all_http_exceptions(app, client):992 app.config['TRAP_HTTP_EXCEPTIONS'] = True830 unmodified linesmodified:tests/test_helpers.py+2 added
42 unmodified lines43 flask.request.get_json(silent=False, cache=False)44 45 def test_post_empty_json_adds_exception_to_response_content_in_debug(self, app, client):46 app.config['DEBUG'] = True47+ app.config['TRAP_BAD_REQUEST_ERRORS'] = False48 49 @app.route('/json', methods=['POST'])50 def post_json():51 flask.request.get_json()4 unmodified lines56 assert b'Failed to decode JSON object' in rv.data57 58 def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self, app, client):59 app.config['DEBUG'] = False60+ app.config['TRAP_BAD_REQUEST_ERRORS'] = False61 62 @app.route('/json', methods=['POST'])63 def post_json():64 flask.request.get_json()868 unmodified linesmodified:CHANGES+5 added-1 removed
47 unmodified lines48 - Factory functions are not required to take a ``script_info`` parameter to49 work with the ``flask`` command. If they take a single parameter or a50 parameter named ``script_info``, the ``ScriptInfo`` object will be passed.51 (`#2319`_)52-- FLASK_APP=myproject.app:create_app('dev') support. 52+- FLASK_APP=myproject.app:create_app('dev') support.53 - ``FLASK_APP`` can be set to an app factory, with arguments if needed, for54 example ``FLASK_APP=myproject.app:create_app('dev')``. (`#2326`_)55 - ``View.provide_automatic_options = True`` is set on the view function from56 ``View.as_view``, to be detected in ``app.add_url_rule``. (`#2316`_)4 unmodified lines61 - ``app.test_request_context()`` take ``subdomain`` and ``url_scheme``62 parameters for use when building base URL. (`#1621`_)63 - Set ``APPLICATION_ROOT = '/'`` by default. This was already the implicit64 default when it was set to ``None``.65+- ``TRAP_BAD_REQUEST_ERRORS`` is enabled by default in debug mode.66+ ``BadRequestKeyError`` has a message with the bad key in debug mode instead67+ of the generic bad request message. (`#2348`_)68 69 .. _#1489: https://github.com/pallets/flask/pull/148970 .. _#1621: https://github.com/pallets/flask/pull/162171 .. _#1898: https://github.com/pallets/flask/pull/189810 unmodified lines82 .. _#2314: https://github.com/pallets/flask/pull/231483 .. _#2316: https://github.com/pallets/flask/pull/231684 .. _#2319: https://github.com/pallets/flask/pull/231985 .. _#2326: https://github.com/pallets/flask/pull/232686+.. _#2348: https://github.com/pallets/flask/pull/234887 88 Version 0.12.289 --------------90 617 unmodified lines