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.
This commit is contained in:
Maik Hoepfel 2017-03-07 13:34:11 +08:00
parent 549df9d3ec
commit 57051a48cd
2 changed files with 8 additions and 6 deletions

View File

@ -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

View File

@ -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({