Rejig request preparing
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 041813b · Browse files · 8 files·+146 added−45 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+146 added−45 removed
- tests:+84 added−10 removed
- other:+62 added−35 removed
Provenance
- Commit
4f23ab4- Tree
dab1c72- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
041813b
8 files changed+146 added−45 removed
modified:httpcore/adapters/redirects.py+11 added-3 removed
2 unmodified lines3 4 from ..config import DEFAULT_MAX_REDIRECTS5 from ..exceptions import RedirectLoop, TooManyRedirects6 from ..interfaces import Adapter7-from ..models import URL, Request, Response7+from ..models import URL, Headers, Request, Response8 from ..status_codes import codes9 from ..utils import requote_uri10 11 6 unmodified lines18 self.dispatch.prepare_request(request)19 20 async def send(self, request: Request, **options: typing.Any) -> Response:21 allow_redirects = options.pop("allow_redirects", True)22- history = []22+ history = [] # type: typing.List[Response]23 seen_urls = set((request.url,))24 25 while True:26 response = await self.dispatch.send(request, **options)27+ response.history = list(history)28 if not allow_redirects or not response.is_redirect:29 break30 history.append(response)31 if len(history) > self.max_redirects:10 unmodified lines42 43 def build_redirect_request(self, request: Request, response: Response) -> Request:44 method = self.redirect_method(request, response)45 url = self.redirect_url(request, response)46+ headers = self.redirect_headers(request, url)45- return Request(method=method, url=url)47+ return Request(method=method, url=url, headers=headers)48 49 def redirect_method(self, request: Request, response: Response) -> str:50 """51 When being redirected we may want to change the method of the request38 unmodified lines90 else:91 url = requote_uri(url)92 93 return URL(url)94+95+ def redirect_headers(self, request: Request, url: URL) -> Headers:96+ headers = Headers(request.headers)97+ if url.origin != request.url.origin:98+ del headers["Authorization"]99+ return headersmodified:httpcore/dispatch/connection_pool.py+2 added-1 removed
8 unmodified lines9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12 )13+from ..decoders import ACCEPT_ENCODING14 from ..exceptions import PoolTimeout15 from ..interfaces import Adapter16 from ..models import Origin, Request, Response17 from ..streams import PoolSemaphore86 unmodified lines104 def num_connections(self) -> int:105 return len(self.keepalive_connections) + len(self.active_connections)106 107 def prepare_request(self, request: Request) -> None:107- pass108+ request.prepare()109 110 async def send(self, request: Request, **options: typing.Any) -> Response:111 connection = await self.acquire_connection(request.url.origin)112 try:46 unmodified linesmodified:httpcore/dispatch/connection.py+1 added-1 removed
35 unmodified lines36 self.h11_connection = None # type: typing.Optional[HTTP11Connection]37 self.h2_connection = None # type: typing.Optional[HTTP2Connection]38 39 def prepare_request(self, request: Request) -> None:40- pass40+ request.prepare()41 42 async def send(self, request: Request, **options: typing.Any) -> Response:43 if self.h11_connection is None and self.h2_connection is None:44 await self.connect(**options)49 unmodified linesmodified:httpcore/dispatch/http11.py+2 added-1 removed
44 unmodified lines45 self.on_release = on_release46 self.h11_state = h11.Connection(our_role=h11.CLIENT)47 48 def prepare_request(self, request: Request) -> None:49- pass49+ request.prepare()50 51 async def send(self, request: Request, **options: typing.Any) -> Response:52 timeout = options.get("timeout")53 stream = options.get("stream", False)32 unmodified lines86 protocol="HTTP/1.1",87 headers=headers,88 body=body,89 on_close=self.response_closed,90+ request=request,91 )92 93 if not stream:94 try:54 unmodified linesmodified:httpcore/dispatch/http2.py+2 added-1 removed
30 unmodified lines31 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]32 self.initialized = False33 34 def prepare_request(self, request: Request) -> None:35- pass35+ request.prepare()36 37 async def send(self, request: Request, **options: typing.Any) -> Response:38 timeout = options.get("timeout")39 stream = options.get("stream", False)34 unmodified lines74 protocol="HTTP/2",75 headers=headers,76 body=body,77 on_close=on_close,78+ request=request,79 )80 81 if not stream:82 try:74 unmodified linesmodified:httpcore/models.py+44 added-28 removed
77 unmodified lines78 79 def __str__(self) -> str:80 return self.components.geturl()81 82+ def __repr__(self) -> str:83+ class_name = self.__class__.__name__84+ url_str = str(self)85+ return f"{class_name}({url_str!r})"86 87+88 class Origin:89 def __init__(self, url: typing.Union[str, URL]) -> None:90 if isinstance(url, str):91 url = URL(url)12 unmodified lines104 def __hash__(self) -> int:105 return hash((self.is_ssl, self.hostname, self.port))106 107 108+HeaderTypes = typing.Union["Headers", typing.List[typing.Tuple[bytes, bytes]]]109+110+111 class Headers(typing.MutableMapping[str, str]):112 """113 A case-insensitive multidict.114 """115 108- def __init__(self, headers: typing.List[typing.Tuple[bytes, bytes]]) -> None:109- self._list = [(k.lower(), v) for k, v in headers]116+ def __init__(self, headers: HeaderTypes = None) -> None:117+ if headers is None:118+ self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]119+ elif isinstance(headers, Headers):120+ self._list = list(headers.raw)121+ else:122+ self._list = [(k.lower(), v) for k, v in headers]123 124 @property125 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:126 return self._list98 unmodified lines225 self,226 method: str,227 url: typing.Union[str, URL],228 *,216- headers: typing.List[typing.Tuple[bytes, bytes]] = [],229+ headers: HeaderTypes = None,230 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",231 ):232 self.method = method.upper()233 self.url = URL(url) if isinstance(url, str) else url2 unmodified lines236 self.body = body237 else:238 self.is_streaming = True239 self.body_aiter = body227- self.headers = self.build_headers(headers)240+ self.headers = Headers(headers)241 229- def build_headers(230- self, init_headers: typing.List[typing.Tuple[bytes, bytes]]231- ) -> Headers:232- has_host = False233- has_content_length = False234- has_accept_encoding = False242+ async def stream(self) -> typing.AsyncIterator[bytes]:243+ if self.is_streaming:244+ async for part in self.body_aiter:245+ yield part246+ elif self.body:247+ yield self.body248 236- for header, value in init_headers:237- header = header.strip().lower()238- if header == b"host":239- has_host = True240- elif header in (b"content-length", b"transfer-encoding"):241- has_content_length = True242- elif header == b"accept-encoding":243- has_accept_encoding = True244-249+ def prepare(self) -> None:250 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]251 252+ has_host = "host" in self.headers253+ has_content_length = (254+ "content-length" in self.headers or "transfer-encoding" in self.headers255+ )256+ has_accept_encoding = "accept-encoding" in self.headers257+258 if not has_host:259 auto_headers.append((b"host", self.url.netloc.encode("ascii")))260 if not has_content_length:261 if self.is_streaming:3 unmodified lines265 auto_headers.append((b"content-length", content_length))266 if not has_accept_encoding:267 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))268 258- return Headers(auto_headers + init_headers)269+ for item in reversed(auto_headers):270+ self.headers.raw.insert(0, item)271 260- async def stream(self) -> typing.AsyncIterator[bytes]:261- if self.is_streaming:262- async for part in self.body_aiter:263- yield part264- elif self.body:265- yield self.body272 267-273 class Response:274 def __init__(275 self,276 status_code: int,2 unmodified lines279 protocol: typing.Optional[str] = None,280 headers: typing.List[typing.Tuple[bytes, bytes]] = [],281 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",282 on_close: typing.Callable = None,283+ request: Request = None,284+ history: typing.List["Response"] = None,285 ):286 self.status_code = status_code287 if not reason:288 try:27 unmodified lines316 self.body = self.decoder.decode(body) + self.decoder.flush()317 else:318 self.body_aiter = body319 320+ self.request = request321+ self.history = [] if history is None else list(history)322+323+ @property324+ def url(self) -> typing.Optional[URL]:325+ return None if self.request is None else self.request.url326+327 async def read(self) -> bytes:328 """329 Read and return the response content.330 """40 unmodified lines371 await self.on_close()372 373 @property374 def is_redirect(self) -> bool:361- return self.status_code in (301, 302, 303, 307, 308)375+ return (376+ self.status_code in (301, 302, 303, 307, 308) and "location" in self.headers377+ )modified:tests/adapters/test_redirects.py+78 added-10 removed
1+import json2 from urllib.parse import parse_qs3 4 import pytest5 6 from httpcore import (7+ URL,8 Adapter,9 RedirectAdapter,10 RedirectLoop,11 Request,8 unmodified lines20 pass21 22 async def send(self, request: Request, **options) -> Response:23 if request.url.path == "/redirect_301": # "Moved Permanently"22- return Response(301, headers=[(b"location", b"https://example.org/")])24+ return Response(25+ 301, headers=[(b"location", b"https://example.org/")], request=request26+ )27 28 elif request.url.path == "/redirect_302": # "Found"25- return Response(302, headers=[(b"location", b"https://example.org/")])29+ return Response(30+ 302, headers=[(b"location", b"https://example.org/")], request=request31+ )32 33 elif request.url.path == "/redirect_303": # "See Other"28- return Response(303, headers=[(b"location", b"https://example.org/")])34+ return Response(35+ 303, headers=[(b"location", b"https://example.org/")], request=request36+ )37 38 elif request.url.path == "/relative_redirect":31- return Response(codes.see_other, headers=[(b"location", b"/")])39+ return Response(40+ codes.see_other, headers=[(b"location", b"/")], request=request41+ )42 43 elif request.url.path == "/no_scheme_redirect":34- return Response(codes.see_other, headers=[(b"location", b"//example.org/")])44+ return Response(45+ codes.see_other,46+ headers=[(b"location", b"//example.org/")],47+ request=request,48+ )49 50 elif request.url.path == "/multiple_redirects":51 params = parse_qs(request.url.query)52 count = int(params.get("count", "0")[0])53+ redirect_count = count - 154 code = codes.see_other if count else codes.ok40- location = "/multiple_redirects?count=" + str(count - 1)55+ location = "/multiple_redirects"56+ if redirect_count:57+ location += "?count=" + str(redirect_count)58 headers = [(b"location", location.encode())] if count else []42- return Response(code, headers=headers)59+ return Response(code, headers=headers, request=request)60 61 if request.url.path == "/redirect_loop":45- return Response(codes.see_other, headers=[(b"location", b"/redirect_loop")])62+ return Response(63+ codes.see_other,64+ headers=[(b"location", b"/redirect_loop")],65+ request=request,66+ )67 47- return Response(codes.ok, body=b"Hello, world!")68+ elif request.url.path == "/cross_domain":69+ location = b"https://example.org/cross_domain_target"70+ return Response(301, headers=[(b"location", location)], request=request)71 72+ elif request.url.path == "/cross_domain_target":73+ headers = {k.decode(): v.decode() for k, v in request.headers.raw}74+ body = json.dumps({"headers": headers}).encode()75+ return Response(codes.ok, body=body, request=request)76 77+ return Response(codes.ok, body=b"Hello, world!", request=request)78+79+80 @pytest.mark.asyncio81 async def test_redirect_301():82 client = RedirectAdapter(MockDispatch())83 response = await client.request("POST", "https://example.org/redirect_301")84 assert response.status_code == codes.ok85+ assert response.url == URL("https://example.org/")86+ assert len(response.history) == 187 88 89 @pytest.mark.asyncio90 async def test_redirect_302():91 client = RedirectAdapter(MockDispatch())92 response = await client.request("POST", "https://example.org/redirect_302")93 assert response.status_code == codes.ok94+ assert response.url == URL("https://example.org/")95+ assert len(response.history) == 196 97 98 @pytest.mark.asyncio99 async def test_redirect_303():100 client = RedirectAdapter(MockDispatch())101 response = await client.request("GET", "https://example.org/redirect_303")102 assert response.status_code == codes.ok103+ assert response.url == URL("https://example.org/")104+ assert len(response.history) == 1105 106 107 @pytest.mark.asyncio108 async def test_relative_redirect():109 client = RedirectAdapter(MockDispatch())110 response = await client.request("GET", "https://example.org/relative_redirect")111 assert response.status_code == codes.ok112+ assert response.url == URL("https://example.org/")113+ assert len(response.history) == 1114 115 116 @pytest.mark.asyncio117 async def test_no_scheme_redirect():118 client = RedirectAdapter(MockDispatch())119 response = await client.request("GET", "https://example.org/no_scheme_redirect")120 assert response.status_code == codes.ok121+ assert response.url == URL("https://example.org/")122+ assert len(response.history) == 1123 124 125 @pytest.mark.asyncio126 async def test_fragment_redirect():127 client = RedirectAdapter(MockDispatch())88- response = await client.request("GET", "https://example.org/relative_redirect#fragment")128+ response = await client.request(129+ "GET", "https://example.org/relative_redirect#fragment"130+ )131 assert response.status_code == codes.ok132+ assert response.url == URL("https://example.org/#fragment")133+ assert len(response.history) == 1134 135 136 @pytest.mark.asyncio137 async def test_multiple_redirects():1 unmodified line139 response = await client.request(140 "GET", "https://example.org/multiple_redirects?count=20"141 )142 assert response.status_code == codes.ok143+ assert response.url == URL("https://example.org/multiple_redirects")144+ assert len(response.history) == 20145 146 147 @pytest.mark.asyncio148 async def test_too_many_redirects():6 unmodified lines155 async def test_redirect_loop():156 client = RedirectAdapter(MockDispatch())157 with pytest.raises(RedirectLoop):158 await client.request("GET", "https://example.org/redirect_loop")159+160+161+@pytest.mark.asyncio162+async def test_cross_domain_redirect():163+ client = RedirectAdapter(MockDispatch())164+ headers = [(b"Authorization", b"abc")]165+ url = "https://example.com/cross_domain"166+ response = await client.request("GET", url, headers=headers)167+ data = json.loads(response.body.decode())168+ assert response.url == URL("https://example.org/cross_domain_target")169+ assert data == {"headers": {}}170+171+172+@pytest.mark.asyncio173+async def test_same_domain_redirect():174+ client = RedirectAdapter(MockDispatch())175+ headers = [(b"Authorization", b"abc")]176+ url = "https://example.org/cross_domain"177+ response = await client.request("GET", url, headers=headers)178+ data = json.loads(response.body.decode())179+ assert response.url == URL("https://example.org/cross_domain_target")180+ assert data == {"headers": {"authorization": "abc"}}modified:tests/test_requests.py+6 added
3 unmodified lines4 5 6 def test_host_header():7 request = httpcore.Request("GET", "http://example.org")8+ request.prepare()9 assert request.headers == httpcore.Headers(10 [(b"host", b"example.org"), (b"accept-encoding", b"deflate, gzip, br")]11 )12 13 14 def test_content_length_header():15 request = httpcore.Request("POST", "http://example.org", body=b"test 123")16+ request.prepare()17 assert request.headers == httpcore.Headers(18 [19 (b"host", b"example.org"),20 (b"content-length", b"8"),8 unmodified lines29 30 body = streaming_body(b"test 123")31 32 request = httpcore.Request("POST", "http://example.org", body=body)33+ request.prepare()34 assert request.headers == httpcore.Headers(35 [36 (b"host", b"example.org"),37 (b"transfer-encoding", b"chunked"),5 unmodified lines43 def test_override_host_header():44 headers = [(b"host", b"1.2.3.4:80")]45 46 request = httpcore.Request("GET", "http://example.org", headers=headers)47+ request.prepare()48 assert request.headers == httpcore.Headers(49 [(b"accept-encoding", b"deflate, gzip, br"), (b"host", b"1.2.3.4:80")]50 )51 1 unmodified line53 def test_override_accept_encoding_header():54 headers = [(b"accept-encoding", b"identity")]55 56 request = httpcore.Request("GET", "http://example.org", headers=headers)57+ request.prepare()58 assert request.headers == httpcore.Headers(59 [(b"host", b"example.org"), (b"accept-encoding", b"identity")]60 )61 5 unmodified lines67 body = streaming_body(b"test 123")68 headers = [(b"content-length", b"8")]69 70 request = httpcore.Request("POST", "http://example.org", body=body, headers=headers)71+ request.prepare()72 assert request.headers == httpcore.Headers(73 [74 (b"host", b"example.org"),75 (b"accept-encoding", b"deflate, gzip, br"),26 unmodified lines