class StatefulClient(Client): """This is a Client subclass that keeps cookies between calls.""" def __init__(self, *a, **kw): super(StatefulClient, self).__init__(*a, **kw) self.cookie = SimpleCookie() def __enter__(self): return self def __exit__(self, *a): self.cookie.clear() def hit(self, *a, **kw): cookies = kw.pop('cookies', None) if cookies: cookie = SimpleCookie() # session cookies first cookie.update(self.cookie) # request cookies second if isinstance(cookies, SimpleCookie): cookie.update(cookies) else: for k, v in cookies.items(): cookie[str(k)] = str(v) else: cookie = self.cookie kw['cookies'] = cookie want = kw.pop('want', 'response') kw['want'] = 'state' state = super(StatefulClient, self).hit(*a, **kw) r = state.get('response') if isinstance(r, Response) and r.headers.cookie: self.cookie.update(r.headers.cookie) return self.resolve_want(state, want)
def hit(self, *a, **kw): cookies = kw.pop('cookies', None) if cookies: cookie = SimpleCookie() # session cookies first cookie.update(self.cookie) # request cookies second if isinstance(cookies, SimpleCookie): cookie.update(cookies) else: for k, v in cookies.items(): cookie[str(k)] = str(v) else: cookie = self.cookie kw['cookies'] = cookie want = kw.pop('want', 'response') kw['want'] = 'state' state = super(StatefulClient, self).hit(*a, **kw) r = state.get('response') if isinstance(r, Response) and r.headers.cookie: self.cookie.update(r.headers.cookie) return self.resolve_want(state, want)