Skip to content
Myr

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

5 files+92 added−10 removed

modified:httpcore/adapters/redirects.py+5 added-1 removed
1import typing2from urllib.parse import urljoin, urlparse34from ..config import DEFAULT_MAX_REDIRECTS5from ..exceptions import TooManyRedirects5from ..exceptions import RedirectLoop, TooManyRedirects6from ..interfaces import Adapter7from ..models import URL, Request, Response8from ..status_codes import codes9from ..utils import requote_uri
9 unmodified lines
1920 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,))2425 while True:26 response = await self.dispatch.send(request, **options)27 if not allow_redirects or not response.is_redirect:
1 unmodified line
29 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)3637 return response3839 async def close(self) -> None:
52 unmodified lines
modified:httpcore/__init__.py+2 added-1 removed
8 unmodified lines
9 ConnectTimeout,10 PoolTimeout,11 ProtocolError,12 ReadTimeout,13 RedirectLoop,14 ResponseClosed,15 StreamConsumed,16 Timeout,16 TooManyRedirects17 TooManyRedirects,18)19from .interfaces import Adapter20from .models import URL, Headers, Origin, Request, Response21from .status_codes import codes
4 unmodified lines
modified:httpcore/exceptions.py+13 added-1 removed
26 unmodified lines
27 Timeout while waiting to acquire a connection from the pool.28 """293031class TooManyRedirects(Exception):31class RedirectError(Exception):32 """33 Base class for HTTP redirect errors.34 """353637class TooManyRedirects(RedirectError):38 """39 Too many redirects.40 """414243class RedirectLoop(RedirectError):44 """45 Infinite redirect loop.46 """474849class ProtocolError(Exception):50 """51 Malformed HTTP.52 """
19 unmodified lines
modified:httpcore/models.py+6 added
68 unmodified lines
69 @property70 def origin(self) -> "Origin":71 return Origin(self)7273 def __hash__(self) -> int:74 return hash(str(self))7576 def __eq__(self, other: typing.Any) -> bool:77 return isinstance(other, URL) and str(self) == str(other)7879 def __str__(self) -> str:80 return self.components.geturl()8182
279 unmodified lines
modified:tests/adapters/test_redirects.py+66 added-7 removed
1import pytest1from urllib.parse import parse_qs24from httpcore import Adapter, RedirectAdapter, Request, Response, TooManyRedirects, codes3import pytest45from httpcore import (6 Adapter,7 RedirectAdapter,8 RedirectLoop,9 Request,10 Response,11 TooManyRedirects,12 codes,13)141516class MockDispatch(Adapter):17 def prepare_request(self, request: Request) -> None:18 pass1920 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/")])2324 elif request.url.path == "/redirect_302": # "Found"25 return Response(302, headers=[(b"location", b"https://example.org/")])2627 elif request.url.path == "/redirect_303": # "See Other"28 return Response(303, headers=[(b"location", b"https://example.org/")])2930 elif request.url.path == "/relative_redirect":31 return Response(codes.see_other, headers=[(b"location", b"/")])3233 elif request.url.path == "/no_scheme_redirect":34 return Response(codes.see_other, headers=[(b"location", b"//example.org/")])3536 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)4344 if request.url.path == "/redirect_loop":45 return Response(codes.see_other, headers=[(b"location", b"/redirect_loop")])4647 return Response(codes.ok, body=b"Hello, world!")484950@pytest.mark.asyncio51async 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.ok555657@pytest.mark.asyncio58async 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.ok626364@pytest.mark.asyncio65async 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.ok
6 unmodified lines
75 assert response.status_code == codes.ok767778@pytest.mark.asyncio79async 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.ok838485@pytest.mark.asyncio86async 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.ok909192@pytest.mark.asyncio93async 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.ok99100101@pytest.mark.asyncio102async 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")106107108@pytest.mark.asyncio109async def test_redirect_loop():110 client = RedirectAdapter(MockDispatch())111 with pytest.raises(RedirectLoop):112 await client.request("GET", "https://example.org/redirect_loop")