Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)41k · #6755

async-python-patterns

Skill này làm gì

Công cụ này giúp tạo các chương trình Python nhanh và hiệu quả hơn. Chương trình có thể làm nhiều việc cùng lúc mà không bị treo, đặc biệt khi cần chờ điều gì đó (như dữ liệu từ internet).

Khi nào nên dùng

  • ✓Khi bạn xây dựng website hoặc ứng dụng cần phản hồi nhanh.
  • ✓Khi bạn tải nhiều thông tin từ internet cùng lúc.
  • ✓Khi bạn muốn chương trình chờ một việc mà không làm dừng mọi thứ khác.

Liên kết skill

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/async-python-patterns/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/async-python-patterns/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để chương trình Python của tôi tải nhiều trang web cùng một lúc?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Công cụ dùng một “event loop” để quản lý các tác vụ. Khi một tác vụ cần chờ, vòng lặp chuyển sang tác vụ khác. Các từ khóa `async` và `await` giúp tổ chức các lần tạm dừng và tiếp tục này.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Async Python Patterns

Comprehensive guidance for implementing asynchronous Python applications using asyncio, concurrent programming patterns, and async/await for building high-performance, non-blocking systems.

When to Use This Skill

  • Building async web APIs (FastAPI, aiohttp, Sanic)
  • Implementing concurrent I/O operations (database, file, network)
  • Creating web scrapers with concurrent requests
  • Developing real-time applications (WebSocket servers, chat systems)
  • Processing multiple independent tasks simultaneously
  • Building microservices with async communication
  • Optimizing I/O-bound workloads
  • Implementing async background tasks and queues

Sync vs Async Decision Guide

Before adopting async, consider whether it's the right choice for your use case.

Use Case Recommended Approach
Many concurrent network/DB calls asyncio
CPU-bound computation multiprocessing or thread pool
Mixed I/O + CPU Offload CPU work with asyncio.to_thread()
Simple scripts, few connections Sync (simpler, easier to debug)
Web APIs with high concurrency Async frameworks (FastAPI, aiohttp)

Key Rule: Stay fully sync or fully async within a call path. Mixing creates hidden blocking and complexity.

Core Concepts

1. Event Loop

The event loop is the heart of asyncio, managing and scheduling asynchronous tasks.

Key characteristics:

  • Single-threaded cooperative multitasking
  • Schedules coroutines for execution
  • Handles I/O operations without blocking
  • Manages callbacks and futures

2. Coroutines

Functions defined with async def that can be paused and resumed.

Syntax:

async def my_coroutine():
    result = await some_async_operation()
    return result

3. Tasks

Scheduled coroutines that run concurrently on the event loop.

4. Futures

Low-level objects representing eventual results of async operations.

5. Async Context Managers

Resources that support async with for proper cleanup.

6. Async Iterators

Objects that support async for for iterating over async data sources.

Quick Start

import asyncio

async def main():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

# Python 3.7+
asyncio.run(main())

Fundamental Patterns

Pattern 1: Basic Async/Await

import asyncio

async def fetch_data(url: str) -> dict:
    """Fetch data from URL asynchronously."""
    await asyncio.sleep(1)  # Simulate I/O
    return {"url": url, "data": "result"}

async def main():
    result = await fetch_data("https://api.example.com")
    print(result)

asyncio.run(main())

Pattern 2: Concurrent Execution with gather()

import asyncio
from typing import List

async def fetch_user(user_id: int) -> dict:
    """Fetch user data."""
    await asyncio.sleep(0.5)
    return {"id": user_id, "name": f"User {user_id}"}

async def fetch_all_users(user_ids: List[int]) -> List[dict]:
    """Fetch multiple users concurrently."""
    tasks = [fetch_user(uid) for uid in user_ids]
    results = await asyncio.gather(*tasks)
    return results

async def main():
    user_ids = [1, 2, 3, 4, 5]
    users = await fetch_all_users(user_ids)
    print(f"Fetched {len(users)} users")

asyncio.run(main())

Pattern 3: Task Creation and Management

import asyncio

async def background_task(name: str, delay: int):
    """Long-running background task."""
    print(f"{name} started")
    await asyncio.sleep(delay)
    print(f"{name} completed")
    return f"Result from {name}"

async def main():
    # Create tasks
    task1 = asyncio.create_task(background_task("Task 1", 2))
    task2 = asyncio.create_task(background_task("Task 2", 1))

    # Do other work
    print("Main: doing other work")
    await asyncio.sleep(0.5)

    # Wait for tasks
    result1 = await task1
    result2 = await task2

    print(f"Results: {result1}, {result2}")

asyncio.run(main())

Pattern 4: Error Handling in Async Code

import asyncio
from typing import List, Optional

async def risky_operation(item_id: int) -> dict:
    """Operation that might fail."""
    await asyncio.sleep(0.1)
    if item_id % 3 == 0:
        raise ValueError(f"Item {item_id} failed")
    return {"id": item_id, "status": "success"}

async def safe_operation(item_id: int) -> Optional[dict]:
    """Wrapper with error handling."""
    try:
        return await risky_operation(item_id)

…
Câu hỏi thường gặp

Khác nhau giữa “sync” và “async” là gì?

“Sync” (đồng bộ) giống như con đường một làn: mỗi lần chỉ một xe. “Async” (bất đồng bộ) giống như đường cao tốc nhiều làn: các xe có thể cùng di chuyển, và một số có thể chờ ngắn mà không chặn các xe khác.

“Coroutine” là gì?

Đó là một hàm Python đặc biệt (đánh dấu bằng `async def`) có thể tạm dừng và tiếp tục, cho phép chương trình làm việc khác trong khi chờ.

Khi nào KHÔNG nên dùng “async”?

Nếu chương trình tính toán nặng (thay vì chờ mạng hoặc ổ đĩa), dùng “async” có thể không giúp ích và thậm chí làm mọi thứ phức tạp hơn. Trong trường hợp đó, các kỹ thuật khác có thể phù hợp hơn.

Chi tiết

Mô tả gốc của tác giả

Master Python asyncio, concurrent programming, and async/await patterns for high-performance applications. Use when building async APIs, concurrent systems, or I/O-bound applications requiring non-blocking operations.

repo: wshobson/agents

Độ phổ biến

Sao GitHub
41k
Vị trí xếp hạng
#6755
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự