Add headers in a Flask app with unicode_literals Add headers in a Flask app with unicode_literals flask flask

Add headers in a Flask app with unicode_literals


This problem is indeed due to a bug in Werkzeug. As you noticed, this is now corrected since Jun 4, 2013 (cf. the related commit on Github). You can have a bug free version of Werkzeug by using the version 0.9.5 instead of the 0.9.4.

Moreover, to troubleshoot your problem, I added app.debug = True just after the initialization of your Flask application. This allows me to got the following error in uWSGI logs:

Traceback (most recent call last):  File "/home/afigura/.virtualenvs/stack-python2/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__    return self.wsgi_app(environ, start_response)  File "/home/afigura/.virtualenvs/stack-python2/lib/python2.7/site-packages/flask/app.py", line 1821, in wsgi_app    return response(environ, start_response)  File "/home/afigura/.virtualenvs/stack-python2/lib/python2.7/site-packages/werkzeug/wrappers.py", line 1201, in __call__    start_response(status, headers)TypeError: http header key must be a string

This corresponds to the error mentioned in the bug you found on Github.

So, you can use the following workaround to get Flask/Werkzeug working with unicode_literals:

response.headers = {b'WWW-Authenticate': 'Basic realm="test"'}

Or:

response.headers = {str('WWW-Authenticate'): 'Basic realm="test"'}

But I recommend to simply update your Werkzeug version to >=0.9.5 if you can.

Also, please note that although the headers attribute of a Flask/Werkzeug response behaves like a dictionary, it is in fact a Headers object (see Werkzeug source code). Hence, I advise you to use it as follows:

response.headers['WWW-Authenticate'] = 'Basic realm="test"'

You can see some examples about this on the Flask documentation of the function make_response.