Requests How to interrupt a request?
PHPz
PHPz 2017-05-18 10:53:01
0
1
1343

How to interrupt requests in requests in python? I used multiple threads to get concurrently, but I couldn't find the stop request operation. I could only wait for the thread to end. I have used socket sockets before, and just write a status to stop reading. requests did not find a similar method.

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

I changed it and used streaming reading, but it still took more than 3 seconds to get. How to interrupt these 3 seconds?

PHPz
PHPz

学习是最好的投资!

reply all(1)
Peter_Zhu

Add an IsStop variable and then return to stop the thread

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()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template