使用python3异步http请求

时间:2014-08-08 06:16:17

标签: python http python-3.x asynchronous

有没有办法像node.js一样制作异步python3?

我想要一个最小的例子,我已尝试过以下内容,但仍然可以使用同步模式。

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')应首先显示。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

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

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)