Refactor middleware (#325)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Split middleware into a subpackage * Refactor basic auth header building * Add encoding parameter to to_bytes()
authored by Florimond Manca · committed by GitHub · parent 0f34f3b · Browse files · 8 files·+188 added−174 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+188 added−174 removed
- other:+188 added−174 removed
Provenance
- Commit
71648ec- Tree
6ed3cfb- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
0f34f3b
8 files changed+188 added−174 removed
added:httpx/middleware/__init__.py
added:httpx/middleware/base.py+10 added
1+import typing2+3+from ..models import AsyncRequest, AsyncResponse4+5+6+class BaseMiddleware:7+ async def __call__(8+ self, request: AsyncRequest, get_response: typing.Callable9+ ) -> AsyncResponse:10+ raise NotImplementedError # pragma: no coveradded:httpx/middleware/basic_auth.py+27 added
1+import typing2+from base64 import b64encode3+4+from ..models import AsyncRequest, AsyncResponse5+from ..utils import to_bytes6+from .base import BaseMiddleware7+8+9+class BasicAuthMiddleware(BaseMiddleware):10+ def __init__(11+ self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]12+ ):13+ self.authorization_header = build_basic_auth_header(username, password)14+15+ async def __call__(16+ self, request: AsyncRequest, get_response: typing.Callable17+ ) -> AsyncResponse:18+ request.headers["Authorization"] = self.authorization_header19+ return await get_response(request)20+21+22+def build_basic_auth_header(23+ username: typing.Union[str, bytes], password: typing.Union[str, bytes]24+) -> str:25+ userpass = b":".join((to_bytes(username), to_bytes(password)))26+ token = b64encode(userpass).decode().strip()27+ return f"Basic {token}"added:httpx/middleware/custom_auth.py+15 added
1+import typing2+3+from ..models import AsyncRequest, AsyncResponse4+from .base import BaseMiddleware5+6+7+class CustomAuthMiddleware(BaseMiddleware):8+ def __init__(self, auth: typing.Callable[[AsyncRequest], AsyncRequest]):9+ self.auth = auth10+11+ async def __call__(12+ self, request: AsyncRequest, get_response: typing.Callable13+ ) -> AsyncResponse:14+ request = self.auth(request)15+ return await get_response(request)added:httpx/middleware/redirect.py+128 added
1+import functools2+import typing3+4+from ..config import DEFAULT_MAX_REDIRECTS5+from ..exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects6+from ..models import URL, AsyncRequest, AsyncResponse, Cookies, Headers7+from ..status_codes import codes8+from .base import BaseMiddleware9+10+11+class RedirectMiddleware(BaseMiddleware):12+ def __init__(13+ self,14+ allow_redirects: bool = True,15+ max_redirects: int = DEFAULT_MAX_REDIRECTS,16+ cookies: typing.Optional[Cookies] = None,17+ ):18+ self.allow_redirects = allow_redirects19+ self.max_redirects = max_redirects20+ self.cookies = cookies21+ self.history: typing.List[AsyncResponse] = []22+23+ async def __call__(24+ self, request: AsyncRequest, get_response: typing.Callable25+ ) -> AsyncResponse:26+ if len(self.history) > self.max_redirects:27+ raise TooManyRedirects()28+ if request.url in (response.url for response in self.history):29+ raise RedirectLoop()30+31+ response = await get_response(request)32+ response.history = list(self.history)33+34+ if not response.is_redirect:35+ return response36+37+ self.history.append(response)38+ next_request = self.build_redirect_request(request, response)39+40+ if self.allow_redirects:41+ return await self(next_request, get_response)42+43+ response.call_next = functools.partial(self, next_request, get_response)44+ return response45+46+ def build_redirect_request(47+ self, request: AsyncRequest, response: AsyncResponse48+ ) -> AsyncRequest:49+ method = self.redirect_method(request, response)50+ url = self.redirect_url(request, response)51+ headers = self.redirect_headers(request, url, method) # TODO: merge headers?52+ content = self.redirect_content(request, method)53+ cookies = Cookies(self.cookies)54+ cookies.update(request.cookies)55+ return AsyncRequest(56+ method=method, url=url, headers=headers, data=content, cookies=cookies57+ )58+59+ def redirect_method(self, request: AsyncRequest, response: AsyncResponse) -> str:60+ """61+ When being redirected we may want to change the method of the request62+ based on certain specs or browser behavior.63+ """64+ method = request.method65+66+ # https://tools.ietf.org/html/rfc7231#section-6.4.467+ if response.status_code == codes.SEE_OTHER and method != "HEAD":68+ method = "GET"69+70+ # Do what the browsers do, despite standards...71+ # Turn 302s into GETs.72+ if response.status_code == codes.FOUND and method != "HEAD":73+ method = "GET"74+75+ # If a POST is responded to with a 301, turn it into a GET.76+ # This bizarre behaviour is explained in 'requests' issue 1704.77+ if response.status_code == codes.MOVED_PERMANENTLY and method == "POST":78+ method = "GET"79+80+ return method81+82+ def redirect_url(self, request: AsyncRequest, response: AsyncResponse) -> URL:83+ """84+ Return the URL for the redirect to follow.85+ """86+ location = response.headers["Location"]87+88+ url = URL(location, allow_relative=True)89+90+ # Facilitate relative 'Location' headers, as allowed by RFC 7231.91+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')92+ if url.is_relative_url:93+ url = request.url.join(url)94+95+ # Attach previous fragment if needed (RFC 7231 7.1.2)96+ if request.url.fragment and not url.fragment:97+ url = url.copy_with(fragment=request.url.fragment)98+99+ return url100+101+ def redirect_headers(self, request: AsyncRequest, url: URL, method: str) -> Headers:102+ """103+ Return the headers that should be used for the redirect request.104+ """105+ headers = Headers(request.headers)106+107+ if url.origin != request.url.origin:108+ # Strip Authorization headers when responses are redirected away from109+ # the origin.110+ headers.pop("Authorization", None)111+ headers["Host"] = url.authority112+113+ if method != request.method and method == "GET":114+ # If we've switch to a 'GET' request, then strip any headers which115+ # are only relevant to the request body.116+ headers.pop("Content-Length", None)117+ headers.pop("Transfer-Encoding", None)118+ return headers119+120+ def redirect_content(self, request: AsyncRequest, method: str) -> bytes:121+ """122+ Return the body that should be used for the redirect request.123+ """124+ if method != request.method and method == "GET":125+ return b""126+ if request.is_streaming:127+ raise RedirectBodyUnavailable()128+ return request.contentmodified:httpx/client.py+4 added-6 removed
21 unmodified lines22 from .dispatch.connection_pool import ConnectionPool23 from .dispatch.threaded import ThreadedDispatcher24 from .dispatch.wsgi import WSGIDispatch25 from .exceptions import HTTPError, InvalidURL26-from .middleware import (27- BaseMiddleware,28- BasicAuthMiddleware,29- CustomAuthMiddleware,30- RedirectMiddleware,31-)26+from .middleware.base import BaseMiddleware27+from .middleware.basic_auth import BasicAuthMiddleware28+from .middleware.custom_auth import CustomAuthMiddleware29+from .middleware.redirect import RedirectMiddleware30 from .models import (31 URL,32 AsyncRequest,33 AsyncRequestData,863 unmodified linesdeleted:httpx/middleware.py-168 removed
1-import functools2-import typing3-from base64 import b64encode4-5-from .config import DEFAULT_MAX_REDIRECTS6-from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects7-from .models import URL, AsyncRequest, AsyncResponse, Cookies, Headers8-from .status_codes import codes9-10-11-class BaseMiddleware:12- async def __call__(13- self, request: AsyncRequest, get_response: typing.Callable14- ) -> AsyncResponse:15- raise NotImplementedError # pragma: no cover16-17-18-class 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")24-25- if isinstance(password, str):26- password = password.encode("latin1")27-28- userpass = b":".join((username, password))29- token = b64encode(userpass).decode().strip()30-31- self.authorization_header = f"Basic {token}"32-33- async def __call__(34- self, request: AsyncRequest, get_response: typing.Callable35- ) -> AsyncResponse:36- request.headers["Authorization"] = self.authorization_header37- return await get_response(request)38-39-40-class CustomAuthMiddleware(BaseMiddleware):41- def __init__(self, auth: typing.Callable[[AsyncRequest], AsyncRequest]):42- self.auth = auth43-44- async def __call__(45- self, request: AsyncRequest, get_response: typing.Callable46- ) -> AsyncResponse:47- request = self.auth(request)48- return await get_response(request)49-50-51-class 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] = []62-63- 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()70-71- response = await get_response(request)72- response.history = list(self.history)73-74- if not response.is_redirect:75- return response76-77- self.history.append(response)78- next_request = self.build_redirect_request(request, response)79-80- if self.allow_redirects:81- return await self(next_request, get_response)82-83- response.call_next = functools.partial(self, next_request, get_response)84- return response85-86- 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- )98-99- 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.method105-106- # https://tools.ietf.org/html/rfc7231#section-6.4.4107- if response.status_code == codes.SEE_OTHER and method != "HEAD":108- method = "GET"109-110- # 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"114-115- # 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"119-120- return method121-122- 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"]127-128- url = URL(location, allow_relative=True)129-130- # 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)134-135- # 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)138-139- return url140-141- 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)146-147- if url.origin != request.url.origin:148- # Strip Authorization headers when responses are redirected away from149- # the origin.150- headers.pop("Authorization", None)151- headers["Host"] = url.authority152-153- if method != request.method and method == "GET":154- # If we've switch to a 'GET' request, then strip any headers which155- # are only relevant to the request body.156- headers.pop("Content-Length", None)157- headers.pop("Transfer-Encoding", None)158- return headers159-160- def redirect_content(self, request: AsyncRequest, method: str) -> bytes:161- """162- Return the body that should be used for the redirect request.163- """164- if method != request.method and method == "GET":165- return b""166- if request.is_streaming:167- raise RedirectBodyUnavailable()168- return request.contentmodified:httpx/utils.py+4 added
167 unmodified lines168 )169 logger.addHandler(handler)170 171 return logging.getLogger(name)172+173+174+def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:175+ return value.encode(encoding) if isinstance(value, str) else value