Skip to content
Myr

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

5 files+43 added−8 removed

modified:docs/config.rst+3 added-2 removed
107 unmodified lines
108109 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.114114 Default: ``False``115 Default: ``None``116117.. py:data:: SECRET_KEY118119 A secret key that will be used for securely signing the session cookie
430 unmodified lines
modified:flask/app.py+27 added-4 removed
16 unmodified lines
17from threading import Lock1819from werkzeug.datastructures import ImmutableDict, Headers20from werkzeug.exceptions import BadRequest, HTTPException, \21 InternalServerError, MethodNotAllowed, default_exceptions21 InternalServerError, MethodNotAllowed, default_exceptions, \22 BadRequestKeyError23from werkzeug.routing import BuildError, Map, RequestRedirect, Rule2425from . import cli, json26from ._compat import integer_types, reraise, string_types, text_type
290 unmodified lines
317 '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 lines
1542 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.15491550 .. versionadded:: 0.81551 """1552 if self.config['TRAP_HTTP_EXCEPTIONS']:1553 return True1550 if self.config['TRAP_BAD_REQUEST_ERRORS']:15541555 trap_bad_request = self.config['TRAP_BAD_REQUEST_ERRORS']15561557 # 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)15601561 return False15621563 def handle_user_exception(self, e):1564 """This method is called whenever an exception occurs that should be
2 unmodified lines
1567 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.15701571 .. 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.15741575 .. versionadded:: 0.71576 """1577 exc_type, exc_value, tb = sys.exc_info()1578 assert exc_value is e15661579 # 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.15831584 # 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)15941595 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1596 return self.handle_http_exception(e)15971598 handler = self._find_error_handler(e)
542 unmodified lines
modified:tests/test_basic.py+6 added-1 removed
973 unmodified lines
974 @app.route('/fail')975 def fail():976 flask.request.form['missing_key']977978 rv = client.get('/fail')978 assert client.get('/fail').status_code == 400979 assert rv.status_code == 400980 assert b'missing_key' not in rv.data981982 app.config['TRAP_BAD_REQUEST_ERRORS'] = True983984 with pytest.raises(KeyError) as e:985 client.get("/fail")986987 assert e.errisinstance(BadRequest)988 assert 'missing_key' in e.value.description989990991def test_trapping_of_all_http_exceptions(app, client):992 app.config['TRAP_HTTP_EXCEPTIONS'] = True
830 unmodified lines
modified:tests/test_helpers.py+2 added
42 unmodified lines
43 flask.request.get_json(silent=False, cache=False)4445 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'] = False4849 @app.route('/json', methods=['POST'])50 def post_json():51 flask.request.get_json()
4 unmodified lines
56 assert b'Failed to decode JSON object' in rv.data5758 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'] = False6162 @app.route('/json', methods=['POST'])63 def post_json():64 flask.request.get_json()
868 unmodified lines
modified:CHANGES+5 added-1 removed
47 unmodified lines
48- 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 lines
61- ``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`_)6869.. _#1489: https://github.com/pallets/flask/pull/148970.. _#1621: https://github.com/pallets/flask/pull/162171.. _#1898: https://github.com/pallets/flask/pull/1898
10 unmodified lines
82.. _#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/23488788Version 0.12.289--------------90
617 unmodified lines