Reputation: 360
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. 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
[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?
Upvotes: 2
Views: 1621
Reputation: 20709
You are accessing a key that doesn't exist. Python dictionaries provide a get
method to help with this
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.
Upvotes: 3