Python使用requests時遇到Failed to establish a new connection

Posted ExplorerMan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python使用requests時遇到Failed to establish a new connection相关的知识,希望对你有一定的参考价值。

再寫Zeppelin的CLI工具的時候
https://github.com/del680202/zdairi

遇到了開起太多connection這樣一個錯誤

requests.exceptions.ConnectionError: HTTPConnectionPool(host=‘xxxxx‘, port=xxxxx): Max retries exceeded with url: /api/notebook/2BG5CTGN7/paragraph/20160407-173136_827952200 (Caused by NewConnectionError(‘<requests.packages.urllib3.connection.HTTPConnection object at 0x29b44d0>: Failed to establish a new connection: [Errno 99] Cannot assign requested address‘,))

細查了一下原因出在我是用Python的requests套件去送HTTP Request
原本我一直以為下面這種寫法不會占用到太多connection資源

requests.post("http....")
requests.get("http....")

但是程式邏輯的關係我會在短時間使用多次requests.post
其結果就是跳出了Failed to establish a new connection這樣一個錯誤
google一下之後,一個根本的解決方法是在發起一個http request之後設定header將其關閉

修改如下

requests..get("http://...", headers={‘Connection‘:‘close‘})
requests..post("http://...", headers={‘Connection‘:‘close‘})

這邊做個筆記

以上是关于Python使用requests時遇到Failed to establish a new connection的主要内容,如果未能解决你的问题,请参考以下文章

iOS 使用AFNetworking遇到异常 Request failed: unacceptable content-type: text/html

AFNetworking 遇到错误 Code=-1016 "Request failed: unacceptable content-type: text/plain"

CSRF verification failed. Request aborted.

Apache无法启动提示the requested operation has failed

Dynamics 365 msis 7069 The specified request failed

Failed to load resource: the server responded with a status of 400 (Bad Request) 错误请求解决