Skip to content

Instantly share code, notes, and snippets.

@lalitsingh24x7
Created August 22, 2024 18:34
Show Gist options
  • Select an option

  • Save lalitsingh24x7/7c42bbe5ba61f83ec1f8122f3795dc42 to your computer and use it in GitHub Desktop.

Select an option

Save lalitsingh24x7/7c42bbe5ba61f83ec1f8122f3795dc42 to your computer and use it in GitHub Desktop.
asyncio
import asyncio
# 1: Coroutines:
"""
Coroutines are functions that can pause and resume their execution.
They are defined using the async def syntax. To call a coroutine, you use await.
"""
async def my_coroutine():
print("Hello")
await asyncio.sleep(1)
print("World")
# 2: Event Loop:
"""
The event loop is the core of the asyncio module. It runs in the background, executing tasks and handling I/O events.
You can get the event loop using asyncio.get_event_loop() and run it using loop.run_until_complete().
"""
loop = asyncio.get_event_loop()
loop.run_until_complete(my_coroutine())
# 3: Tasks:
"""
Tasks are used to schedule coroutines concurrently.
When you create a task, it gets scheduled by the event loop and runs as soon as possible.
"""
async def my_task():
print("Task started")
await asyncio.sleep(2)
print("Task finished")
asyncio.run(my_task())
# 4: Futures:
"""
A Future is an object that represents a result of an operation that hasn’t
completed yet. It is used lower-level in the asyncio module.
"""
# 5: Async/Await Syntax:
"""
async defines a coroutine, and await is used to pause the coroutine until the awaited task is complete.
"""
async def say_hello():
await asyncio.sleep(1)
print("Hello")
asyncio.run(say_hello())
# 6: Running Multiple Coroutines:
"""
You can run multiple coroutines concurrently using asyncio.gather() or asyncio.create_task().
"""
async def task1():
await asyncio.sleep(1)
print("Task 1 complete")
async def task2():
await asyncio.sleep(2)
print("Task 2 complete")
asyncio.run(asyncio.gather(task1(), task2()))
# 7: Example: Fetching Data Asynchronously
"""
Here’s an example of using asyncio to fetch data from multiple URLs concurrently:
"""
import asyncio
import aiohttp
async def fetch_url(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = ['http://example.com', 'http://example.org', 'http://example.net']
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
for result in results:
print(result)
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment