Skip to content
Myr

mostly complete cookie support based on cookiejar

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by miguel · committed by Shivaram Lingamneni · parent 2a27b12 · Browse files · 1 file+188 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+188 added−0 removed

  • other:+188 added−0 removed

1 file+188 added−0 removed

added:requests/packages/oreos/cookiejar.py+188 added
1import urlparse2import Cookie3from Cookie import Morsel4import cookielib5import collections67class MockRequest:8 """9 Wraps a *requests.Request* to mimic a *urllib2.Request*.10 """11 def __init__(self, request):12 self._r = request13 14 def get_type(self):15 return urlparse.urlparse(self._r.full_url).scheme16 17 def get_host(self):18 return urlparse.urlparse(self._r.full_url).netloc19 20 def get_origin_req_host(self):21 if self._r.history:22 r = self._r.history[0]23 return urlparse.urlparse(r).netloc24 else:25 return self.get_host()26 27 def get_full_url(self):28 return self._r.full_url29 30 def has_header(self, name):31 return name in self._r.headers32 33 def get_header(self, name, default=None):34 return self._r.headers.get(name, default)35 36 def add_unredirected_header(self, name, value):37 # XXX: This is incorrect.38 # To do this correctly the *requests.Request* class would need39 # to keep track of headers that are only sent with the original40 # request.41 self._r.headers[name] = value42 43 def is_unverifiable(self):44 # unverifiable == redirected45 return bool(self.history)4647class MockResponse:48 """49 Wraps a *requests.Response* to mimic a *urllib.addinfourl*.50 """51 def __init__(self, response):52 self._r = response53 54 def info(self):55 return self._r.msg56 57 def getheaders(self, name):58 self._r.msg.getheaders(name)5960class CookieJar(cookielib.LWPCookieJar, collections.MutableMapping):61 def extract_cookies(self, response, request):62 if response.raw._original_response:63 req = MockRequest(request)64 res = MockResponse(response.raw._original_response)65 cookielib.CookieJar.extract_cookies(self, res, req)66 67 def get_header(self, request):68 r = MockRequest(request)69 self.add_cookie_header(r)70 return r._r.headers['Cookie']71 72 def get(self, name, domain=None, path=None, default=None):73 try:74 return self._find(name, domain, path)75 except KeyError:76 return default77 78 def set(self, name, value, **kwargs):79 if isinstance(value, Morsel):80 c = morsel_to_cookielib(value)81 else:82 c = create_cookie(name, value, **kwargs)83 self.set_cookie(c)84 return c85 86 def update(self, other):87 if isinstance(other, cookielib.CookieJar):88 for cookie in other:89 self.set_cookie(cookie)90 else:91 collections.MutableMapping.update(self, other)92 93 def __getitem__(self, name):94 return self._find(name)95 96 def __setitem__(self, name, value):97 self.set(name, value)98 99 def __delitem__(self, name):100 raise NotImplementedError('cookies can be removed using *clear*')101 102 def _find(self, name, domain=None, path=None):103 try:104 if domain is None:105 dompaths = self._cookies.itervalues()106 else:107 dompaths = [self._cookies[domain]]108 for paths in dompaths:109 if path is None:110 pathcookies = paths.itervalues()111 else:112 pathcookies = [paths[path]]113 for cookies in pathcookies:114 for cname, cookie in cookies.iteritems():115 if name == cname:116 return cookielib_to_morsel(cookie)117 except KeyError:118 pass119 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))120121def create_cookie(name, value, **kwargs):122 result = dict(123 version=0,124 name=name,125 value=value,126 port=None,127 domain='',128 path='/',129 secure=False,130 expires=None,131 discard=True,132 comment=None,133 comment_url=None,134 rest={'HttpOnly': None},135 rfc2109=False,136 )137 138 badargs = set(kwargs) - set(result)139 if badargs:140 err = 'create_cookie() got unexpected keyword arguments: %s'141 raise TypeError(err % list(badargs))142 143 result.update(kwargs)144 result['port_specified'] = bool(result['port'])145 result['domain_specified'] = bool(result['domain'])146 result['domain_initial_dot'] = result['domain'].startswith('.')147 result['path_specified'] = bool(result['path'])148 149 return cookielib.Cookie(**result)150151def cookielib_to_morsel(cookie):152 m = Morsel()153 m.key = cookie.name154 m.value = cookie.value155 m.coded_value = Cookie._quote(cookie.value)156 m.update({157 'expires': cookie.expires or '',158 'path': cookie.path or '',159 'comment': cookie.comment or '',160 'domain': cookie.domain or '',161 'max-age': cookie.expires or '',162 'secure': cookie.secure or '',163 'httponly': cookie._rest.get('HttpOnly', ''),164 'version': cookie.version or '',165 })166 return m167168def morsel_to_cookielib(morsel):169 c = create_cookie(170 name=morsel.key,171 value=morsel.value,172 version=morsel['version'] or 0,173 port=None,174 port_specified=False,175 domain=morsel['domain'],176 domain_specified=bool(morsel['domain']),177 domain_initial_dot=morsel['domain'].startswith('.'),178 path=morsel['path'],179 path_specified=bool(morsel['path']),180 secure=bool(morsel['secure']),181 expires=morsel['max-age'] or morsel['expires'],182 discard=False,183 comment=morsel['comment'],184 comment_url=bool(morsel['comment']),185 rest={'HttpOnly': morsel['httponly']},186 rfc2109=False,187 )188 return c