python中的requests如何中斷請求呢?我是多執行緒並發去get,但沒找到停止請求操作,只能wait執行緒結束,我以前用過socket套接字,裡面寫個狀態停止read那種就可以。 requests沒找到類似的方法。
import requests
from threading import Thread
from contextlib import closing
import json
import time
class 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()-t
with 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()-t
t = TestT()
t.start()
t.join(30)
t.stop()
t.join()
改了下,用了流式讀取,但是 get的時候,還是花了3秒多,如何中斷這3秒?
天蓬老师2017-05-18 10:55:01
加上一個IsStop變量,然後return停止線程
import requests
from threading import Thread
from contextlib import closing
import json
import time
class 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()-t
with closing(self.p) as r:
print time.time()-t
data = ''
for chunk in r.iter_content(4096):
if self.IsStop : return None
data += chunk
print json.loads(data)
print time.time()-t
t = TestT()
t.start()
t.join(30)
t.stop()
t.join()