diff --git a/AUTHORS.rst b/AUTHORS.rst index 658f0b96..b6002ec8 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -99,3 +99,4 @@ Patches and Suggestions - Miguel Turner - Rohan Jain (crodjer) - Justin Barber +- Roman Haritonov <@reclosedev> diff --git a/requests/models.py b/requests/models.py index fbdfb560..beb8f144 100644 --- a/requests/models.py +++ b/requests/models.py @@ -203,6 +203,12 @@ class Request(object): # Save cookies in Response. response.cookies = self.cookies + # Save cookies in Session. + # (in safe mode, cookies may be None if the request didn't succeed) + if self.cookies is not None: + for cookie in self.cookies: + self.session.cookies.set_cookie(cookie) + # No exceptions were harmed in the making of this request. response.error = getattr(resp, 'error', None) diff --git a/requests/sessions.py b/requests/sessions.py index 8d517ab5..dd670dd3 100644 --- a/requests/sessions.py +++ b/requests/sessions.py @@ -228,12 +228,6 @@ class Session(object): # Send the HTTP Request. r.send(prefetch=prefetch) - # Send any cookies back up the to the session. - # (in safe mode, cookies may be None if the request didn't succeed) - if r.response.cookies is not None: - for cookie in r.response.cookies: - self.cookies.set_cookie(cookie) - # Return the response. return r.response diff --git a/tests/test_requests.py b/tests/test_requests.py index 530008a3..de34cfac 100755 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -726,6 +726,16 @@ class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase): assert params3['b'] in r3.text assert params3['c'] in r3.text + def test_session_cookies_with_return_response_false(self): + s = requests.session() + # return_response=False as it does requests.async.get + rq = get(httpbin('cookies', 'set', 'k', 'v'), return_response=False, + allow_redirects=True, session=s) + rq.send(prefetch=True) + c = rq.response.json.get('cookies') + assert 'k' in c + assert 'k' in s.cookies + def test_session_pickling(self): s = requests.session( diff --git a/tests/test_requests_async.py b/tests/test_requests_async.py index 3a5a762e..892472cf 100755 --- a/tests/test_requests_async.py +++ b/tests/test_requests_async.py @@ -12,6 +12,7 @@ import select has_poll = hasattr(select, "poll") from requests import async +import requests sys.path.append('.') from test_requests import httpbin, RequestsTestSuite, SERVICES @@ -63,5 +64,14 @@ class RequestsTestSuiteUsingAsyncApi(RequestsTestSuite): """Test to make sure we don't overwrite the poll""" self.assertEqual(hasattr(select, "poll"), has_poll) + def test_async_with_session_cookies(self): + s = requests.Session(cookies={'initial': '42'}) + r1 = get(httpbin('cookies/set/async/yes'), session=s) + r2 = get(httpbin('cookies/set/no_session/yes')) + assert 'initial' in r1.cookies + assert 'initial' not in r2.cookies and 'async' not in r2.cookies + assert 'async' in s.cookies + assert 'no_session' not in s.cookies + if __name__ == '__main__': unittest.main()