requests
是建立在urllib3,它提供了设置连接源地址的能力;当您将源地址设置为('', port_number)
您告诉它使用默认主机名但选择特定端口。
您可以在泳池经理,然后你告诉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))
在会话对象中使用此适配器,以下安装适配器用于allHTTP 和 HTTPS 连接,使用54321
作为源端口:
s = requests.Session()
s.mount('http://', SourcePortAdapter(54321))
s.mount('https://', SourcePortAdapter(54321))
您只能设置一个源端口,从而限制您一次只有一个活动连接。如果您需要在端口之间轮换,请注册多个适配器(每个 URL 一个)或每次重新注册全部挂载。
See the create_connection()实用函数文档有关详细信息source_address
option:
If source_address
已设置,它必须是一个元组(host, port)
在建立连接之前将套接字绑定为源地址。主机''
或端口0
告诉操作系统使用默认值。