diff --git a/django/core/handlers/wsgi.py b/django/core/handlers/wsgi.py index 38d8154ac9..5769bee231 100644 --- a/django/core/handlers/wsgi.py +++ b/django/core/handlers/wsgi.py @@ -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): diff --git a/tests/handlers/tests.py b/tests/handlers/tests.py index 2f9f304b81..812dd3f22d 100644 --- a/tests/handlers/tests.py +++ b/tests/handlers/tests.py @@ -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):