Skip to content

Instantly share code, notes, and snippets.

@djotaku
Created August 12, 2022 20:37
Show Gist options
  • Save djotaku/8ced4e6c1c482a41c645720a09db1c10 to your computer and use it in GitHub Desktop.
Save djotaku/8ced4e6c1c482a41c645720a09db1c10 to your computer and use it in GitHub Desktop.
async comparisons
# 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