Skip to content

Commit

Permalink
Fixed #5956 -- Added a better error description for non-ASCII HTTP he…
Browse files Browse the repository at this point in the history
…aders. Patch from jvloothuis.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@6927 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
malcolmt committed Dec 17, 2007
1 parent 1fcb4e4 commit 03f1eb2
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
13 changes: 13 additions & 0 deletions django/http/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,20 @@ def __str__(self):
for key, value in self._headers.values()]) \
+ '\n\n' + self.content

def _convert_to_ascii(self, *values):
"Convert all values to ascii strings"
for value in values:
if isinstance(value, unicode):
try:
yield value.encode('us-ascii')
except UnicodeError, e:
e.reason += ', HTTP response headers must be in US-ASCII format'
raise
else:
yield str(value)

def __setitem__(self, header, value):
header, value = self._convert_to_ascii(header, value)
self._headers[header.lower()] = (header, value)

def __delitem__(self, header):
Expand Down
36 changes: 35 additions & 1 deletion tests/regressiontests/httpwrappers/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,9 +391,43 @@
>>> q.getlist('foo')
[u'bar', u'\ufffd']
######################################
# HttpResponse with Unicode headers #
######################################
>>> r = HttpResponse()
If we insert a unicode value it will be converted to an ascii
string. This makes sure we comply with the HTTP specifications.
>>> r['value'] = u'test value'
>>> isinstance(r['value'], str)
True
An error is raised When a unicode object with non-ascii is assigned.
>>> r['value'] = u't\xebst value' # doctest:+ELLIPSIS
Traceback (most recent call last):
...
UnicodeEncodeError: ..., HTTP response headers must be in US-ASCII format
The response also converts unicode keys to strings.
>>> r[u'test'] = 'testing key'
>>> list(sorted(r.items()))[1]
('test', 'testing key')
It will also raise errors for keys with non-ascii data.
>>> r[u't\xebst'] = 'testing key' # doctest:+ELLIPSIS
Traceback (most recent call last):
...
UnicodeEncodeError: ..., HTTP response headers must be in US-ASCII format
"""

from django.http import QueryDict
from django.http import QueryDict, HttpResponse

if __name__ == "__main__":
import doctest
Expand Down

0 comments on commit 03f1eb2

Please sign in to comment.