Performing asynchronous HTTP requests using aiohttp.
Copy
5. Handling Asynchronous Exceptions
Handling exceptions in asynchronous functions.
Copy
6. Asyncio with Timeouts
Using asyncio.wait_for to apply a timeout to an asynchronous task.
Copy
7. Asyncio Queue for Task Synchronization
Using asyncio.Queue for managing tasks in a producer-consumer model.
Copy
8. Asynchronous File I/O with aiofiles
Performing non-blocking file I/O using aiofiles.
Copy
9. Asynchronous Database Queries with aiomysql
Performing asynchronous MySQL queries using aiomysql.
Copy
10. Asyncio with Custom Event Loop
Running a custom event loop manually instead of using asyncio.run.
Copy
These snippets showcase various ways to handle IO-bound tasks using Python's asyncio module. They cover simple asynchronous function execution, concurrent tasks, timeouts, exception handling, and interaction with external systems like HTTP requests, file I/O, and databases.
import aiohttp
import asyncio
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
data = await fetch_data('https://jsonplaceholder.typicode.com/posts')
print(data[:100]) # Printing only the first 100 characters of the response
asyncio.run(main())
import asyncio
async def might_fail():
print("This might fail...")
await asyncio.sleep(1)
raise ValueError("Something went wrong!")
async def main():
try:
await might_fail()
except ValueError as e:
print(f"Caught an error: {e}")
asyncio.run(main())
import asyncio
async def producer(queue):
for i in range(5):
await asyncio.sleep(1)
await queue.put(i)
print(f"Produced {i}")
async def consumer(queue):
while True:
item = await queue.get()
print(f"Consumed {item}")
queue.task_done()
async def main():
queue = asyncio.Queue()
await asyncio.gather(producer(queue), consumer(queue))
asyncio.run(main())
import aiofiles
import asyncio
async def write_to_file():
async with aiofiles.open('example.txt', mode='w') as file:
await file.write("This is an example of async file I/O.")
async def main():
await write_to_file()
asyncio.run(main())
import asyncio
import aiomysql
async def fetch_data():
async with aiomysql.create_pool(user='user', db='test', host='127.0.0.1', port=3306) as pool:
async with pool.acquire() as conn:
async with conn.cursor() as cursor:
await cursor.execute('SELECT * FROM users')
result = await cursor.fetchall()
print(result)
asyncio.run(fetch_data())
import asyncio
async def custom_loop_task():
print("Task started in custom loop!")
await asyncio.sleep(2)
print("Task finished!")
loop = asyncio.get_event_loop()
loop.run_until_complete(custom_loop_task())
loop.close()