From 91e7d138dcff4226aaf76b31905bff5cebcf6d40 Mon Sep 17 00:00:00 2001 From: benoitc Date: Fri, 16 Nov 2012 09:57:35 +0100 Subject: [PATCH] fix header encoding --- examples/test.py | 3 ++- gunicorn/http/wsgi.py | 9 +++++---- gunicorn/util.py | 7 +++++++ 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/examples/test.py b/examples/test.py index c61f672e..44283565 100644 --- a/examples/test.py +++ b/examples/test.py @@ -18,7 +18,8 @@ def app(environ, start_response): response_headers = [ ('Content-type','text/plain'), ('Content-Length', str(len(data))), - ('X-Gunicorn-Version', __version__) + ('X-Gunicorn-Version', __version__), + ("Test", "test ั‚ะตัั‚"), ] start_response(status, response_headers) return iter([data]) diff --git a/gunicorn/http/wsgi.py b/gunicorn/http/wsgi.py index a32c2573..bb3c3f24 100644 --- a/gunicorn/http/wsgi.py +++ b/gunicorn/http/wsgi.py @@ -210,6 +210,7 @@ class Response(object): def process_headers(self, headers): for name, value in headers: assert isinstance(name, string_types), "%r is not a string" % name + lname = name.lower().strip() if lname == "content-length": self.response_length = int(value) @@ -220,11 +221,11 @@ class Response(object): self.upgrade = True elif lname == "upgrade": if value.lower().strip() == "websocket": - self.headers.append((name.strip(), str(value).strip())) + self.headers.append((name.strip(), value.strip())) # ignore hopbyhop headers continue - self.headers.append((name.strip(), str(value).strip())) + self.headers.append((name.strip(), str(value.strip()))) def is_chunked(self): @@ -265,10 +266,10 @@ class Response(object): if self.headers_sent: return tosend = self.default_headers() - tosend.extend(["%s: %s\r\n" % (n, v) for n, v in self.headers]) + tosend.extend(["%s: %s\r\n" % (k,v) for k, v in self.headers]) header_str = "%s\r\n" % "".join(tosend) - util.write(self.sock, header_str.encode('latin1')) + util.write(self.sock, util.to_bytestring(header_str)) self.headers_sent = True def write(self, arg): diff --git a/gunicorn/util.py b/gunicorn/util.py index f367d2e3..cf976b6e 100644 --- a/gunicorn/util.py +++ b/gunicorn/util.py @@ -348,3 +348,10 @@ def check_is_writeable(path): except IOError as e: raise RuntimeError("Error: '%s' isn't writable [%r]" % (path, e)) f.close() + +def to_bytestring(value): + """Converts a string argument to a byte string""" + if isinstance(value, bytes): + return value + assert isinstance(value, text_type) + return value.encode("utf-8")