/asyncio_task_ensure_future.py Secret
Created
October 4, 2020 16:17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import aiohttp | |
from asyncio import Future | |
async def get_api(client, url, future): | |
async with client.get(url) as response: | |
result = await response.json() | |
future.set_result("Article title :- " + result['title']) | |
async def fetch_hacker_news(): | |
async with aiohttp.ClientSession() as session: | |
url = f"https://hacker-news.firebaseio.com/v0/item/24661271.json?print=pretty" | |
future = Future() | |
task1 = get_api(session, url, future) | |
asyncio.ensure_future(task1) #scheduled task1 on event loop | |
result = await asyncio.ensure_future(future) #waiting for future to be marked as done | |
print(result) | |
asyncio.run(fetch_hacker_news()) | |
"""Output: | |
Article title :- Privacy is the most important concept of our time | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment