summaryrefslogtreecommitdiff
path: root/cherrypy/lib/encoding.py
diff options
context:
space:
mode:
authorJason R. Coombs <jaraco@jaraco.com>2018-08-19 21:19:09 -0400
committerJason R. Coombs <jaraco@jaraco.com>2018-08-19 21:21:53 -0400
commitf89245c16994213544c9e05b52bebbd61fb07c53 (patch)
tree10f6d76e54aa841a6d05a1bdbd1e32a05731b66f /cherrypy/lib/encoding.py
parentf1f244ad9738b31f1a9910bcc3439039c496d011 (diff)
downloadcherrypy-git-f89245c16994213544c9e05b52bebbd61fb07c53.tar.gz
Consolidate prepare_iter behavior
Diffstat (limited to 'cherrypy/lib/encoding.py')
-rw-r--r--cherrypy/lib/encoding.py37
1 files changed, 24 insertions, 13 deletions
diff --git a/cherrypy/lib/encoding.py b/cherrypy/lib/encoding.py
index 0fc15225..3d001ca6 100644
--- a/cherrypy/lib/encoding.py
+++ b/cherrypy/lib/encoding.py
@@ -220,19 +220,7 @@ class ResponseEncoder:
response = cherrypy.serving.response
self.body = self.oldhandler(*args, **kwargs)
- if isinstance(self.body, text_or_bytes):
- # strings get wrapped in a list because iterating over a single
- # item list is much faster than iterating over every character
- # in a long string.
- if self.body:
- self.body = [self.body]
- else:
- # [''] doesn't evaluate to False, so replace it with [].
- self.body = []
- elif hasattr(self.body, 'read'):
- self.body = file_generator(self.body)
- elif self.body is None:
- self.body = []
+ self.body = prepare_iter(self.body)
ct = response.headers.elements('Content-Type')
if self.debug:
@@ -269,6 +257,29 @@ class ResponseEncoder:
return self.body
+
+def prepare_iter(value):
+ """
+ Ensure response body is iterable and resolves to False when empty.
+ """
+ if isinstance(value, text_or_bytes):
+ # strings get wrapped in a list because iterating over a single
+ # item list is much faster than iterating over every character
+ # in a long string.
+ if value:
+ value = [value]
+ else:
+ # [''] doesn't evaluate to False, so replace it with [].
+ value = []
+ # Don't use isinstance here; io.IOBase which has an ABC takes
+ # 1000 times as long as, say, isinstance(value, str)
+ elif hasattr(value, 'read'):
+ value = file_generator(value)
+ elif value is None:
+ value = []
+ return value
+
+
# GZIP