diff --git a/sanic/response.py b/sanic/response.py index 2c4c7f27..f2eb02e5 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -103,10 +103,14 @@ class HTTPResponse: headers = b'' if self.headers: - headers = b''.join( - b'%b: %b\r\n' % (name.encode(), value.encode('utf-8')) - for name, value in self.headers.items() - ) + for name, value in self.headers.items(): + try: + headers += ( + b'%b: %b\r\n' % (name.encode(), value.encode('utf-8'))) + except AttributeError: + headers += ( + b'%b: %b\r\n' % ( + str(name).encode(), str(value).encode('utf-8'))) # Try to pull from the common codes first # Speeds up response rate 6% over pulling from all diff --git a/tests/test_requests.py b/tests/test_requests.py index 5895e3d5..13225892 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -33,6 +33,31 @@ def test_text(): assert response.text == 'Hello' +def test_headers(): + app = Sanic('test_text') + + @app.route('/') + async def handler(request): + headers = {"spam": "great"} + return text('Hello', headers=headers) + + request, response = sanic_endpoint_test(app) + + assert response.headers.get('spam') == 'great' + + +def test_non_str_headers(): + app = Sanic('test_text') + + @app.route('/') + async def handler(request): + headers = {"answer": 42} + return text('Hello', headers=headers) + + request, response = sanic_endpoint_test(app) + + assert response.headers.get('answer') == '42' + def test_invalid_response(): app = Sanic('test_invalid_response') @@ -47,8 +72,8 @@ def test_invalid_response(): request, response = sanic_endpoint_test(app) assert response.status == 500 assert response.text == "Internal Server Error." - - + + def test_json(): app = Sanic('test_json')