跳转至

第四章:异步 IO

aiohttp

安装

pip install aiohttp

异步 HTTP 请求

import aiohttp
import asyncio

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    html = await fetch('https://example.com')
    print(html)

asyncio.run(main())

并发请求

async def fetch_all(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_one(session, url) for url in urls]
        return await asyncio.gather(*tasks)

async def fetch_one(session, url):
    async with session.get(url) as response:
        return await response.text()

# 使用
urls = ['https://example.com/1', 'https://example.com/2']
results = asyncio.run(fetch_all(urls))

httpx

安装

pip install httpx

异步请求

import httpx
import asyncio

async def fetch(url):
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        return response.text

asyncio.run(fetch('https://example.com'))

小结

异步 IO 要点:

  • aiohttp:异步 HTTP 客户端
  • 并发请求:asyncio.gather
  • httpx:现代 HTTP 客户端

下一章我们将学习异步数据库。