Heim  >  Fragen und Antworten  >  Hauptteil

Anfragen Wie kann ich eine Anfrage unterbrechen?

Wie unterbreche ich Anfragen in Anfragen in Python? Ich habe mehrere Threads gleichzeitig verwendet, aber ich konnte den Stoppanforderungsvorgang nicht finden. Ich habe zuvor nur auf das Ende des Threads gewartet und einfach einen Status hineingeschrieben, um das Lesen zu beenden. Anfragen haben keine ähnliche Methode gefunden.

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

Ich habe es geändert und Streaming-Lesen verwendet, aber beim Abrufen dauerte es immer noch mehr als 3 Sekunden. Wie kann ich diese 3 Sekunden unterbrechen?

PHPzPHPz2711 Tage vor1288

Antworte allen(1)Ich werde antworten

  • 天蓬老师

    天蓬老师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()

    Antwort
    0
  • StornierenAntwort