使用Python3进行异步HTTP请求

5

有没有办法使python3的异步操作像node.js一样快速?

我想要一个最小的示例代码,我尝试了以下代码,但仍然在同步模式下工作。

import urllib.request

class MyHandler(urllib.request.HTTPHandler):

    @staticmethod
    def http_response(request, response):
        print(response.code)
        return response

opener = urllib.request.build_opener(MyHandler())
try:
    opener.open('http://www.google.com/')
    print('exit')
except Exception as e:
    print(e)

如果异步模式有效,则应首先显示print('exit')。有人能帮忙吗?

你能为我写一个例子吗? - Alfred Huang
http://www.gevent.org/,这里有一个并发下载的示例https://github.com/surfly/gevent/blob/master/examples/concurrent_download.py。 - nacholibre
1个回答

4

使用线程(基于您自己的代码):

import urllib.request
import threading

class MyHandler(urllib.request.HTTPHandler):
    @staticmethod
    def http_response(request, response):
        print(response.code)
        return response

opener = urllib.request.build_opener(MyHandler())
try:
    thread = threading.Thread(target=opener.open, args=('http://www.google.com',))
    thread.start()      #begin thread execution
    print('exit')

    # other program actions

    thread.join()       #ensure thread in finished before program terminates
except Exception as e:
    print(e)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接