Added HTTP exception trapping. This should fix #294
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent a070b4f · Browse files · 4 files·+86 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
4 files+86 added−8 removed
- tests:+35 added−1 removed
- other:+51 added−7 removed
Provenance
- Commit
7155f11- Tree
a53f69d- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
a070b4f
4 files changed+86 added−8 removed
modified:docs/config.rst+20 added
79 unmodified lines80 ``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will81 reject incoming requests with a82 content length greater than this by83 returning a 413 status code.84+``TRAP_HTTP_EXCEPTIONS`` If this is set to ``True`` Flask will85+ not execute the error handlers of HTTP86+ exceptions but instead treat the87+ exception like any other and bubble it88+ through the exception stack. This is89+ helpful for hairy debugging situations90+ where you have to find out where an HTTP91+ exception is coming from.92+``TRAP_BAD_REQUEST_KEY_ERRORS`` Werkzeug's internal data structures that93+ deal with request specific data will94+ raise special key errors that are also95+ bad request exceptions. By default96+ these will be converted into 40097+ responses which however can make98+ debugging some issues harder. If this99+ config is set to ``True`` you will get100+ a regular traceback instead.101 ================================= =========================================102 103 .. admonition:: More on ``SERVER_NAME``104 25 unmodified lines130 131 .. versionadded:: 0.7132 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``133 134+.. versionadded:: 0.8135+ ``TRAP_BAD_REQUEST_KEY_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``136+137 Configuring from Files138 ----------------------139 140 Configuration becomes more useful if you can configure from a file, and127 unmodified linesmodified:flask/app.py+29 added-7 removed
17 unmodified lines18 19 from werkzeug.datastructures import ImmutableDict20 from werkzeug.routing import Map, Rule21 from werkzeug.exceptions import HTTPException, InternalServerError, \22- MethodNotAllowed22+ MethodNotAllowed, BadRequest23 24 from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25 locked_cached_property, _tojson_filter, _endpoint_from_view_func26 from .wrappers import Request, Response169 unmodified lines196 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),197 'USE_X_SENDFILE': False,198 'LOGGER_NAME': None,199 'SERVER_NAME': None,200- 'MAX_CONTENT_LENGTH': None200+ 'MAX_CONTENT_LENGTH': None,201+ 'TRAP_BAD_REQUEST_KEY_ERRORS': False,202+ 'TRAP_HTTP_EXCEPTIONS': False203 })204 205 #: The rule object to use for URL rules created. This is used by206 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.777 unmodified lines984 if handler is None:985 return e986 return handler(e)987 988+ def trap_http_exception(self, e):989+ """Checks if an HTTP exception should be trapped or not. By default990+ this will return `False` for all exceptions except for a bad request991+ key error if ``TRAP_BAD_REQUEST_KEY_ERRORS`` is set to `True`. It992+ also returns `True` if ``TRAP_HTTP_EXCEPTIONS`` is set to `True`.993+994+ This is called for all HTTP exceptions raised by a view function.995+ If it returns `True` for any exception the error handler for this996+ exception is not called and it shows up as regular exception in the997+ traceback. This is helpful for debugging implicitly raised HTTP998+ exceptions.999+ """1000+ if self.config['TRAP_HTTP_EXCEPTIONS']:1001+ return True1002+ if self.config['TRAP_BAD_REQUEST_KEY_ERRORS']:1003+ return isinstance(e, BadRequest) and isinstance(e, LookupError)1004+ return False1005+1006 def handle_user_exception(self, e):1007 """This method is called whenever an exception occurs that should be1008 handled. A special case are1009 :class:`~werkzeug.exception.HTTPException`\s which are forwarded by2 unmodified lines1012 exception with the same traceback.1013 1014 .. versionadded:: 0.71015 """996- # ensure not to trash sys.exc_info() at that point in case someone997- # wants the traceback preserved in handle_http_exception.998- if isinstance(e, HTTPException):999- return self.handle_http_exception(e)1000-1016 exc_type, exc_value, tb = sys.exc_info()1017 assert exc_value is e1018 1019+ # ensure not to trash sys.exc_info() at that point in case someone1020+ # wants the traceback preserved in handle_http_exception. Of course1021+ # we cannot prevent users from trashing it themselves in a custom1022+ # trap_http_exception method so that's their fault then.1023+ if isinstance(e, HTTPException) and not self.trap_http_exception(e):1024+ return self.handle_http_exception(e)1025+1026 blueprint_handlers = ()1027 handlers = self.error_handler_spec.get(request.blueprint)1028 if handlers is not None:1029 blueprint_handlers = handlers.get(None, ())319 unmodified linesmodified:tests/flask_tests.py+35 added-1 removed
21 unmodified lines22 from contextlib import contextmanager23 from functools import update_wrapper24 from datetime import datetime25 from werkzeug import parse_date, parse_options_header26-from werkzeug.exceptions import NotFound26+from werkzeug.exceptions import NotFound, BadRequest27 from werkzeug.http import parse_set_header28 from jinja2 import TemplateNotFound29 from cStringIO import StringIO30 560 unmodified lines591 592 c = app.test_client()593 assert c.get('/').data == '42'594 595+ def test_trapping_of_bad_request_key_errors(self):596+ app = flask.Flask(__name__)597+ app.testing = True598+ @app.route('/fail')599+ def fail():600+ flask.request.form['missing_key']601+ c = app.test_client()602+ assert c.get('/fail').status_code == 400603+604+ app.config['TRAP_BAD_REQUEST_KEY_ERRORS'] = True605+ c = app.test_client()606+ try:607+ c.get('/fail')608+ except KeyError, e:609+ assert isinstance(e, BadRequest)610+ else:611+ self.fail('Expected exception')612+613+ def test_trapping_of_all_http_exceptions(self):614+ app = flask.Flask(__name__)615+ app.testing = True616+ app.config['TRAP_HTTP_EXCEPTIONS'] = True617+ @app.route('/fail')618+ def fail():619+ flask.abort(404)620+621+ c = app.test_client()622+ try:623+ c.get('/fail')624+ except NotFound, e:625+ pass626+ else:627+ self.fail('Expected exception')628+629 def test_teardown_on_pop(self):630 buffer = []631 app = flask.Flask(__name__)632 @app.teardown_request1387 unmodified linesmodified:CHANGES+2 added
12 unmodified lines13 having to override the Flask class.14 - Empty session cookies are now deleted properly automatically.15 - View functions can now opt out of getting the automatic16 OPTIONS implementation.17+- HTTP exceptions and Bad Request Key Errors can now be trapped so that they18+ show up normally in the traceback.19 20 Version 0.7.321 -------------22 238 unmodified lines