Python Async/Await ile Asenkron Programlama
Python’da async/await ile asenkron programlama, I/O bound işlemlerde performansı önemli ölçüde artırır.
Async/Await Temelleri
import asyncio
async def fetch_data():
print("Fetching data...")
await asyncio.sleep(2) # Simüle edilen I/O
return {"data": "example"}
async def main():
result = await fetch_data()
print(result)
# Çalıştır
asyncio.run(main())
Birden Fazla Task
async def task1():
await asyncio.sleep(1)
return "Task 1 completed"
async def task2():
await asyncio.sleep(2)
return "Task 2 completed"
async def main():
# Paralel çalıştır
results = await asyncio.gather(
task1(),
task2()
)
print(results)
Web Scraping Örneği
import aiohttp
import asyncio
async def fetch_url(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'https://example.com/page1',
'https://example.com/page2',
'https://example.com/page3'
]
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
return results
Async/await ile uygulamalarınızı hızlandırın!