Skip to content
Myr

Nicer headers interface

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 83d322f · Browse files · 3 files+77 added−42 removed
This commit

State

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

Diff stats

3 files+77 added−42 removed

  • tests:+33 added−40 removed
  • other:+44 added−2 removed

3 files+77 added−42 removed

modified:httpcore/models.py+25 added-2 removed
9 unmodified lines
10 IdentityDecoder,11 MultiDecoder,12)13from .exceptions import ResponseClosed, StreamConsumed14from .utils import normalize_header_key, normalize_header_value151617class URL:18 def __init__(self, url: str = "") -> None:
86 unmodified lines
105 def __hash__(self) -> int:106 return hash((self.is_ssl, self.hostname, self.port))107108108HeaderTypes = typing.Union["Headers", typing.List[typing.Tuple[bytes, bytes]]]109HeaderTypes = typing.Union[110 "Headers",111 typing.Dict[typing.AnyStr, typing.AnyStr],112 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],113]114115116class Headers(typing.MutableMapping[str, str]):117 """
4 unmodified lines
122 if headers is None:123 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]124 elif isinstance(headers, Headers):125 self._list = list(headers.raw)126 elif isinstance(headers, dict):127 self._list = [128 (normalize_header_key(k), normalize_header_value(v))129 for k, v in headers.items()130 ]131 else:122 self._list = [(k.lower(), v) for k, v in headers]132 self._list = [133 (normalize_header_key(k), normalize_header_value(v)) for k, v in headers134 ]135136 @property137 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:138 return self._list
111 unmodified lines
250 self.is_streaming = True251 self.body_aiter = body252 self.headers = Headers(headers)253254 async def read(self) -> bytes:255 """256 Read and return the response content.257 """258 if not hasattr(self, "body"):259 body = b""260 async for part in self.stream():261 body += part262 self.body = body263 return self.body264265 async def stream(self) -> typing.AsyncIterator[bytes]:266 if self.is_streaming:267 async for part in self.body_aiter:268 yield part
132 unmodified lines
modified:httpcore/utils.py+19 added
1import typing2from urllib.parse import quote34from .exceptions import InvalidURL5
44 unmodified lines
50 # We couldn't unquote the given URI, so let's try quoting it, but51 # there may be unquoted '%'s in the URI. We need to make sure they're52 # properly quoted so they do not cause issues elsewhere.53 return quote(uri, safe=safe_without_percent)545556def normalize_header_key(value: typing.AnyStr) -> bytes:57 """58 Coerce str/bytes into a strictly byte-wise HTTP header key.59 """60 if isinstance(value, bytes):61 return value.lower()62 return value.encode("latin-1").lower()636465def normalize_header_value(value: typing.AnyStr) -> bytes:66 """67 Coerce str/bytes into a strictly byte-wise HTTP header value.68 """69 if isinstance(value, bytes):70 return value71 return value.encode("latin-1")
modified:tests/adapters/test_redirects.py+33 added-40 removed
19 unmodified lines
20 def prepare_request(self, request: Request) -> None:21 pass2223 async def send(self, request: Request, **options) -> Response:24 if request.url.path == "/redirect_301": # "Moved Permanently"25 return Response(26 301, headers=[(b"location", b"https://example.org/")], request=request27 )24 if request.url.path == "/redirect_301":25 status_code = codes.moved_permanently26 headers = {"location": "https://example.org/"}27 return Response(status_code, headers=headers, request=request)2829 elif request.url.path == "/redirect_302": # "Found"30 return Response(31 302, headers=[(b"location", b"https://example.org/")], request=request32 )29 elif request.url.path == "/redirect_302":30 status_code = codes.found31 headers = {"location": "https://example.org/"}32 return Response(status_code, headers=headers, request=request)3334 elif request.url.path == "/redirect_303": # "See Other"35 return Response(36 303, headers=[(b"location", b"https://example.org/")], request=request37 )34 elif request.url.path == "/redirect_303":35 status_code = codes.see_other36 headers = {"location": "https://example.org/"}37 return Response(status_code, headers=headers, request=request)3839 elif request.url.path == "/relative_redirect":40 return Response(41 codes.see_other, headers=[(b"location", b"/")], request=request42 )40 headers = {"location": "/"}41 return Response(codes.see_other, headers=headers, request=request)4243 elif request.url.path == "/no_scheme_redirect":45 return Response(46 codes.see_other,47 headers=[(b"location", b"//example.org/")],48 request=request,49 )44 headers = {"location": "//example.org/"}45 return Response(codes.see_other, headers=headers, request=request)4647 elif request.url.path == "/multiple_redirects":48 params = parse_qs(request.url.query)49 count = int(params.get("count", "0")[0])
1 unmodified line
51 code = codes.see_other if count else codes.ok52 location = "/multiple_redirects"53 if redirect_count:54 location += "?count=" + str(redirect_count)59 headers = [(b"location", location.encode())] if count else []55 headers = {"location": location} if count else {}56 return Response(code, headers=headers, request=request)5758 if request.url.path == "/redirect_loop":63 return Response(64 codes.see_other,65 headers=[(b"location", b"/redirect_loop")],66 request=request,67 )59 headers = {"location": "/redirect_loop"}60 return Response(codes.see_other, headers=headers, request=request)6162 elif request.url.path == "/cross_domain":70 location = b"https://example.org/cross_domain_target"71 return Response(301, headers=[(b"location", location)], request=request)63 headers = {"location": "https://example.org/cross_domain_target"}64 return Response(codes.see_other, headers=headers, request=request)6566 elif request.url.path == "/cross_domain_target":74 headers = {k.decode(): v.decode() for k, v in request.headers.raw}67 headers = dict(request.headers.items())68 body = json.dumps({"headers": headers}).encode()69 return Response(codes.ok, body=body, request=request)7071 elif request.url.path == "/redirect_body":79 headers = [(b"location", b"/redirect_body_target")]72 body = await request.read()73 headers = {"location": "/redirect_body_target"}74 return Response(codes.permanent_redirect, headers=headers, request=request)7576 elif request.url.path == "/redirect_body_target":77 body = await request.read()83 body = json.dumps({"body": request.body.decode()}).encode()78 body = json.dumps({"body": body.decode()}).encode()79 return Response(codes.ok, body=body, request=request)8081 return Response(codes.ok, body=b"Hello, world!", request=request)82
45 unmodified lines
128129@pytest.mark.asyncio130async def test_fragment_redirect():131 client = RedirectAdapter(MockDispatch())137 response = await client.request(138 "GET", "https://example.org/relative_redirect#fragment"139 )132 url = "https://example.org/relative_redirect#fragment"133 response = await client.request("GET", url)134 assert response.status_code == codes.ok135 assert response.url == URL("https://example.org/#fragment")136 assert len(response.history) == 1137138139@pytest.mark.asyncio140async def test_multiple_redirects():141 client = RedirectAdapter(MockDispatch())148 response = await client.request(149 "GET", "https://example.org/multiple_redirects?count=20"150 )142 url = "https://example.org/multiple_redirects?count=20"143 response = await client.request("GET", url)144 assert response.status_code == codes.ok145 assert response.url == URL("https://example.org/multiple_redirects")146 assert len(response.history) == 20147
14 unmodified lines
162163@pytest.mark.asyncio164async def test_cross_domain_redirect():165 client = RedirectAdapter(MockDispatch())173 headers = [(b"Authorization", b"abc")]166 url = "https://example.com/cross_domain"167 headers = {"Authorization": "abc"}168 response = await client.request("GET", url, headers=headers)169 data = json.loads(response.body.decode())170 assert response.url == URL("https://example.org/cross_domain_target")171 assert data == {"headers": {}}
1 unmodified line
173174@pytest.mark.asyncio175async def test_same_domain_redirect():176 client = RedirectAdapter(MockDispatch())184 headers = [(b"Authorization", b"abc")]177 url = "https://example.org/cross_domain"178 headers = {"Authorization": "abc"}179 response = await client.request("GET", url, headers=headers)180 data = json.loads(response.body.decode())181 assert response.url == URL("https://example.org/cross_domain_target")182 assert data == {"headers": {"authorization": "abc"}}
1 unmodified line
184185@pytest.mark.asyncio186async def test_body_redirect():187 client = RedirectAdapter(MockDispatch())195 body = b"Example request body"188 url = "https://example.org/redirect_body"189 body = b"Example request body"190 response = await client.request("POST", url, body=body)191 data = json.loads(response.body.decode())192 assert response.url == URL("https://example.org/redirect_body_target")193 assert data == {"body": "Example request body"}
12 unmodified lines