diff options
| author | Martin Thurau <martin@keeeb.com> | 2016-06-29 11:47:39 +0200 |
|---|---|---|
| committer | Martin Thurau <martin@keeeb.com> | 2016-06-29 11:47:39 +0200 |
| commit | d7ab30047633147fe8e03d0210eb23d2001bdab7 (patch) | |
| tree | 0389e71f55115e00d139b3d5c6c54cf79b28917c | |
| parent | 13854d6bb56e39656a44f9d5e7168cbc6b2323a0 (diff) | |
| download | webob-d7ab30047633147fe8e03d0210eb23d2001bdab7.tar.gz | |
Adds Reponse.has_body.
Purpose of this property is to allow users to check if the Response has
a body without forcing an evaulation of the underlying app_iter.
This is handy if you wan't to create a streaming response where the
app_iter itself is lazy (i.e. streams data over a socket) or the app_iter
can only read once.
| -rw-r--r-- | tests/test_response.py | 31 | ||||
| -rw-r--r-- | webob/response.py | 18 |
2 files changed, 49 insertions, 0 deletions
diff --git a/tests/test_response.py b/tests/test_response.py index 58fee3c..aaac831 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -437,6 +437,37 @@ def test_app_iter_range_inner_method(): res = Response(app_iter=FakeAppIter()) assert res.app_iter_range(30, 40), ('you win', 30 == 40) +def test_has_body(): + empty = Response() + assert not empty.has_body + + with_list = Response(app_iter=['1']) + assert with_list.has_body + + with_empty_list = Response(app_iter=[b'']) + assert not with_empty_list.has_body + + with_body = Response(body='Seomthing') + assert with_body.has_body + + with_none_app_iter = Response(app_iter=None) + assert not with_none_app_iter.has_body + + with_none_body = Response(body=None) + assert not with_none_body.has_body + + # key feature: has_body should not read app_iter + app_iter = iter(['1', '2']) + not_iterating = Response(app_iter=app_iter) + assert not_iterating.has_body + assert next(app_iter) == '1' + + # messed with private attribute but method should nonetheless not + # return True + messing_with_privates = Response() + messing_with_privates._app_iter = None + assert not messing_with_privates.has_body + def test_content_type_in_headerlist(): # Couldn't manage to clone Response in order to modify class # attributes safely. Shouldn't classes be fresh imported for every diff --git a/webob/response.py b/webob/response.py index 1cc41cd..4faaad4 100644 --- a/webob/response.py +++ b/webob/response.py @@ -405,6 +405,24 @@ class Response(object): json = json_body = property(_json_body__get, _json_body__set, _json_body__del) + def _has_body__get(self): + """Determine if the the response has a body. In contrast to simply + accessing ``body`` this method will *not* read the underlying app_iter.""" + app_iter = self._app_iter + + if isinstance(app_iter, list) and len(app_iter) == 1: + if app_iter[0] != b'': + return True + else: + return False + + if app_iter is None: # pragma: no cover (just a safeguard, houl) + return False + + return True + + has_body = property(_has_body__get) + # # text, unicode_body, ubody |
