您的位置:首页技术文章
文章详情页

python - Requests 如何中断请求?

浏览:88日期:2022-07-15 09:36:32

问题描述

python中的requests如何中断请求呢? 我是多线程并发去get,但是没找到停止请求操作,只能wait线程结束,我以前用过socket套接字,里面写个状态停止read那种就可以。 requests没找到类似的方法。

import requestsfrom threading import Threadfrom contextlib import closingimport jsonimport timeclass TestT(Thread): def __init__(self):super(TestT, self).__init__()self.s = requests.session() def stop(self):self.p.connection.close()self.s.close() def run(self):t = time.time()self.p = self.s.get(’http://api2.qingmo.com/api/column/tree/one?Pid=8&Child=1’, stream=True, timeout=10)# 消耗了很多时间print time.time()-twith closing(self.p) as r: print time.time()-t data = ’’ for chunk in r.iter_content(4096):data += chunk print json.loads(data)print time.time()-tt = TestT()t.start()t.join(30)t.stop()t.join()

改了下,用了流式读取,但是 get的时候,还是花了3秒多,如何中断这3秒?

问题解答

回答1:

加一个IsStop变量,然后return停止线程

import requestsfrom threading import Threadfrom contextlib import closingimport jsonimport timeclass TestT(Thread): def __init__(self):super(TestT, self).__init__()self.s = requests.session()self.IsStop = False def stop(self):self.p.connection.close()self.s.close()self.IsStop = True def run(self):t = time.time()self.p = self.s.get(’http://api2.qingmo.com/api/column/tree/one?Pid=8&Child=1’, stream=True, timeout=10)# 消耗了很多时间print time.time()-twith closing(self.p) as r: print time.time()-t data = ’’ for chunk in r.iter_content(4096):if self.IsStop : return Nonedata += chunk print json.loads(data)print time.time()-tt = TestT()t.start()t.join(30)t.stop()t.join()

标签: Python 编程
相关文章: