bottlepy / bottle

bottle.py is a fast and simple micro-framework for python web-applications.
http://bottlepy.org/
MIT License
8.44k stars 1.47k forks source link

Assertion on Non-ASCII HeaderDict keys when run with Python 2.x #914

Open bnbdr opened 7 years ago

bnbdr commented 7 years ago

Python asserts that header names are StringType, which crashes the code whenever unicode strings are used directly as keys in python 2.x, or when someone uses unicode_literals from __future__ in their python 2/3 compatible code.

Reproducible sample:

from __future__ import unicode_literals
import bottle

@bottle.route('/')
def index():
    bottle.response.headers['Content-Encoding'] = ''
    return ''

if __name__ == '__main__':
    bottle.run()

possible solution could be normalizing the key returned from _hkey

return str(s.title()).replace('_', '-')
eric-wieser commented 7 years ago

Does python 3 allow unicode headers?

bnbdr commented 7 years ago

Yes. You can run the sample I provided without issue using python3.

eric-wieser commented 7 years ago

In fact, python 3 will complain if you use bytes, it seems

bnbdr commented 7 years ago

Seems reasonable to support the literal-string type of the running python environment; unicode_literals changes the type for the caller's module, and not bottle's. My proposed change simply enforces the real literal-type that bottle(and probably the underlying framework) expects.

defnull commented 7 years ago

Bottle expects 'native strings' (str() type) most of the time. Using from __future__ import unicode_literals will probably break a lot more than just headers.

BubaVV commented 6 years ago

Looks strange that header values are converted to Unicode, but keys are only normalized. Added uniform conversion to keys also - issue is gone