Redirections
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 8b4ef87 · Browse files · 5 files·+92 added−10 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+92 added−10 removed
- tests:+66 added−7 removed
- other:+26 added−3 removed
Provenance
- Commit
041813b- Tree
fd43657- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
8b4ef87
5 files changed+92 added−10 removed
modified:httpcore/adapters/redirects.py+5 added-1 removed
1 import typing2 from urllib.parse import urljoin, urlparse3 4 from ..config import DEFAULT_MAX_REDIRECTS5-from ..exceptions import TooManyRedirects5+from ..exceptions import RedirectLoop, TooManyRedirects6 from ..interfaces import Adapter7 from ..models import URL, Request, Response8 from ..status_codes import codes9 from ..utils import requote_uri9 unmodified lines19 20 async def send(self, request: Request, **options: typing.Any) -> Response:21 allow_redirects = options.pop("allow_redirects", True)22 history = []23+ seen_urls = set((request.url,))24 25 while True:26 response = await self.dispatch.send(request, **options)27 if not allow_redirects or not response.is_redirect:1 unmodified line29 history.append(response)30 if len(history) > self.max_redirects:31 raise TooManyRedirects()32 request = self.build_redirect_request(request, response)33+ if request.url in seen_urls:34+ raise RedirectLoop()35+ seen_urls.add(request.url)36 37 return response38 39 async def close(self) -> None:52 unmodified linesmodified:httpcore/__init__.py+2 added-1 removed
8 unmodified lines9 ConnectTimeout,10 PoolTimeout,11 ProtocolError,12 ReadTimeout,13+ RedirectLoop,14 ResponseClosed,15 StreamConsumed,16 Timeout,16- TooManyRedirects17+ TooManyRedirects,18 )19 from .interfaces import Adapter20 from .models import URL, Headers, Origin, Request, Response21 from .status_codes import codes4 unmodified linesmodified:httpcore/exceptions.py+13 added-1 removed
26 unmodified lines27 Timeout while waiting to acquire a connection from the pool.28 """29 30 31-class TooManyRedirects(Exception):31+class RedirectError(Exception):32 """33+ Base class for HTTP redirect errors.34+ """35+36+37+class TooManyRedirects(RedirectError):38+ """39 Too many redirects.40 """41 42 43+class RedirectLoop(RedirectError):44+ """45+ Infinite redirect loop.46+ """47+48+49 class ProtocolError(Exception):50 """51 Malformed HTTP.52 """19 unmodified linesmodified:httpcore/models.py+6 added
68 unmodified lines69 @property70 def origin(self) -> "Origin":71 return Origin(self)72 73+ def __hash__(self) -> int:74+ return hash(str(self))75+76+ def __eq__(self, other: typing.Any) -> bool:77+ return isinstance(other, URL) and str(self) == str(other)78+79 def __str__(self) -> str:80 return self.components.geturl()81 82 279 unmodified linesmodified:tests/adapters/test_redirects.py+66 added-7 removed
1-import pytest1 from urllib.parse import parse_qs2 4-from httpcore import Adapter, RedirectAdapter, Request, Response, TooManyRedirects, codes3+import pytest4 5+from httpcore import (6+ Adapter,7+ RedirectAdapter,8+ RedirectLoop,9+ Request,10+ Response,11+ TooManyRedirects,12+ codes,13+)14 15+16 class MockDispatch(Adapter):17 def prepare_request(self, request: Request) -> None:18 pass19 20 async def send(self, request: Request, **options) -> Response:12- if request.url.path == "/redirect_303":13- return Response(14- codes.see_other, headers=[(b"location", b"https://example.org/")]15- )21+ if request.url.path == "/redirect_301": # "Moved Permanently"22+ return Response(301, headers=[(b"location", b"https://example.org/")])23+24+ elif request.url.path == "/redirect_302": # "Found"25+ return Response(302, headers=[(b"location", b"https://example.org/")])26+27+ elif request.url.path == "/redirect_303": # "See Other"28+ return Response(303, headers=[(b"location", b"https://example.org/")])29+30 elif request.url.path == "/relative_redirect":31 return Response(codes.see_other, headers=[(b"location", b"/")])32+33+ elif request.url.path == "/no_scheme_redirect":34+ return Response(codes.see_other, headers=[(b"location", b"//example.org/")])35+36 elif request.url.path == "/multiple_redirects":37 params = parse_qs(request.url.query)38 count = int(params.get("count", "0")[0])39 code = codes.see_other if count else codes.ok40 location = "/multiple_redirects?count=" + str(count - 1)41 headers = [(b"location", location.encode())] if count else []42 return Response(code, headers=headers)43+44+ if request.url.path == "/redirect_loop":45+ return Response(codes.see_other, headers=[(b"location", b"/redirect_loop")])46+47 return Response(codes.ok, body=b"Hello, world!")48 49 50 @pytest.mark.asyncio51+async def test_redirect_301():52+ client = RedirectAdapter(MockDispatch())53+ response = await client.request("POST", "https://example.org/redirect_301")54+ assert response.status_code == codes.ok55+56+57+@pytest.mark.asyncio58+async def test_redirect_302():59+ client = RedirectAdapter(MockDispatch())60+ response = await client.request("POST", "https://example.org/redirect_302")61+ assert response.status_code == codes.ok62+63+64+@pytest.mark.asyncio65 async def test_redirect_303():66 client = RedirectAdapter(MockDispatch())67 response = await client.request("GET", "https://example.org/redirect_303")68 assert response.status_code == codes.ok6 unmodified lines75 assert response.status_code == codes.ok76 77 78 @pytest.mark.asyncio79+async def test_no_scheme_redirect():80+ client = RedirectAdapter(MockDispatch())81+ response = await client.request("GET", "https://example.org/no_scheme_redirect")82+ assert response.status_code == codes.ok83+84+85+@pytest.mark.asyncio86+async def test_fragment_redirect():87+ client = RedirectAdapter(MockDispatch())88+ response = await client.request("GET", "https://example.org/relative_redirect#fragment")89+ assert response.status_code == codes.ok90+91+92+@pytest.mark.asyncio93 async def test_multiple_redirects():94 client = RedirectAdapter(MockDispatch())45- response = await client.request("GET", "https://example.org/multiple_redirects?count=20")95+ response = await client.request(96+ "GET", "https://example.org/multiple_redirects?count=20"97+ )98 assert response.status_code == codes.ok99 100 101 @pytest.mark.asyncio102 async def test_too_many_redirects():103 client = RedirectAdapter(MockDispatch())104 with pytest.raises(TooManyRedirects):105 await client.request("GET", "https://example.org/multiple_redirects?count=21")106+107+108+@pytest.mark.asyncio109+async def test_redirect_loop():110+ client = RedirectAdapter(MockDispatch())111+ with pytest.raises(RedirectLoop):112+ await client.request("GET", "https://example.org/redirect_loop")