KeyError: 'HTTP_ACCESS_TOKEN' : Flask with gevent WSGIServer

Question:

I am trying to take my Flask application to production with gevent WSGIServer

if __name__ == "__main__":

    app_host = "0.0.0.0"
    app_port = "8080"
    #app.run(host=app_host, port=app_port, debug=False)

    http_server = WSGIServer((app_host, app_port), app)
    logging.info("Starting the App server")
    http_server.serve_forever()

I am running the app server with gevent WSGIServer. Whenever I am trying to fetch any data like

token = request.headers["access_token"]

Receiving the following error

File "app.py", line 62, in post
token = request.headers["access_token"]
File "/home/shravan40/.local/lib/python3.6/site-packages/werkzeug/datastructures.py", line 1463, in __getitem__
return _unicodify_header_value(self.environ["HTTP_" + key])
KeyError: 'HTTP_ACCESS_TOKEN'
2020-08-03T18:01:31Z {'REMOTE_ADDR': '::ffff:127.0.0.1', 'REMOTE_PORT': '55088', 'HTTP_HOST': '127.0.0.1:8080', (hidden keys: 26)} failed with KeyError
Asked By: Shravan40

||

Answers:

pywsgi has something called SecureEnviron. This is intended to keep potentially sensitive information like HTTP authorization and cookies from being inadvertently printed or logged.

One can read more at the official documentation

Since I was passing access_token as key in the headers and trying to access the same from the code, it was raising KeyError: 'HTTP_ACCESS_TOKEN' because wasn’t part of whitelist_keys.

I used Authorization as header key and it worked like charm. The same can be done by adding access_token into the whitelist_keys.

Answered By: Shravan40

Not only headers like ACCESS_TOKEN, even arbitrary header names have this problem: A header like

header = {'MY_DEAR_RAJA' : '3AB690CDF3B'}

raised an error at the server, specifically in the line:

site-packageswerkzeugdatastructures.py", in getitem return unicodify_header_value(self.environ["HTTP" + key])

I found that my use of underscores in the key name was the problem. When I changed them to hyphens it fixed the issue:

header = {'MY-DEAR-RAJA' : '3AB690CDF3B'}
Answered By: Raja
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.