From f091d82badc35116a45d59560f85cc6176980780 Mon Sep 17 00:00:00 2001 From: cr0hn Date: Fri, 23 Dec 2016 13:12:59 +0100 Subject: [PATCH 1/3] Improvement improvement: support fo binary data as a input. This do that the response process has more performance because not encoding needed. --- sanic/response.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sanic/response.py b/sanic/response.py index 15130edd..1f86a807 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -79,7 +79,9 @@ class HTTPResponse: self.content_type = content_type if body is not None: - self.body = body.encode('utf-8') + self.body = body + if type(body) is str: + self.body = body.encode('utf-8') else: self.body = body_bytes From cc982c5a61ef9523e3565b9d3d014f404d4141ec Mon Sep 17 00:00:00 2001 From: cr0hn Date: Sat, 24 Dec 2016 15:24:25 +0100 Subject: [PATCH 2/3] Update response.py Type check by isinstance --- sanic/response.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sanic/response.py b/sanic/response.py index 1f86a807..c09c8dbd 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -80,7 +80,7 @@ class HTTPResponse: if body is not None: self.body = body - if type(body) is str: + if isinstance(body, str): self.body = body.encode('utf-8') else: self.body = body_bytes From d7e94473f3c350a1c3ec49e79f3a7e6c711b8842 Mon Sep 17 00:00:00 2001 From: Eli Uriegas Date: Sat, 24 Dec 2016 18:37:55 -0800 Subject: [PATCH 3/3] Use a try/except, it's a bit faster Also reorder some imports and add some comments --- sanic/response.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/sanic/response.py b/sanic/response.py index c09c8dbd..2c4c7f27 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -1,9 +1,11 @@ from aiofiles import open as open_async -from .cookies import CookieJar from mimetypes import guess_type from os import path + from ujson import dumps as json_dumps +from .cookies import CookieJar + COMMON_STATUS_CODES = { 200: b'OK', 400: b'Bad Request', @@ -79,9 +81,12 @@ class HTTPResponse: self.content_type = content_type if body is not None: - self.body = body - if isinstance(body, str): + try: + # Try to encode it regularly self.body = body.encode('utf-8') + except AttributeError: + # Convert it to a str if you can't + self.body = str(body).encode('utf-8') else: self.body = body_bytes