Skip to content

Commit 5502c40

Browse files
committed
Pass content directly to Response()
This allows passing an iterable of strings or bytes to serve_content() so that it can be returned using chunked encoding.
1 parent bc0d4d6 commit 5502c40

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

pytest_localserver/http.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def __call__(self, environ, start_response):
8080
else:
8181
content = self.content
8282

83-
response = Response(status=self.code)
83+
response = Response(response=self.content, status=self.code)
8484
response.headers.clear()
8585
response.headers.extend(self.headers)
8686

@@ -89,7 +89,6 @@ def __call__(self, environ, start_response):
8989
# content = gzip.compress(content.encode('utf-8'))
9090
# response.content_encoding = 'gzip'
9191

92-
response.data = content
9392
return response(environ, start_response)
9493

9594
def serve_content(self, content, code=200, headers=None):
@@ -101,6 +100,17 @@ def serve_content(self, content, code=200, headers=None):
101100
:param code: HTTP status code
102101
:param headers: HTTP headers to be returned
103102
"""
103+
if not isinstance(content, (str, bytes, list, tuple)):
104+
# If content is an iterable which is not known to be a string,
105+
# bytes, or sequence, it might be something that can only be iterated
106+
# through once, in which case we need to cache it so it can be reused
107+
# to handle multiple requests.
108+
try:
109+
content = tuple(iter(content))
110+
except TypeError:
111+
# this probably means that content is not iterable, so just go
112+
# ahead in case it's some type that Response knows how to handle
113+
pass
104114
self.content, self.code = (content, code)
105115
if headers:
106116
self.headers = headers

0 commit comments

Comments
 (0)