Python 3 - 请求库 - iter_lines - 读取流数据块时处理可能的服务器停顿

Ant*_*toG 4 python python-requests

当我从中读取数据时,我需要找到一种顺利管理服务器停顿的方法。我写了下面这段代码:

def listener():    
    resp = requests.get(someurl, stream=True)
    if resp.status_code == 200:
        for line in resp.iter_lines():            
            if line:
                do_something_with_the_line
                print(result)

price_thread = threading.Thread(target=listener, name="StreamingThread", args=[])
trade_thread.start()
Run Code Online (Sandbox Code Playgroud)

该代码运行良好,直到服务器发生停顿(API 提供者建议当 10 秒内没有收到“行”时发生停顿)。

我如何在我的代码中实现这一点?换句话说,当发生停顿时,我会尝试调用该listener方法而不退出线程。price_thread

提前致谢

zwe*_*wer 5

您可以使用该timeout属性来确保在指定时间内没有收到数据后连接中断,然后重新生成连接:

def listener():
    while True:
        try:
            resp = requests.get(someurl, stream=True, timeout=10)
            if resp.status_code == 200:
                for line in resp.iter_lines():
                    if line:
                        # do_something_with_the_line
                        pass
            elif resp.status_code == 429:
                    print("Too many reconnects, exiting.")
                    break
            else:
                print("Unhandled status `{}` retreived, exiting.".format(resp.status_code))
                break
        except requests.exceptions.Timeout:
            pass  # we'll ignore timeout errors and reconnect
        except requests.exceptions.RequestException as e:
            print("Request exception `{}`, exiting".format(e))
            break
Run Code Online (Sandbox Code Playgroud)

您还可以添加一个重新连接计数器,而不是while True无限期地循环。