【问题标题】:Socket.getaddrinfo gets stuck, blocking the process indefinitely when using requests in pythonSocket.getaddrinfo卡住,在python中使用请求时无限期阻塞进程
【发布时间】:2017-05-03 16:22:15
【问题描述】:

这是我的项目的简单演示:

import requests
import json, time
import socket
socket.setdefaulttimeout(2)
def request(url, msg=None, timeout=2, method="get"):
    flag, resp = False, None
    try:
        if method == "get":
            resp = requests.get(url, params=msg, timeout=timeout, verify=False)
    elif method == "post":
        resp = requests.post(url, data=msg, timeout=timeout, verify=False)
    elif method == "delete":
        s=requests.Session()
        resp = s.delete(url, data=msg, timeout=timeout, verify=False)

    flag = True
    except requests.exceptions.Timeout:
        resp = "time_out"
    except requests.exceptions.TooManyRedirects:
        resp = "too_many_redirect"
    except requests.ConnectionError as err:
        resp = "connection_error"
    except requests.exceptions.RequestException as err:
        resp = str(err.__class__.__name__)

    return flag, resp

if __name__ == '__main__':
    while True:
        print request("https://www.google.com", timeout=1)
        time.sleep(1)

运行一段时间后,进程会阻塞,当我 pstack 时,我总是看到这个:

Thread 3 (Thread 0x7f465f310700 (LWP 22537)):
#0  0x00000030dd0e993d in recvmsg () from /lib64/libc.so.6
#1  0x00000030dd10f8d5 in make_request () from /lib64/libc.so.6
#2  0x00000030dd10fd0a in __check_pf () from /lib64/libc.so.6
#3  0x00000030dd0d2ec7 in getaddrinfo () from /lib64/libc.so.6
#4  0x00007f46647e07bf in socket_getaddrinfo () from ...

我发现了一条消息here,并且知道它在查询 DNS 时被阻塞,我已经为请求设置了超时,但它没有用!有人遇到过这个问题吗?感谢您的帮助。

【问题讨论】:

    标签: python python-requests blocking


    【解决方案1】:

    经过谷歌长时间的搜索,我找到了这个帖子[Bug libc/12926] getaddrinfo()/make_request() may spin forever,并修复了The GNU C Library version 2.23中的错误。但是在我的机器上更新 glibc 是不可能的。

    我以前也写过一个使用requests模块的python程序,它没有这个问题,所以我仔细比较了两者,我发现最大的区别是数量使用http请求请求的线程。第一个只有一个使用请求的线程,但最后一个有两个所以我将程序重构为单线程程序进行测试。问题再也没有发生过。

    man page of requests 说请求是线程安全的,我还没有找到这个错误的确切原因,所以我只是使用单线程方法来避免这个问题。

    如果有人知道任何建议将不胜感激。

    【讨论】:

      猜你喜欢
      • 2014-09-13
      • 1970-01-01
      • 2021-10-13
      • 2016-07-12
      • 2018-03-13
      • 1970-01-01
      • 2022-01-24
      • 2020-03-04
      • 2012-05-14
      相关资源
      最近更新 更多