简体   繁体   English

Gunicorn 抛出 KeyError 导致内部服务器错误

[英]Gunicorn throws KeyError resulting in Internal Server Error

In my flask app I have在我的烧瓶应用程序中,我有

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024

class StreamConsumingMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
          stream = LimitedStream(environ['wsgi.input'], int(environ['CONTENT_LENGTH'] or 0))
          environ['wsgi.input'] = stream
          app_iter = self.app(environ, start_response)
          try:
              stream.exhaust()
              for event in app_iter:
                  yield event
          finally:
              if hasattr(app_iter, 'close'):
                  app_iter.close()

app.wsgi_app = StreamConsumingMiddleware(app.wsgi_app)

When I simply run the app using python app.py it works as expected.当我简单地使用python app.py运行应用程序时,它按预期工作。 However, launching with Gunicorn gunicorn app:app , the app starts just fine, but trying to load any page results in a 500, and throws a KeyError但是,使用gunicorn app:app gunicorn gunicorn app:app启动,应用程序启动得很好,但尝试加载任何页面都会导致 500,并引发 KeyError

[2015-11-08 17:36:53 -0500] [15848] [ERROR] Error handling request
Traceback (most recent call last):
  File "[...]/venv/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 130, in handle
    self.handle_request(listener, req, client, addr)
  File "[...]/venv/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
    for item in respiter:
  File "[...]/app.py", line 33, in __call__
    stream = LimitedStream(environ['wsgi.input'], int(environ['CONTENT_LENGTH'] or 0))
KeyError: 'CONTENT_LENGTH'

Any ideas?有任何想法吗?

You are accessing a key that doesn't exist.您正在访问一个不存在的密钥。 Python dictionaries provide a get method to help with this Python 字典提供了一个get方法来帮助解决这个问题

int(os.environ.get('CONTENT_LENGTH', 0))

This will return the value of os.environ['CONTENT_LENGTH'] if the key exists or 0 if it doesn't.如果键存在,这将返回os.environ['CONTENT_LENGTH']的值,否则返回 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM