Skip to content
Myr

middleware.py

This file

Path

httpx/middleware.py

167 lines · 5.7 KiB · Python

Last changed by

White whitespacingTom Christiebefore adoptione5964b3

History of this file

Take it

1import functools2import typing3from base64 import b64encode45from .config import DEFAULT_MAX_REDIRECTS6from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects7from .models import URL, AsyncRequest, AsyncResponse, Cookies, Headers8from .status_codes import codes91011class BaseMiddleware:12    async def __call__(13        self, request: AsyncRequest, get_response: typing.Callable14    ) -> AsyncResponse:15        raise NotImplementedError  # pragma: no cover161718class BasicAuthMiddleware(BaseMiddleware):19    def __init__(20        self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]21    ):22        if isinstance(username, str):23            username = username.encode("latin1")2425        if isinstance(password, str):26            password = password.encode("latin1")2728        userpass = b":".join((username, password))29        token = b64encode(userpass).decode().strip()3031        self.authorization_header = f"Basic {token}"3233    async def __call__(34        self, request: AsyncRequest, get_response: typing.Callable35    ) -> AsyncResponse:36        request.headers["Authorization"] = self.authorization_header37        return await get_response(request)383940class CustomAuthMiddleware(BaseMiddleware):41    def __init__(self, auth: typing.Callable[[AsyncRequest], AsyncRequest]):42        self.auth = auth4344    async def __call__(45        self, request: AsyncRequest, get_response: typing.Callable46    ) -> AsyncResponse:47        request = self.auth(request)48        return await get_response(request)495051class RedirectMiddleware(BaseMiddleware):52    def __init__(53        self,54        allow_redirects: bool = True,55        max_redirects: int = DEFAULT_MAX_REDIRECTS,56        cookies: typing.Optional[Cookies] = None,57    ):58        self.allow_redirects = allow_redirects59        self.max_redirects = max_redirects60        self.cookies = cookies61        self.history: typing.List[AsyncResponse] = []6263    async def __call__(64        self, request: AsyncRequest, get_response: typing.Callable65    ) -> AsyncResponse:66        if len(self.history) > self.max_redirects:67            raise TooManyRedirects()68        if request.url in (response.url for response in self.history):69            raise RedirectLoop()7071        response = await get_response(request)72        response.history = list(self.history)7374        if not response.is_redirect:75            return response7677        self.history.append(response)78        next_request = self.build_redirect_request(request, response)7980        if self.allow_redirects:81            return await self(next_request, get_response)8283        response.call_next = functools.partial(self, next_request, get_response)84        return response8586    def build_redirect_request(87        self, request: AsyncRequest, response: AsyncResponse88    ) -> AsyncRequest:89        method = self.redirect_method(request, response)90        url = self.redirect_url(request, response)91        headers = self.redirect_headers(request, url, method)  # TODO: merge headers?92        content = self.redirect_content(request, method)93        cookies = Cookies(self.cookies)94        cookies.update(request.cookies)95        return AsyncRequest(96            method=method, url=url, headers=headers, data=content, cookies=cookies97        )9899    def redirect_method(self, request: AsyncRequest, response: AsyncResponse) -> str:100        """101        When being redirected we may want to change the method of the request102        based on certain specs or browser behavior.103        """104        method = request.method105106        # https://tools.ietf.org/html/rfc7231#section-6.4.4107        if response.status_code == codes.SEE_OTHER and method != "HEAD":108            method = "GET"109110        # Do what the browsers do, despite standards...111        # Turn 302s into GETs.112        if response.status_code == codes.FOUND and method != "HEAD":113            method = "GET"114115        # If a POST is responded to with a 301, turn it into a GET.116        # This bizarre behaviour is explained in 'requests' issue 1704.117        if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":118            method = "GET"119120        return method121122    def redirect_url(self, request: AsyncRequest, response: AsyncResponse) -> URL:123        """124        Return the URL for the redirect to follow.125        """126        location = response.headers["Location"]127128        url = URL(location, allow_relative=True)129130        # Facilitate relative 'Location' headers, as allowed by RFC 7231.131        # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')132        if url.is_relative_url:133            url = request.url.join(url)134135        # Attach previous fragment if needed (RFC 7231 7.1.2)136        if request.url.fragment and not url.fragment:137            url = url.copy_with(fragment=request.url.fragment)138139        return url140141    def redirect_headers(self, request: AsyncRequest, url: URL, method: str) -> Headers:142        """143        Return the headers that should be used for the redirect request.144        """145        headers = Headers(request.headers)146147        if url.origin != request.url.origin:148            # Strip Authorization headers when responses are redirected away from149            # the origin.150            del headers["Authorization"]151            del headers["Host"]152153        if method != request.method and method == "GET":154            # Strip Content-Length headers when we've switch to a 'GET' request.155            del headers["Content-Length"]156157        return headers158159    def redirect_content(self, request: AsyncRequest, method: str) -> bytes:160        """161        Return the body that should be used for the redirect request.162        """163        if method != request.method and method == "GET":164            return b""165        if request.is_streaming:166            raise RedirectBodyUnavailable()167        return request.content