Skip to content
Myr

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

4 files+86 added−8 removed

modified:docs/config.rst+20 added
79 unmodified lines
80``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================================= =========================================102103.. admonition:: More on ``SERVER_NAME``104
25 unmodified lines
130131.. versionadded:: 0.7132 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``133134.. versionadded:: 0.8135 ``TRAP_BAD_REQUEST_KEY_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``136137Configuring from Files138----------------------139140Configuration becomes more useful if you can configure from a file, and
127 unmodified lines
modified:flask/app.py+29 added-7 removed
17 unmodified lines
1819from werkzeug.datastructures import ImmutableDict20from werkzeug.routing import Map, Rule21from werkzeug.exceptions import HTTPException, InternalServerError, \22 MethodNotAllowed22 MethodNotAllowed, BadRequest2324from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25 locked_cached_property, _tojson_filter, _endpoint_from_view_func26from .wrappers import Request, Response
169 unmodified lines
196 '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 })204205 #: 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 lines
984 if handler is None:985 return e986 return handler(e)987988 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`.993994 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 False10051006 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 by
2 unmodified lines
1012 exception with the same traceback.10131014 .. 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)10001016 exc_type, exc_value, tb = sys.exc_info()1017 assert exc_value is e10181019 # 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)10251026 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 lines
modified:tests/flask_tests.py+35 added-1 removed
21 unmodified lines
22from contextlib import contextmanager23from functools import update_wrapper24from datetime import datetime25from werkzeug import parse_date, parse_options_header26from werkzeug.exceptions import NotFound26from werkzeug.exceptions import NotFound, BadRequest27from werkzeug.http import parse_set_header28from jinja2 import TemplateNotFound29from cStringIO import StringIO30
560 unmodified lines
591592 c = app.test_client()593 assert c.get('/').data == '42'594595 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 == 400603604 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')612613 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)620621 c = app.test_client()622 try:623 c.get('/fail')624 except NotFound, e:625 pass626 else:627 self.fail('Expected exception')628629 def test_teardown_on_pop(self):630 buffer = []631 app = flask.Flask(__name__)632 @app.teardown_request
1387 unmodified lines
modified:CHANGES+2 added
12 unmodified lines
13 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.1920Version 0.7.321-------------22
238 unmodified lines