Python - Example of urllib2 asynchronous / threaded request using HTTPS

前端 未结 5 1366
梦谈多话
梦谈多话 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:29

    The code below does 7 http requests asynchronously at the same time. It does not use threads, instead it uses asynchronous networking with the twisted library.

    from twisted.web import client
    from twisted.internet import reactor, defer
    
    urls = [
     'http://www.python.org', 
     'http://stackoverflow.com', 
     'http://www.twistedmatrix.com', 
     'http://www.google.com',
     'http://launchpad.net',
     'http://github.com',
     'http://bitbucket.org',
    ]
    
    def finish(results):
        for result in results:
            print 'GOT PAGE', len(result), 'bytes'
        reactor.stop()
    
    waiting = [client.getPage(url) for url in urls]
    defer.gatherResults(waiting).addCallback(finish)
    
    reactor.run()
    

提交回复
热议问题