python - Requests 如何中斷請求?
問題描述
python中的requests如何中斷請求呢? 我是多線程并發(fā)去get,但是沒找到停止請求操作,只能wait線程結(jié)束,我以前用過socket套接字,里面寫個狀態(tài)停止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()
相關(guān)文章:
1. mac連接阿里云docker集群,已經(jīng)卡了2天了,求問?2. ddos - apache日志很多其它網(wǎng)址,什么情況?3. 上傳圖片老是失敗是什么原因?SAE_TMP_PATH.后面跟的路徑在哪看4. javascript - 關(guān)于jquery的ajax post數(shù)據(jù)的問題5. 前端 - 我有一個建站程序,但是多個文件夾下的HTML模板代碼沒有進(jìn)行縮進(jìn)格式化,請問用什么軟件可以批量格式化一下代碼?6. android-studio - Win10下修改Windows用戶文件夾名user,導(dǎo)致Android Studio報錯無法使用7. phpstudy pro小皮面板經(jīng)常報這個nginx: [emerg] CreateFile【急】8. thinkphp5.1學(xué)習(xí)時遇到session問題9. angular.js - angular 路由為什么一直請求css和js文件10. javascript - setTimeout的延遲時間,是從什么時間段開始算起的?
