如何在Flask上修复“ KeyError:'log_context'”

时间:2019-03-27 10:50:31

标签: python flask

我正在为一台服务器使用较旧的版本(因为某些依赖项)。我将服务器设置在Docker容器中,并且直到今天工作正常。当我重建映像并重新运行服务时,它会收到此错误:

Exception on /messages [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1379, in handle_user_exception
    return handler(e)
  File "/opt/sync-engine/inbox/api/ns_api.py", line 226, in handle_input_error
    request.environ['log_context']['error'] = error.__class__.__name__
KeyError: 'log_context'
{"module": "inbox.api.srv:28", "level": "error", "event": "Uncaught error thrown by Flask/Werkzeug", "timestamp": "2019-03-27T10:36:55.760581Z", "greenlet_id": 140055343249040}

srv.py(inbox.api.srv):

...
def default_json_error(ex):
    """ Exception -> flask JSON responder """
    logger = get_logger()
    logger.error('Uncaught error thrown by Flask/Werkzeug', exc_info=ex)
    response = jsonify(message=str(ex), type='api_error')
    response.status_code = (ex.code
                            if isinstance(ex, HTTPException)
                            else 500)
    return response
...

ns_api.py:

...
@app.errorhandler(APIException)
def handle_input_error(error):
    # these "errors" are normal, so we don't need to save a traceback
    request.environ['log_context']['error'] = error.__class__.__name__
    request.environ['log_context']['error_message'] = error.message
    response = flask_jsonify(message=error.message,
                             type='invalid_request_error')
    response.status_code = error.status_code
    return response
...

1 个答案:

答案 0 :(得分:0)

主要原因:

  

log_context中没有request.environ

要解决此问题,只需初始化log_context

request.environ.setdefault('log_context', dict())
# etc...
request.environ['log_context']['error'] = error.__class__.__name__

希望这会有所帮助。