异步编程在 Python 开发中变得越来越重要。 随着 asyncio
现在成为标准库组件和许多兼容的第三方包,这种范例将继续存在。本教程演示如何使用 HTTPX
库进行异步 HTTP 请求 - 非阻塞代码的主要用例。
“异步”、“非阻塞”和“并发”等术语可能会令人困惑。 本质上:
异步代码避免阻塞,使其他代码能够在等待结果时运行。 asyncio
库为此提供了工具,并且 aiohttp
提供了专门的 HTTP 请求功能。 HTTP 请求非常适合异步性,因为它们涉及等待服务器响应,在此期间其他任务可以有效执行。
确保您的 Python 环境已配置。 如果需要,请参阅虚拟环境指南(需要 Python 3.7)。 安装HTTPX
:
pip install httpx==0.18.2
此示例使用对 Pokémon API 的单个 GET 请求来获取 Mew(Pokémon #151)的数据:
import asyncio import httpx async def main(): url = 'https://pokeapi.co/api/v2/pokemon/151' async with httpx.AsyncClient() as client: response = await client.get(url) pokemon = response.json() print(pokemon['name']) asyncio.run(main())
async
指定一个协程; await
产生对事件循环的控制,在结果可用时恢复执行。
当发出大量请求时,异步性的真正力量是显而易见的。此示例获取前 150 个 Pokémon 的数据:
import asyncio import httpx import time start_time = time.time() async def main(): async with httpx.AsyncClient() as client: for number in range(1, 151): url = f'https://pokeapi.co/api/v2/pokemon/{number}' response = await client.get(url) pokemon = response.json() print(pokemon['name']) asyncio.run(main()) print(f"--- {time.time() - start_time:.2f} seconds ---")
执行的时间。 将此与同步方法进行比较。
同步等效项:
import httpx import time start_time = time.time() client = httpx.Client() for number in range(1, 151): url = f'https://pokeapi.co/api/v2/pokemon/{number}' response = client.get(url) pokemon = response.json() print(pokemon['name']) print(f"--- {time.time() - start_time:.2f} seconds ---")
注意运行时差异。 HTTPX
的连接池最大限度地减少了差异,但 asyncio 提供了进一步的优化。
为了获得卓越的性能,请使用 asyncio.ensure_future
和 asyncio.gather
同时运行请求:
import asyncio import httpx import time start_time = time.time() async def fetch_pokemon(client, url): response = await client.get(url) return response.json()['name'] async def main(): async with httpx.AsyncClient() as client: tasks = [asyncio.ensure_future(fetch_pokemon(client, f'https://pokeapi.co/api/v2/pokemon/{number}')) for number in range(1, 151)] pokemon_names = await asyncio.gather(*tasks) for name in pokemon_names: print(name) asyncio.run(main()) print(f"--- {time.time() - start_time:.2f} seconds ---")
这通过并发运行请求显着减少了执行时间。 总时间接近最长单次请求的持续时间。
使用 HTTPX
和异步编程可以显着提高多个 HTTP 请求的性能。本教程提供了 asyncio
的基本介绍;进一步探索其功能以增强您的 Python 项目。 考虑探索 aiohttp
来替代异步 HTTP 请求处理。
以上是Python 中使用 HTTPX 和 asyncio 的异步 HTTP 请求的详细内容。更多信息请关注PHP中文网其他相关文章!