Home  >  Q&A  >  body text

Requests How to interrupt a request?

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?

PHPzPHPz2711 days ago1290

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-05-18 10:55:01

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

    reply
    0
  • Cancelreply