[1.6.x] Fixed #20557 -- Properly decoded non-ASCII cookies on Python 3.

Thanks mitsuhiko for the report.

Non-ASCII values are supported. Non-ASCII keys still aren't, because the
current parser mangles them. That's another bug.

Simplified backport of 8aaca651 and f5add47 from master.
This commit is contained in:
Aymeric Augustin 2013-09-07 10:41:02 -05:00
parent f855058c35
commit fac5735a3d
2 changed files with 23 additions and 3 deletions

View File

@ -12,6 +12,7 @@ from django.core.handlers import base
from django.core.urlresolvers import set_script_prefix
from django.utils import datastructures
from django.utils.encoding import force_str, force_text, iri_to_uri
from django.utils import six
# For backwards compatibility -- lots of code uses this in the wild!
from django.http.response import REASON_PHRASES as STATUS_CODE_TEXT
@ -147,7 +148,10 @@ class WSGIRequest(http.HttpRequest):
def _get_cookies(self):
if not hasattr(self, '_cookies'):
self._cookies = http.parse_cookie(self.environ.get('HTTP_COOKIE', ''))
raw_cookie = self.environ.get('HTTP_COOKIE', str(''))
if six.PY3:
raw_cookie = raw_cookie.encode('iso-8859-1').decode('utf-8')
self._cookies = http.parse_cookie(raw_cookie)
return self._cookies
def _set_cookies(self, cookies):

View File

@ -1,8 +1,14 @@
from django.core.handlers.wsgi import WSGIHandler
# coding: utf-8
from __future__ import unicode_literals
from django.core.handlers.wsgi import WSGIHandler, WSGIRequest
from django.core.signals import request_started, request_finished
from django.db import close_old_connections, connection
from django.test import RequestFactory, TestCase, TransactionTestCase
from django.test.utils import override_settings
from django.utils.encoding import force_str
from django.utils import six
class HandlerTests(TestCase):
@ -30,11 +36,21 @@ class HandlerTests(TestCase):
def test_bad_path_info(self):
"""Tests for bug #15672 ('request' referenced before assignment)"""
environ = RequestFactory().get('/').environ
environ['PATH_INFO'] = '\xed'
environ['PATH_INFO'] = b'\xed' if six.PY2 else '\xed'
handler = WSGIHandler()
response = handler(environ, lambda *a, **k: None)
self.assertEqual(response.status_code, 400)
def test_non_ascii_cookie(self):
"""Test that non-ASCII cookies set in JavaScript are properly decoded (#20557)."""
environ = RequestFactory().get('/').environ
raw_cookie = 'want="café"'
if six.PY3:
raw_cookie = raw_cookie.encode('utf-8').decode('iso-8859-1')
environ['HTTP_COOKIE'] = raw_cookie
request = WSGIRequest(environ)
self.assertEqual(request.COOKIES['want'], force_str("café"))
class TransactionsPerRequestTests(TransactionTestCase):