Skip to content
Myr

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

8 files+188 added−174 removed

added:httpx/middleware/__init__.py
added:httpx/middleware/base.py+10 added
1import typing23from ..models import AsyncRequest, AsyncResponse456class BaseMiddleware:7 async def __call__(8 self, request: AsyncRequest, get_response: typing.Callable9 ) -> AsyncResponse:10 raise NotImplementedError # pragma: no cover
added:httpx/middleware/basic_auth.py+27 added
1import typing2from base64 import b64encode34from ..models import AsyncRequest, AsyncResponse5from ..utils import to_bytes6from .base import BaseMiddleware789class 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)1415 async def __call__(16 self, request: AsyncRequest, get_response: typing.Callable17 ) -> AsyncResponse:18 request.headers["Authorization"] = self.authorization_header19 return await get_response(request)202122def 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
1import typing23from ..models import AsyncRequest, AsyncResponse4from .base import BaseMiddleware567class CustomAuthMiddleware(BaseMiddleware):8 def __init__(self, auth: typing.Callable[[AsyncRequest], AsyncRequest]):9 self.auth = auth1011 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
1import functools2import typing34from ..config import DEFAULT_MAX_REDIRECTS5from ..exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects6from ..models import URL, AsyncRequest, AsyncResponse, Cookies, Headers7from ..status_codes import codes8from .base import BaseMiddleware91011class 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] = []2223 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()3031 response = await get_response(request)32 response.history = list(self.history)3334 if not response.is_redirect:35 return response3637 self.history.append(response)38 next_request = self.build_redirect_request(request, response)3940 if self.allow_redirects:41 return await self(next_request, get_response)4243 response.call_next = functools.partial(self, next_request, get_response)44 return response4546 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 )5859 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.method6566 # https://tools.ietf.org/html/rfc7231#section-6.4.467 if response.status_code == codes.SEE_OTHER and method != "HEAD":68 method = "GET"6970 # 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"7475 # 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"7980 return method8182 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"]8788 url = URL(location, allow_relative=True)8990 # 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)9495 # 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)9899 return url100101 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)106107 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.authority112113 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 headers119120 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.content
modified:httpx/client.py+4 added-6 removed
21 unmodified lines
22from .dispatch.connection_pool import ConnectionPool23from .dispatch.threaded import ThreadedDispatcher24from .dispatch.wsgi import WSGIDispatch25from .exceptions import HTTPError, InvalidURL26from .middleware import (27 BaseMiddleware,28 BasicAuthMiddleware,29 CustomAuthMiddleware,30 RedirectMiddleware,31)26from .middleware.base import BaseMiddleware27from .middleware.basic_auth import BasicAuthMiddleware28from .middleware.custom_auth import CustomAuthMiddleware29from .middleware.redirect import RedirectMiddleware30from .models import (31 URL,32 AsyncRequest,33 AsyncRequestData,
863 unmodified lines
deleted:httpx/middleware.py-168 removed
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 headers.pop("Authorization", None)151 headers["Host"] = url.authority152153 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 headers159160 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.content
modified:httpx/utils.py+4 added
167 unmodified lines
168 )169 logger.addHandler(handler)170171 return logging.getLogger(name)172173174def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:175 return value.encode(encoding) if isinstance(value, str) else value