使用 python3 进行异步 http 请求

Alf*_*ang 5 python asynchronous http python-3.x

有没有办法像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)
Run Code Online (Sandbox Code Playgroud)

如果异步模式有效,则应print('exit')首先显示 。

有人可以帮忙吗?

Cth*_*lhu 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)
Run Code Online (Sandbox Code Playgroud)