Async/Warten in Python

Pythons Async/Await für gleichzeitige Programmierung mit Asyncio verstehen

Async/Warten in Python

Die asynchrone Programmierung ermöglicht die gleichzeitige Ausführung ohne Threads, ideal für E/A-gebundene Aufgaben.

Grundkonzepte

import asyncio

async def fetch_data() -> str:
    await asyncio.sleep(1)  # Simulates I/O
    return "data"

async def main():
    result = await fetch_data()
    print(result)

asyncio.run(main())

Aufgaben gleichzeitig ausführen

async def main():
    # Sequential - takes 3 seconds
    a = await fetch_data()
    b = await fetch_data()
    c = await fetch_data()

    # Concurrent - takes 1 second
    a, b, c = await asyncio.gather(
        fetch_data(),
        fetch_data(),
        fetch_data()
    )

Beispiel aus der Praxis: HTTP-Anfragen

import aiohttp
import asyncio

async def fetch_url(session: aiohttp.ClientSession, url: str) -> str:
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = [
        "https://api.example.com/users",
        "https://api.example.com/posts",
        "https://api.example.com/comments",
    ]

    async with aiohttp.ClientSession() as session:
        results = await asyncio.gather(
            *[fetch_url(session, url) for url in urls]
        )

    for result in results:
        print(len(result))

asyncio.run(main())

Wann sollte Async verwendet werden?

Gut für: - HTTP-Anfragen - Datenbankabfragen - Datei-E/A - WebSockets

Nicht ideal für: - CPU-gebundene Aufgaben (verwenden Sie multiprocessing) - Einfache Skripte mit minimalem I/O