Created
September 3, 2019 22:00
-
-
Save koladev32/40189599febe78a0b654f13706378ae7 to your computer and use it in GitHub Desktop.
Introduction to asynchronous programming with python Part 1 : asyncio your code
This file contains hidden or 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 | |
| url_req ='https://www.prevision-meteo.ch/services/json/' | |
| async def get_temp(city:str): | |
| """Get the temperature of the city given in params""" | |
| print(f"Request for {city}.") | |
| s = time.perf_counter() | |
| async with aiohttp.ClientSession() as session: | |
| async with session.get(url=url_req+city.lower()) as r: | |
| temp = await r.json() | |
| elapsed = time.perf_counter() - s | |
| print(f"Response is now ready {elapsed:0.2f} seconds.\nTemperature at {city} : {temp.get('current_condition')['tmp']} C.") | |
| async def main(): | |
| await asyncio.gather(get_temp('Paris'),get_temp('Toulouse'),get_temp('Marseille')) | |
| if __name__ == "__main__": | |
| import time | |
| s = time.perf_counter() | |
| asyncio.run(main()) | |
| elapsed = time.perf_counter() - s | |
| print(f"Program executed in {elapsed:0.2f} seconds.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment