From 6d1996c449d4cacded23b72b0fc0fd5ded53fbb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=2E=20K=C3=A4rkk=C3=A4inen?= Date: Wed, 11 Sep 2019 12:24:33 +0300 Subject: [PATCH] -to-str response autoconversion limited to sanic.response.text() only. --- sanic/response.py | 22 ++++++++++------------ tests/test_response.py | 3 ++- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/sanic/response.py b/sanic/response.py index 26a2f885..34339209 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -23,18 +23,7 @@ except ImportError: class BaseHTTPResponse: def _encode_body(self, data): - # Replace the entire function with this once past deprecation: - # return data.encode() if hasattr(data, "encode") else data - # Deprecation fallbacks: - if hasattr(data, "encode"): - return data.encode() - try: - # Test if data is bytes-ish (implements the buffer protocol) - with memoryview(data): - return data - except TypeError: - # This is deprecated and quite b0rked (issue warning here?) - return f"{data}".encode() + return data.encode() if hasattr(data, "encode") else data def _parse_headers(self): return format_http1(self.headers.items()) @@ -203,6 +192,15 @@ def text( :param headers: Custom Headers. :param content_type: the content type (string) of the response """ + # Type conversions are deprecated and quite b0rked but still supported for + # text() until applications get fixed. This try-except should be removed. + try: + # Avoid repr(body).encode() b0rkage for body that is already encoded. + # memoryview used only to test bytes-ishness. + with memoryview(body): + pass + except TypeError: + body = f"{body}" # no-op if body is already str return HTTPResponse( body, status=status, headers=headers, content_type=content_type ) diff --git a/tests/test_response.py b/tests/test_response.py index 8feadb06..011d853d 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -20,6 +20,7 @@ from sanic.response import ( json, raw, stream, + text, ) from sanic.server import HttpProtocol from sanic.testing import HOST, PORT @@ -34,7 +35,7 @@ def test_response_body_not_a_string(app): @app.route("/hello") async def hello_route(request): - return HTTPResponse(body=random_num) + return text(random_num) request, response = app.test_client.get("/hello") assert response.text == str(random_num)