From 590ce29743d6c8d68f3885a949a93fdb68f4d142 Mon Sep 17 00:00:00 2001 From: Shrikant Sharat Date: Sun, 19 Feb 2012 15:11:19 +0530 Subject: [PATCH] Implemented #439. Added supporting test. --- requests/sessions.py | 25 +++++++++++++++++-------- tests/test_requests.py | 14 ++++++++++++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/requests/sessions.py b/requests/sessions.py index d9683b0..f9c938f 100644 --- a/requests/sessions.py +++ b/requests/sessions.py @@ -52,7 +52,7 @@ class Session(object): __attrs__ = [ 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks', - 'params', 'config'] + 'params', 'config', 'verify'] def __init__(self, @@ -79,10 +79,7 @@ class Session(object): for (k, v) in list(defaults.items()): self.config.setdefault(k, v) - self.poolmanager = PoolManager( - num_pools=self.config.get('pool_connections'), - maxsize=self.config.get('pool_maxsize') - ) + self.init_poolmanager() # Set up a CookieJar to be used by default self.cookies = {} @@ -91,6 +88,12 @@ class Session(object): if cookies is not None: self.cookies.update(cookies) + def init_poolmanager(self): + self.poolmanager = PoolManager( + num_pools=self.config.get('pool_connections'), + maxsize=self.config.get('pool_maxsize') + ) + def __repr__(self): return '' % (id(self)) @@ -146,9 +149,6 @@ class Session(object): params = {} if params is None else params hooks = {} if hooks is None else hooks - if verify is None: - verify = self.verify - # use session's hooks as defaults for key, cb in list(self.hooks.items()): hooks.setdefault(key, cb) @@ -281,6 +281,15 @@ class Session(object): return self.request('delete', url, **kwargs) + def __getstate__(self): + return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__) + + def __setstate__(self, state): + for attr, value in state.items(): + setattr(self, attr, value) + + self.init_poolmanager() + def session(**kwargs): """Returns a :class:`Session` for context-management.""" diff --git a/tests/test_requests.py b/tests/test_requests.py index 76df752..516b9a4 100755 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -13,6 +13,7 @@ import time import os import sys import unittest +import pickle import requests from requests.compat import str, bytes, StringIO @@ -729,6 +730,19 @@ class RequestsTestSuite(TestSetup, unittest.TestCase): assert params3['b'] in r3.text assert params3['c'] in r3.text + def test_session_pickling(self): + + s = requests.session( + headers={'header': 'value'}, + cookies={'a-cookie': 'cookie-value'}, + auth=('username', 'password')) + + ds = pickle.loads(pickle.dumps(s)) + + self.assertEqual(s.headers, ds.headers) + self.assertEqual(s.cookies, ds.cookies) + self.assertEqual(s.auth, ds.auth) + def test_invalid_content(self): # WARNING: if you're using a terrible DNS provider (comcast), # this will fail. -- 2.7.4