Created
August 12, 2022 20:37
-
-
Save djotaku/8ced4e6c1c482a41c645720a09db1c10 to your computer and use it in GitHub Desktop.
async comparisons
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
# async version 1 | |
import asyncio | |
import httpx | |
async def get_weather(city: str, state: str) -> dict: | |
url = f"https://weather.talkpython.fm/api/weather?city={city}&state={state}&country=US&units=imperial" | |
async with httpx.AsyncClient() as client: | |
response = await client.get(url, follow_redirects=True) | |
return response.json() | |
async def main(): | |
city_state = [("Portland", "OR"), ("Seattle", "WA"), ("La Jolla", "CA"), ("Phoenix", "AZ"), ("New York", "NY"), | |
("Boston", "MA")] | |
for combo in city_state: | |
print(await get_weather(combo[0], combo[1])) | |
if __name__ == '__main__': | |
loop = asyncio.new_event_loop() | |
loop.run_until_complete(main()) | |
###################### async version 2 ############################ | |
import asyncio | |
import httpx | |
async def get_weather(city: str, state: str) -> dict: | |
url = f"https://weather.talkpython.fm/api/weather?city={city}&state={state}&country=US&units=imperial" | |
async with httpx.AsyncClient() as client: | |
response = await client.get(url, follow_redirects=True) | |
return response.json() | |
async def main(): | |
city_state = [("Portland", "OR"), ("Seattle", "WA"), ("La Jolla", "CA"), ("Phoenix", "AZ"), ("New York", "NY"), | |
("Boston", "MA")] | |
work = [] | |
for city, state in city_state: | |
work.append(asyncio.create_task(get_weather(city, state))) | |
print([await task for task in work]) | |
if __name__ == '__main__': | |
loop = asyncio.new_event_loop() | |
loop.run_until_complete(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment