Merge pull request #626 from joshimhoff/develop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Improvements to RequestsCookieJar
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 2d97466, 0eb0b89 · Browse files · 2 files·+138 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+138 added−3 removed
- tests:+33 added−0 removed
- other:+105 added−3 removed
Provenance
- Commit
de1637c- Tree
1cb5a63- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
2d97466- Parent 2
0eb0b89
2 files changed+138 added−3 removed
modified:requests/cookies.py+105 added-3 removed
118 unmodified lines119 120 for domain, path, name in clearables:121 cookiejar.clear(domain, path, name)122 123+class CookieConflictError(RuntimeError):124+ """There are two cookies that meet the criteria specified in the cookie jar. 125+ Use .get and .set and include domain and path args in order to be more specific."""126+127 class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):128 """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface.129 130 This is the CookieJar we create by default for requests and sessions that10 unmodified lines141 Unlike a regular CookieJar, this class is pickleable.142 """143 144 def get(self, name, default=None, domain=None, path=None):145+ """Dict-like get() that also supports optional domain and path args in146+ order to resolve naming collisions from using one cookie jar over147+ multiple domains. Caution: operation is O(n), not O(1)."""148 try:142- return self._find(name, domain, path)149+ return self._find_no_duplicates(name, domain, path)150 except KeyError:151 return default152 153 def set(self, name, value, **kwargs):154+ """Dict-like set() that also supports optional domain and path args in155+ order to resolve naming collisions from using one cookie jar over156+ multiple domains."""157 # support client code that unsets cookies by assignment of a None value:158 if value is None:159 remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))160 return4 unmodified lines165 c = create_cookie(name, value, **kwargs)166 self.set_cookie(c)167 return c168 169+ def keys(self):170+ """Dict-like keys() that returns a list of names of cookies from the jar.171+ See values() and items()."""172+ keys = []173+ for cookie in iter(self):174+ keys.append(cookie.name)175+ return keys176+177+ def values(self):178+ """Dict-like values() that returns a list of values of cookies from the jar.179+ See keys() and items()."""180+ values = []181+ for cookie in iter(self):182+ values.append(cookie.value)183+ return values184+ 185+ def items(self):186+ """Dict-like items() that returns a list of name-value tuples from the jar.187+ See keys() and values(). Allows client-code to call "dict(RequestsCookieJar)188+ and get a vanilla python dict of key value pairs."""189+ items = []190+ for cookie in iter(self):191+ items.append((cookie.name, cookie.value))192+ return items193+194+ def list_domains(self):195+ """Utility method to list all the domains in the jar."""196+ domains = []197+ for cookie in iter(self):198+ if cookie.domain not in domains:199+ domains.append(cookie.domain)200+ return domains201+202+ def list_paths(self):203+ """Utility method to list all the paths in the jar."""204+ paths = []205+ for cookie in iter(self):206+ if cookie.path not in paths:207+ paths.append(cookie.path)208+ return paths209+210+ def multiple_domains(self):211+ """Returns True if there are multiple domains in the jar.212+ Returns False otherwise."""213+ domains = []214+ for cookie in iter(self):215+ if cookie.domain is not None and cookie.domain in domains:216+ return True217+ domains.append(cookie.domain)218+ return False # there is only one domain in jar219+220+ def get_dict(self, domain=None, path=None):221+ """Takes as an argument an optional domain and path and returns a plain old222+ Python dict of name-value pairs of cookies that meet the requirements."""223+ dictionary = {}224+ for cookie in iter(self):225+ if (domain == None or cookie.domain == domain) and (path == None 226+ or cookie.path == path):227+ dictionary[cookie.name] = cookie.value228+ return dictionary229+230 def __getitem__(self, name):231+ """Dict-like __getitem__() for compatibility with client code. Throws exception232+ if there are more than one cookie with name. In that case, use the more233+ explicit get() method instead. Caution: operation is O(n), not O(1)."""160- return self._find(name)234+ return self._find_no_duplicates(name)235 236 def __setitem__(self, name, value):237+ """Dict-like __setitem__ for compatibility with client code. Throws exception238+ if there is already a cookie of that name in the jar. In that case, use the more239+ explicit set() method instead."""240 self.set(name, value)241 242 def __delitem__(self, name):243+ """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name()."""244 remove_cookie_by_name(self, name)245 246 def _find(self, name, domain=None, path=None):247+ """Requests uses this method internally to get cookie values. Takes as args name 248+ and optional domain and path. Returns a cookie.value. If there are conflicting cookies,249+ _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown250+ if there are conflicting cookies."""251 for cookie in iter(self):252 if cookie.name == name:253 if domain is None or cookie.domain == domain:254 if path is None or cookie.path == path:255 return cookie.value256 257 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))258 259+ def _find_no_duplicates(self, name, domain=None, path=None):260+ """__get_item__ and get call _find_no_duplicates -- never used in Requests internally. 261+ Takes as args name and optional domain and path. Returns a cookie.value. 262+ Throws KeyError if cookie is not found and CookieConflictError if there are 263+ multiple cookies that match name and optionally domain and path."""264+ toReturn = None265+ for cookie in iter(self):266+ if cookie.name == name:267+ if domain is None or cookie.domain == domain:268+ if path is None or cookie.path == path:269+ if toReturn != None: # if there are multiple cookies that meet passed in criteria270+ raise CookieConflictError('There are multiple cookies with name, %r' % (name))271+ toReturn = cookie.value # we will eventually return this as long as no cookie conflict272+273+ if toReturn:274+ return toReturn275+ raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))276+277 def __getstate__(self):278+ """Unlike a normal CookieJar, this class is pickleable."""279 state = self.__dict__.copy()280 # remove the unpickleable RLock object281 state.pop('_cookies_lock')282 return state283 284 def __setstate__(self, state):285+ """Unlike a normal CookieJar, this class is pickleable."""286 self.__dict__.update(state)287 if '_cookies_lock' not in self.__dict__:288 self._cookies_lock = threading.RLock()289 290 def copy(self):189- """We're probably better off forbidding this."""291+ """This is not implemented. Calling this will throw an exception."""292 raise NotImplementedError293 294 def create_cookie(name, value, **kwargs):295 """Make a cookie from underspecified parameters.68 unmodified linesmodified:tests/test_cookies.py+33 added
22 unmodified lines23 r = requests.get(httpbin('cookies', 'set', 'myname', 'myvalue'))24 25 # test deprecated dictionary interface26 self.assertEqual(r.cookies['myname'], 'myvalue')27+ self.assertEqual(r.cookies.get('myname'), 'myvalue')28 # test CookieJar interface29 jar = r.cookies30 self.assertEqual(len(jar), 1)31 cookie_from_jar = list(jar)[0]90 unmodified lines122 s.get(httpbin('cookies', 'set', 'key', 'value'), store_cookies = False)123 r = s.get(httpbin('cookies'))124 self.assertEqual(json.loads(r.text)['cookies'], {})125 126+ def test_jar_utility_functions(self):127+ """Test utility functions such as list_domains, list_paths, multiple_domains."""128+ r = requests.get("http://github.com")129+ c = r.cookies130+ # github should send us cookies131+ self.assertTrue(len(c) >= 1)132+ self.assertEqual(len(c), len(r.cookies.keys()))133+ self.assertEqual(len(c), len(r.cookies.values()))134+ self.assertEqual(len(c), len(r.cookies.items()))135+ 136+ # domain and path utility functions137+ domain = r.cookies.list_domains()[0]138+ path = r.cookies.list_paths()[0]139+ self.assertEqual(dict(r.cookies), r.cookies.get_dict(domain=domain, path=path))140+ self.assertEqual(len(r.cookies.list_domains()), 1)141+ self.assertEqual(len(r.cookies.list_paths()), 1)142+ self.assertFalse(r.cookies.multiple_domains())143 144+ def test_convert_jar_to_dict(self):145+ """Test that keys, values, and items are defined and that we can convert146+ cookie jars to plain old Python dicts."""147+ r = requests.get(httpbin('cookies', 'set', 'myname', 'myvalue'))148+149+ # test keys, values, and items150+ self.assertEqual(r.cookies.keys(), ['myname'])151+ self.assertEqual(r.cookies.values(), ['myvalue'])152+ self.assertEqual(r.cookies.items(), [('myname','myvalue')])153+ 154+ # test if we can convert jar to dict155+ dictOfCookies = dict(r.cookies)156+ self.assertEqual(dictOfCookies, {'myname':'myvalue'})157+ self.assertEqual(dictOfCookies, r.cookies.get_dict())158+159 class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):160 """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""161 162 COOKIEJAR_CLASS = cookielib.LWPCookieJar99 unmodified lines