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()