requests
은 urllib3
에 있으며 연결에 대한 원본 주소를 설정할 수 있습니다. 원본 주소를 ('', port_number)
으로 설정하면 기본 호스트 이름을 사용하지만 특정 포트를 선택하도록 지정합니다.
당신은 pool manager에서 이러한 옵션을 설정할 수 있습니다, 그리고 당신은 transport adapter 새로운 생성하여 다른 풀 관리자를 사용 requests
알려주기 : 어댑터, 세션 객체에
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
class SourcePortAdapter(HTTPAdapter):
""""Transport adapter" that allows us to set the source port."""
def __init__(self, port, *args, **kwargs):
self._source_port = port
super(SourcePortAdapter, self).__init__(*args, **kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(
num_pools=connections, maxsize=maxsize,
block=block, source_address=('', self._source_port))
사용에게 다음과 같은 마운트를이 어댑터를 소스 포트로 54321
를 사용 모든 HTTP 및 HTTPS 연결 :
s = requests.Session()
s.mount('http://', SourcePortAdapter(54321))
s.mount('https://', SourcePortAdapter(54321))
당신은 단지 하나 개의 소스 포트를 설정할 수 있습니다 한 번에 하나의 활성 연결로 제한됩니다. 포트간에 순환해야하는 경우 URL마다 하나씩 여러 어댑터를 등록하거나 매번 catch-all 마운트를 다시 등록하십시오.
는
source_address
옵션에 대한 자세한 내용은
create_connection()
utility function documentation를 참조하십시오 : 당신은 표준 소켓에 할 수 없어
If source_address
is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection. An host of ''
or port 0
tells the OS to use the default.
. 포트는 OS에 의해 선택됩니다. –
@KlausD .: 예. 표준 소켓에서 그렇게 할 수 있습니다. * default *는 OS에 그대로 두는 것입니다. –
@KlausD : 트릭은 기본값 대신 특정 포트를 사용하도록 요청하는 방법에만 있습니다. –