示例#1
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
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
async def get_report_async(city: str, state: Optional[str], country: str,
                           units: str) -> dict:
    """
    Function responsible for getting the weather report.
    It looks at the cashed info first, if found, results are returned, if not, an API call is made.
    :param city: str, name of the city.
    :param state: (str - optional), name of the state.
    :param country: str, name of the country.
    :param units: str, unit system to use.
    :return: dict, weather forecast.
    """

    # Validate the provided parameters
    city, state, country, units = validate_units(city, state, country, units)

    # If forecast available in cache, return it.
    if forecast := weather_cache.get_weather(city, state, country, units):
        return forecast
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)

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