Skip to content
Myr

Fixed after_request handlers being called twice in some cases and improved logging system

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 bc00fd1 · Browse files · 3 files+51 added−24 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+51 added−24 removed

  • tests:+12 added−4 removed
  • other:+39 added−20 removed

3 files+51 added−24 removed

modified:tests/flask_tests.py+12 added-4 removed
286 unmodified lines
287 assert 'Internal Server Error' in rv.data288 assert len(called) == 1289290 def test_after_request_handler_error(self):291 error_out = StringIO()291 called = []292 app = flask.Flask(__name__)293 app.logger.addHandler(StreamHandler(error_out))293 @app.after_request294 def after_request(response):295 called.append(True)296 1/0297 return response298 @app.route('/')299 def fails():300 1/0301 rv = app.test_client().get('/')302 assert rv.status_code == 500303 assert 'Internal Server Error' in rv.data304 assert 'after_request handler failed' in error_out.getvalue()304 assert len(called) == 1305306 def test_error_handling(self):307 app = flask.Flask(__name__)308 @app.errorhandler(404)
397 unmodified lines
706707708class LoggingTestCase(unittest.TestCase):709710 def test_logger_cache(self):711 app = flask.Flask(__name__)712 logger1 = app.logger713 assert app.logger is logger1714 assert logger1.name == __name__715 app.logger_name = __name__ + '/test_logger_cache'716 assert app.logger is not logger1717718 def test_debug_log(self):719 app = flask.Flask(__name__)720 app.debug = True721 @app.route('/')
21 unmodified lines
743 else:744 assert False, 'debug log ate the exception'745746 def test_exception_logging(self):739 from logging import StreamHandler747 out = StringIO()748 app = flask.Flask(__name__)749 app.logger_name = 'flask_tests/test_exception_logging'750 app.logger.addHandler(StreamHandler(out))751752 @app.route('/')753 def index():
102 unmodified lines
modified:CHANGES+2 added
14 unmodified lines
15 kicks in.16- test client has not the ability to preserve the request context17 for a little longer. This can also be used to trigger custom18 requests that do not pop the request stack for testing.19- because the Python standard library caches loggers, the name of20 the logger is configurable now to better support unittests.2122Version 0.3.123-------------24
48 unmodified lines
modified:flask.py+37 added-20 removed
14 unmodified lines
15import mimetypes16from datetime import datetime, timedelta1718from itertools import chain19from threading import Lock20from jinja2 import Environment, PackageLoader, FileSystemLoader21from werkzeug import Request as RequestBase, Response as ResponseBase, \22 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \23 ImmutableDict, cached_property, wrap_file, Headers, \
26 unmodified lines
50 pkg_resources.resource_stream51except (ImportError, AttributeError):52 pkg_resources = None5354# a lock used for logger initialization55_logger_lock = Lock()565758class Request(RequestBase):59 """The request object used by default in flask. Remembers the60 matched endpoint and view arguments.61
780 unmodified lines
842 #: This attribute can also be configured from the config with the843 #: `USE_X_SENDFILE` configuration key. Defaults to `False`.844 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')845846 #: the name of the logger to use. By default the logger name is the847 #: package name passed to the constructor.848 #:849 #: .. versionadded:: 0.4850 logger_name = ConfigAttribute('LOGGER_NAME')851852 #: the logging format used for the debug logger. This is only used when853 #: the application is in debug mode, otherwise the attached logging854 #: handler does the formatting.855 #:
16 unmodified lines
872 'DEBUG': False,873 'SECRET_KEY': None,874 'SESSION_COOKIE_NAME': 'session',875 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),866 'USE_X_SENDFILE': False876 'USE_X_SENDFILE': False,877 'LOGGER_NAME': None878 })879880 def __init__(self, import_name):881 _PackageBoundObject.__init__(self, import_name)
2 unmodified lines
884 #: exactly like a regular dictionary but supports additional methods885 #: to load a config from files.886 self.config = Config(self.root_path, self.default_config)887888 #: prepare the deferred setup of the logger889 self._logger = None890 self.logger_name = self.import_name891892 #: a dictionary of all view functions registered. The keys will893 #: be function names which are also used to generate URLs and894 #: the values are the function objects themselves.895 #: to register a view function, use the :meth:`route` decorator.
70 unmodified lines
966 get_flashed_messages=get_flashed_messages967 )968 self.jinja_env.filters['tojson'] = _tojson_filter969955 @cached_property970 @property971 def logger(self):972 """A :class:`logging.Logger` object for this application. The973 default configuration is to log to stderr if the application is974 in debug mode. This logger can be used to (surprise) log messages.
4 unmodified lines
979 app.logger.error('An error occoured')980981 .. versionadded:: 0.3982 """983 if self._logger and self._logger.name == self.logger_name:984 return self._logger985 with _logger_lock:986 if self._logger and self._logger.name == self.logger_name:987 return self._logger968 from logging import getLogger, StreamHandler, Formatter, DEBUG969 class DebugHandler(StreamHandler):970 def emit(x, record):971 if self.debug:972 StreamHandler.emit(x, record)973 handler = DebugHandler()974 handler.setLevel(DEBUG)975 handler.setFormatter(Formatter(self.debug_log_format))976 logger = getLogger(self.import_name)977 logger.addHandler(handler)978 return logger988 from logging import getLogger, StreamHandler, Formatter, DEBUG989 class DebugHandler(StreamHandler):990 def emit(x, record):991 if self.debug:992 StreamHandler.emit(x, record)993 handler = DebugHandler()994 handler.setLevel(DEBUG)995 handler.setFormatter(Formatter(self.debug_log_format))996 logger = getLogger(self.logger_name)997 logger.addHandler(handler)998 self._logger = logger999 return logger10001001 def create_jinja_loader(self):1002 """Creates the Jinja loader. By default just a package loader for1003 the configured package is returned that looks up templates in the
428 unmodified lines
1432 rv = self.preprocess_request()1433 if rv is None:1434 rv = self.dispatch_request()1435 response = self.make_response(rv)1436 except Exception, e:1437 response = self.make_response(self.handle_exception(e))1438 try:1439 response = self.process_response(response)1440 except Exception, e:1441 response = self.make_response(self.handle_exception(e))1418 try:1419 response = self.process_response(response)1420 except Exception, e:1421 self.logger.exception('after_request handler failed '1422 'to postprocess error response. '1423 'Depending on uncertain state?')14241442 return response(environ, start_response)14431444 def request_context(self, environ):1445 """Creates a request context from the given environment and binds
55 unmodified lines