请求,无法分配请求的地址,超出端口?

requests, cannot assign requested address, out of ports?

requests.exceptions.ConnectionError: ('Connection aborted.', error(99, 'Cannot assign requested address'))

当 运行 多个进程利用 python 请求库并将 post 函数调用到返回速度非常快的 API 时(< 10 毫秒)。

减少进程数 运行 有延迟效果,但只减少到 1 个进程就解决了问题。这不是解决方案,但确实表明有限的资源是罪魁祸首。

我解决问题的方法是使用 requests.Session class,我会在给定进程中为每个调用重复使用相同的 connection/session。

人为的例子:

import requests
for line in file:
  requests.get('http://example.com/api?key={key}'.format(key=line['key']))

变成

import requests
with requests.Session() as session:
  for line in file:
    session.get('http://example.com/api?key={key}'.format(key=line['key']))

这些问题有一些相关的建议:

Repeated POST request is causing error "socket.error: (99, 'Cannot assign requested address')" Python urllib2: Cannot assign requested address

我在 Spark 中使用 python 的请求库执行多个 POST 语句时也遇到了类似的问题。 更糟糕的是,我对每个执行程序使用多处理 post 到服务器。 因此,数以千计的连接在几秒钟内创建,每个连接花费几秒钟时间从 TIME_WAIT 更改状态并为下一组连接释放端口。

在互联网上提到禁用 keep-alive 的所有可用解决方案中,使用 request.Session() 等,我发现 this 答案有效。不过,您可能需要将 header 内容放在 post 命令之外的单独一行中。

headers = {
        'Connection': 'close'
}
with requests.Session() as session:
response = session.post('https://xx.xxx.xxx.x/xxxxxx/x', headers=headers, files=files, verify=False)
results = response.json()
print results