python中的httpx异步请求

HTTPX 是一个 Python 3.6+ 用于异步和同步 HTTP 请求的库。它提供了一个简单、易用的接口,并兼容 requests API。

以下是一个使用 HTTPX 发送异步 GET 请求的示例:

bash 复制代码
import asyncio

import httpx



async def fetch_async(url):

    async with httpx.AsyncClient() as client:

        response = await client.get(url)

        return response.text



async def main():

    url = 'http://httpbin.org/get'

    content = await fetch_async(url)

    print(content)



# 运行事件循环

asyncio.run(main())

在这个例子中,我们定义了一个异步函数 fetch_async,它使用了 HTTPX 的 AsyncClient 来发送异步 GET 请求。然后我们定义了一个 main 函数,它运行异步函数并打印结果。最后,我们使用 asyncio.run 来运行事件循环并启动异步任务。

相关推荐
Python私教1 小时前
Django 接入 AI 大模型实战:从零做一个流式聊天网站
人工智能·python·django
Python私教1 小时前
Django 接入 MCP 实战:让 AI 安全调用数据库和业务接口
人工智能·python·django
Python私教1 小时前
Django 搭建 AI 本地知识库:文档上传、向量检索与智能问答
人工智能·python·django
always_TT1 小时前
【Python 日志记录:logging 模块入门】
开发语言·python·php
lipku4 小时前
数字人直播开源项目LiveStream
python·开源·数字人·数字人直播
阿童木写作4 小时前
Python实现亚马逊商品图批量智能抠图教程
人工智能·python
axinawang4 小时前
第24课:while循环的应用
python
三亚兴嘉装饰5 小时前
三亚服装店装修
python
小柯南敲键盘5 小时前
速卖通AI图片翻译API集成实战
人工智能·python
phltxy5 小时前
多智能体系统架构设计:从单体代理到协作网络
python·langchain·系统架构