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. centos7 編譯安裝 Python 3.5.1 失敗2. mysql 把其中兩行合并怎么解決3. mysql - 無恥的請教一條sql4. python3.x - python3.5使用pyinstaller打包報錯找不到libpython3.5mu.so.1.0等文件求解?5. python3.x - python連oanda的模擬交易api獲取json問題第二問6. MySQL中的enum類型有什么優點?7. phpStudy2017輕巧版mysql無法啟動8. 為什么我寫的PHP不行9. flask - python web中如何共享登錄狀態?10. 為什么我輸入了refresh不會跳轉?請教大神支招!
