Skip to content
Myr

Add Cookies model

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

authored by Tom Christie · committed by Tom Christie · parent 1e0409c · Browse files · 6 files+250 added−117 removed
This commit

State

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

Diff stats

6 files+250 added−117 removed

  • tests:+156 added−110 removed
  • other:+94 added−7 removed

6 files+250 added−117 removed

modified:httpcore/__init__.py+1 added
3 unmodified lines
4from .dispatch.connection import HTTPConnection5from .dispatch.connection_pool import ConnectionPool6from .exceptions import (7 ConnectTimeout,8 CookieConflict,9 DecodingError,10 InvalidURL,11 PoolTimeout,12 ProtocolError,
15 unmodified lines
modified:httpcore/exceptions.py+6 added
118 unmodified lines
119class InvalidURL(Exception):120 """121 URL was missing a hostname, or was not one of HTTP/HTTPS.122 """123124125class CookieConflict(Exception):126 """127 Attempted to lookup a cookie by name, but multiple cookies existed.128 """
modified:httpcore/models.py+87 added-7 removed
1 unmodified line
2import cgi3import email.message4import typing5import urllib.request6from collections.abc import MutableMapping7from http.cookiejar import Cookie, CookieJar8from urllib.parse import parse_qsl, urlencode910import chardet
6 unmodified lines
17 IdentityDecoder,18 MultiDecoder,19)20from .exceptions import (21 CookieConflict,22 HttpError,23 InvalidURL,24 ResponseClosed,25 ResponseNotRead,
462 unmodified lines
488 self.url = URL(url, query_params=query_params)489 self.headers = Headers(headers)490 if cookies:491 cookies = Cookies(cookies)490 cookies.add_cookie_header(self)492 cookies.set_cookie_header(self)493494 if isinstance(data, bytes):495 self.is_streaming = False496 self.content = data
364 unmodified lines
861 def __repr__(self) -> str:862 return f"<Response({self.status_code}, {self.reason_phrase!r})>"863864863class Cookies:864 def __init__(self, cookies: CookieTypes = None):865class Cookies(MutableMapping):866 """867 HTTP Cookies, as a mutable mapping.868 """869870 def __init__(self, cookies: CookieTypes = None) -> None:871 if cookies is None or isinstance(cookies, dict):872 self.jar = CookieJar()873 if isinstance(cookies, dict):874 for key, value in cookies.items():
12 unmodified lines
887 urllib_request = self._CookieCompatRequest(response.request)888889 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore890885 def add_cookie_header(self, request: Request) -> None:891 def set_cookie_header(self, request: Request) -> None:892 """893 Sets an appropriate 'Cookie:' HTTP header on the `Request`.894 """895 urllib_request = self._CookieCompatRequest(request)896 self.jar.add_cookie_header(urllib_request)897898 def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:899 """894 Set a cookie.900 Set a cookie value by name. May optionally include domain and path.901 """902 kwargs = dict(903 version=0,904 name=name,
15 unmodified lines
920 )921 cookie = Cookie(**kwargs) # type: ignore922 self.jar.set_cookie(cookie)923924 def get( # type: ignore925 self, name: str, default: str = None, domain: str = None, path: str = None926 ) -> typing.Optional[str]:927 """928 Get a cookie by name. May optionally include domain and path929 in order to specify exactly which cookie to retrieve.930 """931 value = None932 for cookie in self.jar:933 if cookie.name == name:934 if domain is None or cookie.domain == domain: # type: ignore935 if path is None or cookie.path == path:936 if value is not None:937 message = f"Multiple cookies exist with name={name}"938 raise CookieConflict(message)939 value = cookie.value940941 if value is None:942 return default943 return value944945 def delete(self, name: str, domain: str = None, path: str = None) -> None:946 """947 Delete a cookie by name. May optionally include domain and path948 in order to specify exactly which cookie to delete.949 """950 if domain is not None and path is not None:951 return self.jar.clear(domain, path, name)952953 remove = []954 for cookie in self.jar:955 if cookie.name == name:956 if domain is None or cookie.domain == domain: # type: ignore957 if path is None or cookie.path == path:958 remove.append(cookie)959960 for cookie in remove:961 self.jar.clear(cookie.domain, cookie.path, cookie.name) # type: ignore962963 def clear(self, domain: str = None, path: str = None) -> None:964 """965 Delete all cookies. Optionally include a domain and path in966 order to only delete a subset of all the cookies.967 """968 args = []969 if domain is not None:970 args.append(domain)971 if path is not None:972 assert domain is not None973 args.append(path)974 self.jar.clear(*args)975976 def update(self, cookies: CookieTypes) -> None: # type: ignore977 cookies = Cookies(cookies)978 for cookie in cookies.jar:979 self.jar.set_cookie(cookie)980981 def __setitem__(self, name: str, value: str) -> None:982 return self.set(name, value)983921 def __iter__(self) -> typing.Iterable:922 return iter(self.jar)984 def __getitem__(self, name: str) -> str:985 value = self.get(name)986 if value is None:987 raise KeyError(name)988 return value989990 def __delitem__(self, name: str) -> None:991 return self.delete(name)992993 def __len__(self) -> int:994 return len(self.jar)995996 def __iter__(self) -> typing.Iterator[str]:997 return (cookie.name for cookie in self.jar)998999 def __bool__(self) -> bool:1000 for cookie in self.jar:1001 return True1002 return False10031004 class _CookieCompatRequest(urllib.request.Request):1005 """1006 Wraps a `Request` instance up in a compatability interface suitable1007 for use with `CookieJar` operations.
28 unmodified lines
deleted:tests/client/test_cookies.py-110 removed
1import json2from http.cookiejar import Cookie, CookieJar34import pytest56from httpcore import (7 URL,8 Client,9 Cookies,10 Dispatcher,11 Request,12 Response,13 SSLConfig,14 TimeoutConfig,15)161718class MockDispatch(Dispatcher):19 async def send(20 self,21 request: Request,22 stream: bool = False,23 ssl: SSLConfig = None,24 timeout: TimeoutConfig = None,25 ) -> Response:26 if request.url.path.startswith("/echo_cookies"):27 body = json.dumps({"cookies": request.headers.get("Cookie")}).encode()28 return Response(200, content=body, request=request)29 elif request.url.path.startswith("/set_cookie"):30 headers = {"set-cookie": "example-name=example-value"}31 return Response(200, headers=headers, request=request)323334def test_set_cookie():35 """36 Send a request including a cookie.37 """38 url = "http://example.org/echo_cookies"39 cookies = {"example-name": "example-value"}4041 with Client(dispatch=MockDispatch()) as client:42 response = client.get(url, cookies=cookies)4344 assert response.status_code == 20045 assert json.loads(response.text) == {"cookies": "example-name=example-value"}464748def test_set_cookie_with_cookiejar():49 """50 Send a request including a cookie, using a `CookieJar` instance.51 """5253 url = "http://example.org/echo_cookies"54 cookies = CookieJar()55 cookie = Cookie(56 version=0,57 name="example-name",58 value="example-value",59 port=None,60 port_specified=False,61 domain="",62 domain_specified=False,63 domain_initial_dot=False,64 path="/",65 path_specified=True,66 secure=False,67 expires=None,68 discard=True,69 comment=None,70 comment_url=None,71 rest={"HttpOnly": None},72 rfc2109=False,73 )74 cookies.set_cookie(cookie)7576 with Client(dispatch=MockDispatch()) as client:77 response = client.get(url, cookies=cookies)7879 assert response.status_code == 20080 assert json.loads(response.text) == {"cookies": "example-name=example-value"}818283def test_set_cookie_with_cookies_model():84 """85 Send a request including a cookie, using a `Cookies` instance.86 """8788 url = "http://example.org/echo_cookies"89 cookies = Cookies()90 cookies["example-name"] = "example-value"9192 with Client(dispatch=MockDispatch()) as client:93 response = client.get(url, cookies=cookies)9495 assert response.status_code == 20096 assert json.loads(response.text) == {"cookies": "example-name=example-value"}979899def test_get_cookie():100 url = "http://example.org/set_cookie"101102 with Client(dispatch=MockDispatch()) as client:103 response = client.get(url)104105 assert response.status_code == 200106 cookies = list(response.cookies)107 assert len(cookies) == 1108 cookie = cookies[0]109 assert cookie.name == "example-name"110 assert cookie.value == "example-value"
added:tests/models/test_cookies.py+50 added
1import pytest23from httpcore import CookieConflict, Cookies456def test_cookies():7 cookies = Cookies({"name": "value"})8 assert cookies["name"] == "value"9 assert "name" in cookies10 assert len(cookies) == 111 assert dict(cookies) == {"name": "value"}12 assert bool(cookies) is True1314 del cookies["name"]15 assert "name" not in cookies16 assert len(cookies) == 017 assert dict(cookies) == {}18 assert bool(cookies) is False192021def test_cookies_update():22 cookies = Cookies()23 more_cookies = Cookies()24 more_cookies.set("name", "value", domain="example.com")2526 cookies.update(more_cookies)27 assert dict(cookies) == {"name": "value"}28 assert cookies.get("name", domain="example.com") == "value"293031def test_cookies_with_domain():32 cookies = Cookies()33 cookies.set("name", "value", domain="example.com")34 cookies.set("name", "value", domain="example.org")3536 with pytest.raises(CookieConflict):37 cookies["name"]3839 cookies.clear(domain="example.com")40 assert len(cookies) == 1414243def test_cookies_with_domain_and_path():44 cookies = Cookies()45 cookies.set("name", "value", domain="example.com", path="/subpath/1")46 cookies.set("name", "value", domain="example.com", path="/subpath/2")47 cookies.clear(domain="example.com", path="/subpath/1")48 assert len(cookies) == 149 cookies.delete("name", domain="example.com", path="/subpath/2")50 assert len(cookies) == 0