python - 使用 python3 的异步 http 请求

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

有人能帮忙吗?

最佳答案

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

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)

关于python - 使用 python3 的异步 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25197108/

相关文章:

http - 重定向返回 http : multiple response. WriteHeader 调用

android - 发送 HttpPost 请求时出现 SocketTimeOutException

python - 如何在python中对具有特殊日期结构的DataFrame进行排序?

iphone - 服务器不接受我的多部分/表单数据

python - 在 pandas 中添加行终止符最终会添加另一个\r

python - 终止使用 'subprocess.run' 创建的进程

python - DRF 中的 request.data 与 DRF 中的 serializers.data

Python 请求.exceptions.SSLError : EOF occurred in violation of protocol

python - 如何使用 Matplotlib 创建折线图

python - 如何在 Google App Engine 上读取 Excel 文件