python - Requests 如何中斷請求?
問題描述
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()
相關文章:
1. python - 啟動Eric6時報錯:’qscintilla_zh_CN’ could not be loaded2. php - 微信開發驗證服務器有效性3. MySQL中的enum類型有什么優點?4. android下css3動畫非常卡,GPU也不差啊5. mysql - 記得以前在哪里看過一個估算時間的網站6. css3 - 純css實現點擊特效7. javascript - 關于<a>元素與<input>元素的JS事件運行問題8. javascript - vue 怎么渲染自定義組件9. python - 有什么好的可以收集貨幣基金的資源?10. html - vue項目中用到了elementUI問題
