From 57051a48cd485c2dbb4a4c09d8c47f294ba75f06 Mon Sep 17 00:00:00 2001 From: Maik Hoepfel Date: Tue, 7 Mar 2017 13:34:11 +0800 Subject: [PATCH] Fix byte string issue in Python 2 Twisted seems to return a byte string for the client and server IP address. It is easily rectified by casting to the required unicode string. Also added a test to ensure this is also handled correctly in the X-Forwarded-For header parsing. --- daphne/http_protocol.py | 6 ++++-- daphne/tests/test_utils.py | 8 ++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/daphne/http_protocol.py b/daphne/http_protocol.py index b049899..e9ba7a6 100755 --- a/daphne/http_protocol.py +++ b/daphne/http_protocol.py @@ -63,8 +63,10 @@ class WebRequest(http.Request): upgrade_header = self.requestHeaders.getRawHeaders(b"Upgrade")[0] # Get client address if possible if hasattr(self.client, "host") and hasattr(self.client, "port"): - self.client_addr = [self.client.host, self.client.port] - self.server_addr = [self.host.host, self.host.port] + # client.host and host.host are byte strings in Python 2, but spec + # requires unicode string. + self.client_addr = [six.text_type(self.client.host), self.client.port] + self.server_addr = [six.text_type(self.host.host), self.host.port] else: self.client_addr = None self.server_addr = None diff --git a/daphne/tests/test_utils.py b/daphne/tests/test_utils.py index 61fe1a3..0431134 100644 --- a/daphne/tests/test_utils.py +++ b/daphne/tests/test_utils.py @@ -1,6 +1,7 @@ # coding: utf8 from __future__ import unicode_literals from unittest import TestCase +import six from twisted.web.http_headers import Headers @@ -17,10 +18,9 @@ class TestXForwardedForParsing(TestCase): b'X-Forwarded-For': [b'10.1.2.3'], b'X-Forwarded-Port': [b'1234'] }) - self.assertEqual( - parse_x_forwarded_for(headers), - ['10.1.2.3', 1234] - ) + result = parse_x_forwarded_for(headers) + self.assertEqual(result, ['10.1.2.3', 1234]) + self.assertIsInstance(result[0], six.text_type) def test_address_only(self): headers = Headers({