async def get_current_weather(city: str, province: Optional[str], country: str,
                              units: str) -> dict:
    city, province, country, units = validate_units(city, province, country,
                                                    units)

    forecast = weather_cache.get_weather(city, province, country, units)
    if forecast:
        return forecast

    if province:
        q = f'{city},{province},{country}'
    else:
        q = f'{city},{country}'

    url = f'https://api.openweathermap.org/data/2.5/weather?q={q}&appid={api_key}&units={units}'

    async with httpx.AsyncClient() as client:
        resp: Response = await client.get(url)
        if resp.status_code != 200:
            raise ValidationError(resp.text, status_code=resp.status_code)

    data = resp.json()
    current_weather = data['main']

    weather_cache.set_weather(city, province, country, units, current_weather)
    return current_weather
Exemple #2
0
async def get_report_async(city: str, state: Optional[str], country: str,
                           units: str) -> dict:

    city, state, country, units = validate_units(city, state, country, units)

    forecast = weather_cache.get_weather(city, state, country, units)

    if forecast:
        return forecast

    if state:
        q = f"{city}, {state}, {country}"
    else:
        q = f"{city}, {country}"

    url = f"https://api.openweathermap.org/data/2.5/weather?q={q}&appid={api_key}&units={units}"

    async with httpx.AsyncClient() as client:
        resp: httpx.Response = await client.get(url)

        if resp.status_code != 200:
            raise ValidationError(resp.text, status_code=resp.status_code)

    data = resp.json()
    print(data)
    forecast = data['main']

    weather_cache.set_weather(city, state, country, units, forecast)

    return forecast
    if state:
        q = f'{city},{state},{country}'
    else:
        q = f'{city},{country}'

    url = f'https://api.openweathermap.org/data/2.5/weather?q={q}&appid={api_key}&units={units}'

    async with httpx.AsyncClient() as client:
        resp: Response = await client.get(url)
        if resp.status_code != 200:
            raise ValidationError(resp.text, status_code=resp.status_code)

    data = resp.json()
    forecast = data['main']

    weather_cache.set_weather(city, state, country, units, forecast)

    return forecast


def validate_units(city: str, state: Optional[str], country: Optional[str], units: str) -> \
        Tuple[str, Optional[str], str, str]:
    city = city.lower().strip()
    if not country:
        country = "us"
    else:
        country = country.lower().strip()

    if len(country) != 2:
        error = f"Invalid country: {country}. It must be a two letter abbreviation such as US or GB."
        raise ValidationError(status_code=400, error_msg=error)