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))
将此适配器用于会话对象中,以下代码将适配器安装到所有的HTTP和HTTPS连接中,使用54321
作为源端口:
适配器应用于会话对象,下面的代码将适配器安装到所有的HTTP和HTTPS连接中,使用54321作为源端口:
s = requests.Session()
s.mount('http://', SourcePortAdapter(54321))
s.mount('https://', SourcePortAdapter(54321))
您只能设置一个源端口,这将限制您一次只能有一个活动连接。如果您需要在不同的端口之间轮换,请注册多个适配器(每个 URL 一个)或每次重新注册全局挂载点。
有关 source_address
选项的详细信息,请参见create_connection()
实用程序函数文档:
如果设置了 source_address
,则必须将其设置为要在建立连接之前将套接字绑定为源地址的 (host, port)
元组。主机为 ''
或端口为 0
,则表示使用默认值。