Handle body in redirects
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 4f23ab4 · Browse files · 5 files·+54 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+54 added−3 removed
- tests:+32 added−0 removed
- other:+22 added−3 removed
Provenance
- Commit
83d322f- Tree
4a58b3c- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
4f23ab4
5 files changed+54 added−3 removed
modified:httpcore/adapters/redirects.py+10 added-2 removed
1 import typing2 from urllib.parse import urljoin, urlparse3 4 from ..config import DEFAULT_MAX_REDIRECTS5-from ..exceptions import RedirectLoop, TooManyRedirects5+from ..exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects6 from ..interfaces import Adapter7 from ..models import URL, Headers, Request, Response8 from ..status_codes import codes9 from ..utils import requote_uri33 unmodified lines43 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)47+ body = self.redirect_body(request, method)47- return Request(method=method, url=url, headers=headers)48+ return Request(method=method, url=url, headers=headers, body=body)49 50 def redirect_method(self, request: Request, response: Response) -> str:51 """52 When being redirected we may want to change the method of the request44 unmodified lines97 headers = Headers(request.headers)98 if url.origin != request.url.origin:99 del headers["Authorization"]100 return headers101+102+ def redirect_body(self, request: Request, method: str) -> bytes:103+ if method != request.method and method == "GET":104+ return b""105+ if request.is_streaming:106+ raise RedirectBodyUnavailable()107+ return request.bodymodified:httpcore/__init__.py+1 added
8 unmodified lines9 ConnectTimeout,10 PoolTimeout,11 ProtocolError,12 ReadTimeout,13+ RedirectBodyUnavailable,14 RedirectLoop,15 ResponseClosed,16 StreamConsumed,17 Timeout,9 unmodified linesmodified:httpcore/exceptions.py+7 added
38 unmodified lines39 Too many redirects.40 """41 42 43+class RedirectBodyUnavailable(RedirectError):44+ """45+ Got a redirect response, but the request body was streaming, and is46+ no longer available.47+ """48+49+50 class RedirectLoop(RedirectError):51 """52 Infinite redirect loop.53 """25 unmodified linesmodified:httpcore/status_codes.py+4 added-1 removed
3 unmodified lines4 "StatusCode",5 [6 ("continue", 100),7 ("switching_protocols", 101),8+ ("processing", 102),9 ("ok", 200),10 ("created", 201),11 ("accepted", 202),12 ("non_authoritative_information", 203),13 ("no_content", 204),14 ("reset_content", 205),15 ("partial_content", 206),16 ("multi_status", 207),17+ ("already_reported", 208),18+ ("im_used", 226),19 ("multiple_choices", 300),20 ("moved_permanently", 301),21 ("found", 302),22 ("see_other", 303),23 ("not_modified", 304),24 ("use_proxy", 305),22- ("reserved", 306),25 ("temporary_redirect", 307),26+ ("permanent_redirect", 308),27 ("bad_request", 400),28 ("unauthorized", 401),29 ("payment_required", 402),30 ("forbidden", 403),31 unmodified linesmodified:tests/adapters/test_redirects.py+32 added
5 unmodified lines6 from httpcore import (7 URL,8 Adapter,9 RedirectAdapter,10+ RedirectBodyUnavailable,11 RedirectLoop,12 Request,13 Response,14 TooManyRedirects,59 unmodified lines74 headers = {k.decode(): v.decode() for k, v in request.headers.raw}75 body = json.dumps({"headers": headers}).encode()76 return Response(codes.ok, body=body, request=request)77 78+ elif request.url.path == "/redirect_body":79+ headers = [(b"location", b"/redirect_body_target")]80+ return Response(codes.permanent_redirect, headers=headers, request=request)81+82+ elif request.url.path == "/redirect_body_target":83+ body = json.dumps({"body": request.body.decode()}).encode()84+ return Response(codes.ok, body=body, request=request)85+86 return Response(codes.ok, body=b"Hello, world!", request=request)87 88 89 @pytest.mark.asyncio96 unmodified lines186 response = await client.request("GET", url, headers=headers)187 data = json.loads(response.body.decode())188 assert response.url == URL("https://example.org/cross_domain_target")189 assert data == {"headers": {"authorization": "abc"}}190+191+192+@pytest.mark.asyncio193+async def test_body_redirect():194+ client = RedirectAdapter(MockDispatch())195+ body = b"Example request body"196+ url = "https://example.org/redirect_body"197+ response = await client.request("POST", url, body=body)198+ data = json.loads(response.body.decode())199+ assert response.url == URL("https://example.org/redirect_body_target")200+ assert data == {"body": "Example request body"}201+202+203+@pytest.mark.asyncio204+async def test_cannot_redirect_streaming_body():205+ client = RedirectAdapter(MockDispatch())206+ url = "https://example.org/redirect_body"207+208+ async def body():209+ yield b"Example request body"210+211+ with pytest.raises(RedirectBodyUnavailable):212+ await client.request("POST", url, body=body())