File size: 1,202 Bytes
036b3a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import asyncio, httpx

coordinates = {
    "New York": (40.7128, -74.0060),
#     "Los Angeles": (34.0500, -118.2500),
    "San Francisco": (37.7749, -122.4194),
    "Chicago": (41.8333, -87.6167),
    "Houston": (29.7500, -95.3500),
    "Washington": (38.8833, -77.0333)
}

async def weather(client, city):
    lat,lon = coordinates[city]
    point = (await client.get(f"https://api.weather.gov/points/{lat},{lon}")).json()['properties']
    station_url = point['observationStations']
    stations = (await client.get(station_url)).json()
    first_url = stations['features'][0]['id']
    try:
        obs = (await client.get(f"{first_url}/observations/latest")).json()
        obs = obs['properties']
    except: return city, dict(temp='NA',wind='NA',humid='NA')
    def val(x): return round(x['value'], 1) if x['value'] else 'NA'
    return city, dict(temp=val(obs['temperature']),
                      wind=val(obs['windSpeed']),
                      humid=val(obs['relativeHumidity']))

async def all_weather():
    async with httpx.AsyncClient() as client:
        tasks = [weather(client, city) for city in coordinates]
        results = await asyncio.gather(*tasks)
    return dict(results)