Yazılım Geliştirme
1 dakika okuma
Python Asyncio ile Asenkron Programlama
Python asyncio ile asenkron programlama: coroutine, event loop, gather ve real-world ornekler.
E
Emre Cihan Asyncio Neden
IO-bound islemlerde (ag, disk) thread kullanmak yerine asyncio ile tek thread'de binlerce eszamanli islem yapilabilir.
Temel Coroutine
import asyncio
async def selamla(isim: str, bekleme: float) -> str:
await asyncio.sleep(bekleme)
return f'Merhaba, {isim}!'
async def main():
sonuc = await selamla('Emre', 1.0)
print(sonuc)
asyncio.run(main())
Paralel Islemler
async def main():
# Sirayla: 3 saniye
# await selamla('A', 1)
# await selamla('B', 2)
# Paralel: 2 saniye (en uzun kadar)
sonuclar = await asyncio.gather(
selamla('A', 1),
selamla('B', 2),
selamla('C', 0.5),
)
print(sonuclar)
HTTP Istekleri
import aiohttp
import asyncio
async def url_getir(session: aiohttp.ClientSession, url: str) -> dict:
async with session.get(url) as yanit:
return {'url': url, 'durum': yanit.status, 'boyut': len(await yanit.text())}
async def main():
urls = [
'https://httpbin.org/delay/1',
'https://httpbin.org/delay/2',
'https://httpbin.org/get',
]
async with aiohttp.ClientSession() as session:
gorevler = [url_getir(session, u) for u in urls]
sonuclar = await asyncio.gather(*gorevler)
for s in sonuclar:
print(f"{s['url']}: {s['durum']} ({s['boyut']} byte)")
asyncio.run(main())
Timeout ve Hata Yonetimi
async def guvenli_getir(url: str) -> str | None:
try:
async with asyncio.timeout(5.0):
async with aiohttp.ClientSession() as s:
async with s.get(url) as r:
return await r.text()
except asyncio.TimeoutError:
print(f'Timeout: {url}')
return None
except Exception as e:
print(f'Hata: {e}')
return None
asyncio, Python'da yuksek performansli IO islemleri icin guclu bir araçtir.
Paylaş:
Twitter / X
E
Emre Cihan
Sistem Yöneticisi · Maker · Elektronik Meraklısı
İlgili yazılar