Async python patterns

From findscripter/everything-skills · View interactive version

Async python patterns is an AI agent skill from the GitHub repository findscripter/everything-skills. 当用 asyncio 写 I/O 密集的异步并发(API/爬虫/WebSocket/批量请求/后台队列)时使用;做出带超时、限流、取消与结构化错误处理的 async/await 代码与排错方案;不适用于 CPU 密集任务、同步脚本足够或运行环境无事件循环的场景;触发词:asyncio、async/await、gather、并发请求、协程。

How to use this skill

Skill file

何时使用

不该用的边界:

步骤 / 指令

1. 判定工作负载:I/O 密集才用 asyncio;先确认目标(吞吐/延迟)与运行时约束。
2. 选并发原语并定义取消规则:
   - 入口统一用 asyncio.run(main())(Python 3.7+)。
   - 多任务并发:asyncio.gather(*tasks) 或 asyncio.create_task() + 后续 await。
   - 队列解耦:asyncio.Queue(生产者/消费者)。
   - 资源池/限流:asyncio.Semaphore;连接复用用 aiohttp.TCPConnector。
3. 加固:每个外部调用配 timeout(asyncio.wait_for / ClientTimeout);
   队列设 maxsize 做背压;gather(..., return_exceptions=True) 收集失败而非整体崩。
4. 正确处理取消:捕获 asyncio.CancelledError 做清理后 re-raise,勿吞掉。
5. 隔离阻塞:绝不在协程里调 time.sleep / 阻塞 IO / 重计算;用 await asyncio.sleep
   或 loop.run_in_executor 包装。
6. 测试与调试:用 pytest-asyncio(@pytest.mark.asyncio)覆盖正常/超时/取消路径。

规则:

示例

并发抓取(gather + 超时 + 错误隔离 + 连接池):

import asyncio, aiohttp
from typing import List, Dict

async def fetch(session: aiohttp.ClientSession, url: str) -> Dict:
    try:
        async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as r:
            return {"url": url, "status": r.status, "length": len(await r.text())}
    except Exception as e:
        return {"url": url, "error": str(e)}

async def scrape(urls: List[str]) -> List[Dict]:
    conn = aiohttp.TCPConnector(limit=100, limit_per_host=10)  # 连接池
    async with aiohttp.ClientSession(connector=conn) as session:
        return await asyncio.gather(*(fetch(session, u) for u in urls))

asyncio.run(scrape(["https://httpbin.org/delay/1"]))

信号量限流(控制最大并发):

async def api_call(url, sem: asyncio.Semaphore):
    async with sem:                       # 同时最多 N 个进入
        await asyncio.sleep(0.5)
        return {"url": url, "status": 200}

async def main(urls, max_concurrent=3):
    sem = asyncio.Semaphore(max_concurrent)
    return await asyncio.gather(*(api_call(u, sem) for u in urls))

超时控制:

try:
    result = await asyncio.wait_for(slow_op(5), timeout=2.0)
except asyncio.TimeoutError:
    print("Operation timed out")

把阻塞操作丢进线程池(避免卡事件循环):

import concurrent.futures
async def run_blocking(data):
    loop = asyncio.get_event_loop()
    with concurrent.futures.ThreadPoolExecutor() as pool:
        return await loop.run_in_executor(pool, blocking_operation, data)

正确处理取消:

async def cancelable_task():
    try:
        while True:
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        # 在这里做清理
        raise   # 必须 re-raise 以传播取消

测试(pytest-asyncio):

@pytest.mark.asyncio
async def test_with_timeout():
    with pytest.raises(asyncio.TimeoutError):
        await asyncio.wait_for(slow_op(5), timeout=1.0)

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT 许可)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.