From efcbe93075c8674657e45005c5d59af1d94fc600 Mon Sep 17 00:00:00 2001 From: Rotem Yaari Date: Sat, 11 Feb 2017 21:27:50 +0200 Subject: [PATCH] Make Response.raise_for_status() return the response object if the response is successful This allows for chaining method calls in cases where we want to raise for bad codes but use the response otherwise, e.g. requests.get(URL).raise_for_status().json()['value'] --- 3.0-HISTORY.rst | 2 ++ docs/user/quickstart.rst | 6 +++++- requests/models.py | 5 ++++- tests/test_requests.py | 4 ++++ 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/3.0-HISTORY.rst b/3.0-HISTORY.rst index cf853343..4701e529 100644 --- a/3.0-HISTORY.rst +++ b/3.0-HISTORY.rst @@ -58,5 +58,7 @@ - URLs are now automatically stripped of leading/trailing whitespace. +- ``Response.raise_for_status()`` now returns the response object for good responses + .. _#2002: https://github.com/kennethreitz/requests/issues/2002 .. _#2631: https://github.com/kennethreitz/requests/issues/2631 diff --git a/docs/user/quickstart.rst b/docs/user/quickstart.rst index 60cc73fb..ecb7029d 100644 --- a/docs/user/quickstart.rst +++ b/docs/user/quickstart.rst @@ -354,10 +354,14 @@ But, since our ``status_code`` for ``r`` was ``200``, when we call ``raise_for_status()`` we get:: >>> r.raise_for_status() - None + All is well. +.. note:: ``raise_for_status`` returns the response object for a successful response. This eases chaining in trivial cases, where we want bad codes to raise an exception, but use the response otherwise: + + >>> value = requests.get('http://httpbin.org/ip').raise_for_status().json()['origin'] + Response Headers ---------------- diff --git a/requests/models.py b/requests/models.py index 0b3838b2..df94f026 100644 --- a/requests/models.py +++ b/requests/models.py @@ -902,7 +902,8 @@ class Response(object): return l def raise_for_status(self): - """Raises stored :class:`HTTPError`, if one occurred.""" + """Raises stored :class:`HTTPError`, if one occurred. + Otherwise, returns the response object (self).""" http_error_msg = '' if isinstance(self.reason, bytes): @@ -926,6 +927,8 @@ class Response(object): if http_error_msg: raise HTTPError(http_error_msg, response=self) + return self + def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. diff --git a/tests/test_requests.py b/tests/test_requests.py index fe1718ce..b6cda0a0 100755 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -829,6 +829,10 @@ class TestRequests: r = requests.get(httpbin('status', '500')) assert not r.ok + def test_raise_for_status_returns_self(self, httpbin): + r = requests.get(httpbin('status', '200')) + assert r.raise_for_status() is r + def test_decompress_gzip(self, httpbin): r = requests.get(httpbin('gzip')) r.content.decode('ascii')