Requests의 HTTPAdapter.proxy_headers로 프록시 헤더 설정하기
프록시가 정의한 필드를 위해 HTTPAdapter.proxy_headers를 확장하면서 Requests의 기존 프록시 인증 헤더 생성을 유지합니다.
프록시 운영자가 정의한 헤더에 대해 Requests는 HTTPAdapter.proxy_headers를 재정의 지점으로 제공합니다:
from urllib.parse import urlsplit
import requests
from requests.adapters import HTTPAdapter
class TaggedProxy(HTTPAdapter):
def proxy_headers(self, proxy):
headers = super().proxy_headers(proxy)
endpoint = urlsplit(proxy)
if (endpoint.scheme == 'http'
and endpoint.hostname == 'proxy.example'
and endpoint.port == 8080):
headers['X-Proxy-Account'] = 'department-a'
return headers
with requests.Session() as session:
adapter = TaggedProxy()
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.get(
'https://service.example/data',
proxies={'https': 'http://proxy.example:8080'},
timeout=15,
)
X-Proxy-Account는 이 특정 프록시가 이해하는 필드의 예이며, 모든 중개자에 대한 표준 인증 방식은 아닙니다.
super().proxy_headers(proxy)로 시작하세요. URL이 Basic 계정을 제공할 때 Requests는 그 메서드로 Proxy-Authorization을 생성합니다. 결과 전체를 교체하면 그 동작을 잃을 수 있습니다.
어댑터는 이 값들을 urllib3의 ProxyManager로 전달합니다. HTTPS 터널에서는 CONNECT와 함께 갑니다. 일반 요청 헤더 매핑은 이후의 목적지 요청을 설명합니다.
프록시 관리자는 프록시 URL별로 캐시됩니다. 호출마다 바뀌어야 하는 값에 대해 이 훅을 캐시되지 않는 업무 요청별 콜백으로 취급하지 마세요. 계정 표시가 달라지면 그에 맞게 전송 주체를 선택하세요.
단순 HTTP 전달에서는 프록시 필드에 여전히 중개자가 의도한 처리 정책이 필요합니다. 클라이언트 API에서 헤더가 프록시 전용이라는 사실은 프록시가 그것을 계속 전달할 경우 기밀성 보장이 아닙니다.