HTTP Cookies, as a mutable mapping.
| 27 | |
| 28 | |
| 29 | class Cookies(typing.MutableMapping[str, str]): |
| 30 | """HTTP Cookies, as a mutable mapping.""" |
| 31 | |
| 32 | def __init__(self, cookies: CookieTypes | None = None) -> None: |
| 33 | if cookies is None or isinstance(cookies, dict): |
| 34 | self.jar = CookieJar() |
| 35 | if isinstance(cookies, dict): |
| 36 | for key, value in cookies.items(): |
| 37 | self.set(key, value) |
| 38 | elif isinstance(cookies, list): |
| 39 | self.jar = CookieJar() |
| 40 | for key, value in cookies: |
| 41 | self.set(key, value) |
| 42 | elif isinstance(cookies, Cookies): |
| 43 | self.jar = CookieJar() |
| 44 | for cookie in cookies.jar: |
| 45 | self.jar.set_cookie(cookie) |
| 46 | else: |
| 47 | self.jar = cookies |
| 48 | |
| 49 | def set(self, name: str, value: str, domain: str = '', path: str = '/') -> None: |
| 50 | """Set a cookie value by name. May optionally include domain and path.""" |
| 51 | kwargs = { |
| 52 | 'version': 0, |
| 53 | 'name': name, |
| 54 | 'value': value, |
| 55 | 'port': None, |
| 56 | 'port_specified': False, |
| 57 | 'domain': domain, |
| 58 | 'domain_specified': bool(domain), |
| 59 | 'domain_initial_dot': domain.startswith('.'), |
| 60 | 'path': path, |
| 61 | 'path_specified': bool(path), |
| 62 | 'secure': False, |
| 63 | 'expires': None, |
| 64 | 'discard': True, |
| 65 | 'comment': None, |
| 66 | 'comment_url': None, |
| 67 | 'rest': {'HttpOnly': None}, |
| 68 | 'rfc2109': False, |
| 69 | } |
| 70 | cookie = Cookie(**kwargs) # type: ignore[arg-type] |
| 71 | self.jar.set_cookie(cookie) |
| 72 | |
| 73 | def get( # type: ignore[override] |
| 74 | self, |
| 75 | name: str, |
| 76 | default: str | None = None, |
| 77 | domain: str | None = None, |
| 78 | path: str | None = None, |
| 79 | ) -> str | None: |
| 80 | """Get a cookie by name. |
| 81 | |
| 82 | May optionally include domain and path in order to specify exactly which cookie to retrieve. |
| 83 | """ |
| 84 | value = None |
| 85 | for cookie in self.jar: |
| 86 | if cookie.name == name: |
no outgoing calls
searching dependent graphs…