Python - Example of urllib2 asynchronous / threaded request using HTTPS

前端 未结 5 1365
梦谈多话
梦谈多话 2021-02-02 13:50

I\'m having a heck of a time getting asynchronous / threaded HTTPS requests to work using Python\'s urllib2.

Does anyone out there have a basic example that implements u

5条回答
  •  死守一世寂寞
    2021-02-02 14:26

    there's a really simple way, involving a handler for urllib2, which you can find here: http://pythonquirks.blogspot.co.uk/2009/12/asynchronous-http-request.html

    #!/usr/bin/env python
    
    import urllib2
    import threading
    
    class MyHandler(urllib2.HTTPHandler):
        def http_response(self, req, response):
            print "url: %s" % (response.geturl(),)
            print "info: %s" % (response.info(),)
            for l in response:
                print l
            return response
    
    o = urllib2.build_opener(MyHandler())
    t = threading.Thread(target=o.open, args=('http://www.google.com/',))
    t.start()
    print "I'm asynchronous!"
    
    t.join()
    
    print "I've ended!"
    

提交回复
热议问题