<any type>-to-str response autoconversion limited to sanic.response.text() only.

This commit is contained in:
L. Kärkkäinen 2019-09-11 12:24:33 +03:00
parent 13a2f487f7
commit 6d1996c449
2 changed files with 12 additions and 13 deletions

View File

@ -23,18 +23,7 @@ except ImportError:
class BaseHTTPResponse: class BaseHTTPResponse:
def _encode_body(self, data): def _encode_body(self, data):
# Replace the entire function with this once past deprecation: return data.encode() if hasattr(data, "encode") else data
# 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()
def _parse_headers(self): def _parse_headers(self):
return format_http1(self.headers.items()) return format_http1(self.headers.items())
@ -203,6 +192,15 @@ def text(
:param headers: Custom Headers. :param headers: Custom Headers.
:param content_type: the content type (string) of the response :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( return HTTPResponse(
body, status=status, headers=headers, content_type=content_type body, status=status, headers=headers, content_type=content_type
) )

View File

@ -20,6 +20,7 @@ from sanic.response import (
json, json,
raw, raw,
stream, stream,
text,
) )
from sanic.server import HttpProtocol from sanic.server import HttpProtocol
from sanic.testing import HOST, PORT from sanic.testing import HOST, PORT
@ -34,7 +35,7 @@ def test_response_body_not_a_string(app):
@app.route("/hello") @app.route("/hello")
async def hello_route(request): async def hello_route(request):
return HTTPResponse(body=random_num) return text(random_num)
request, response = app.test_client.get("/hello") request, response = app.test_client.get("/hello")
assert response.text == str(random_num) assert response.text == str(random_num)