Free weather api python

Узнаем текущую погоду и прогноз простеньким скриптом на Python’е

На Хабре есть интересная статья о том, как энтузиасты делают погоду. Энтузиасты делают, а мы воспользуемся плодами их трудов — получим эту самую погоду от OpenWeatherMap.org скриптом на Python’е.

Для получения доступа к сервису погоды придется пройти несложную процедуру регистрации на сайте OpenWeatherMap.org. Сформируем и отправим запрос, разберем ответный пакет в формате JSON, и получим текущую температуру с описанием состояния погоды.

Зарегистрироваться на openweathermap.org совсем несложно, а остальное сделать будет ещё проще.

Регистрация нужна для получения идентифицирующей пользователя строки App Id, состоящей из набора букв и цифр (похоже — только из шестнадцатеричных цифр). Такого вида:
«6d8e495ca73d5bbc1d6bf8ebd52c4». После регистрации нужно зайти в личный кабинет и взять App Id, который там называется «API key».

Формирование строки запроса

Сначала попытаемся найти интересующий нас город в их базе. Строка запроса должна быть примерно такая:

http://api.openweathermap.org/data/2.5/find?q=Petersburg&type=like&APPID=6d8e495ca73d5bbc1d6bf8ebd52c4

В запросе нужно указать нужный город (вместо «Petersburg») и свой App Id (вместо «6d8e495ca73d5bbc1d6bf8ebd52c4». Можно уточнить запрос, указав идентификатор страны после названия города через запятую. Например, так:

http://api.openweathermap.org/data/2.5/find?q=Petersburg,RU&type=like&APPID=6d8e495ca73d5bbc1d6bf8ebd52c4

Собственно запросная строка будет сформирована самой библиотекой requests в функции get, которую используем для отправки запроса:

requests.get("http://api.openweathermap.org/data/2.5/find", params=) 

Проверка наличия в базе информации о нужном населенном пункте

План такой. В ответ на сформированный запрос получаем пакет в формате JSON. Разбираем пакет и получаем нужные значения по названиям полей.

import requests s_city = "Petersburg,RU" city_id = 0 appid = "буквенно-цифровой APPID" try: res = requests.get("http://api.openweathermap.org/data/2.5/find", params=) data = res.json() cities = ["<> (<>)".format(d['name'], d['sys']['country']) for d in data['list']] print("city:", cities) city_id = data['list'][0]['id'] print('city_id=', city_id) except Exception as e: print("Exception (find):", e) pass 

Запомним числовой идентификатор города city_id для последующего запроса, потому что поставщики сервиса рекомендовали делать запрос не по имени, а по идентификатору.
В ответе может оказаться несколько городов, соответствующих нашему запросу. Кстати, если в запросе указать “Moscow” и убрать страну из строки приведенного в примере запроса, то гарантированно получим несколько строк в списке cities:

Получение информации о текущей погоде

Осталось только получить искомую информацию о погоде. Если нас не интересуют имперские единицы измерения, то в запросе указываем, что желаем получить метрические единицы: «units=metric». Если описание погоды нужно получить на русском, то указываем «lang=ru».

try: res = requests.get("http://api.openweathermap.org/data/2.5/weather", params=) data = res.json() print("conditions:", data['weather'][0]['description']) print("temp:", data['main']['temp']) print("temp_min:", data['main']['temp_min']) print("temp_max:", data['main']['temp_max']) except Exception as e: print("Exception (weather):", e) pass 

Прогноз на 5 дней

 try: res = requests.get("http://api.openweathermap.org/data/2.5/forecast", params=) data = res.json() for i in data['list']: print( i['dt_txt'], ''.format(i['main']['temp']), i['weather'][0]['description'] ) except Exception as e: print("Exception (forecast):", e) pass 

Получим такой вывод:
2016-11-24 15:00 -1 7 м/с ЮЗ пасмурно
2016-11-24 18:00 +2 7 м/с З легкий дождь
2016-11-24 21:00 +2 7 м/с З легкий дождь
2016-11-25 00:00 -0 7 м/с З ясно
2016-11-25 03:00 +0 7 м/с З небольшой снегопад
2016-11-25 06:00 -0 6 м/с СЗ слегка облачно
.

Скачать owm-request.py. Чтобы этот скрипт заработал, нужно в первой строке ввести Ваш «API key», полученный при регистрации на OpenWeatherMap.org.
Командная строка, например, такая:
$python owm-request.py Moscow,RU

На сайте OpenWeatherMap есть ещё масса интересного — получение информации по географическим координатам, архив погоды, информация с конкретных метеостанций. Описание всех доступных сервисов можно посмотреть здесь http://openweathermap.org/api
Для работы на Python’е с OpenWeatherMap существует специализированная библиотека pyowm.

Помимо OpenWeatherMap есть другие сайты, предоставляющие аналогичную информацию. Например, WorldWeatherOnline. Доступные API можно посмотреть здесь. Регистрация нужна. Есть библиотека на Python’е: pywwo.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A free and asynchronous weather API wrapper made in python, for python.

License

null8626/python-weather

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A free and asynchronous weather Python API wrapper made in Python, for Python.

$ pip install python-weather
# import the module import python_weather import asyncio import os async def getweather(): # declare the client. the measuring unit used defaults to the metric system (celcius, km/h, etc.) async with python_weather.Client(unit=python_weather.IMPERIAL) as client: # fetch a weather forecast from a city weather = await client.get('New York') # returns the current day's forecast temperature (int) print(weather.current.temperature) # get the weather forecast for a few days for forecast in weather.forecasts: print(forecast) # hourly forecasts for hourly in forecast.hourly: print(f' --> hourly!r>') if __name__ == '__main__': # see https://stackoverflow.com/questions/45600579/asyncio-event-loop-is-closed-when-getting-loop # for more details if os.name == 'nt': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) asyncio.run(getweather())

About

A free and asynchronous weather API wrapper made in python, for python.

Источник

Why design —> matters to our lives ? —> How To Generate Realtime Weather Data With Python How To Generate Realtime Weather Data With Python

This post will show you how to fetch and generate live weather data in Python. I’ll also show you how to use WeatherAPI to supplement the data.

Last Updated: December 29, 2022

This is an example description for this item.

This post will show you how to fetch and generate live weather data of any city in Python using a weather API. We are going to make use of the weather api from www.weatherapi.com . WeatherAPI is a service that provides weather data, including realtime weather data, forecasts, and historical data to the developers of web services and mobile applications.

Before using their API, you have to signup for a free account and generate an api key here. You will need the API key for accessing their service.

We will use the python Requests module for accessing the API.

Install the requests module by running:

Fetching live weather data

Before we make the request, first we will create these variables:

  1. base_url , which stores the API’s URL
  2. api_key, stores your api key
  3. city, the city whose weather data we need.
import requests api_key = "your_API_key" base_url = "http://api.weatherapi.com/v1" city = "london" parameters = # URL parameters r = requests.get(f"/current.json", params=parameters) data = r.json() # retrieve the json data print(data)
, 'current': , 'wind_mph': 8.1, 'wind_kph': 13.0, 'wind_degree': 200, 'wind_dir': 'SSW', 'pressure_mb': 1011.0, 'pressure_in': 30.3, 'precip_mm': 0.1, 'precip_in': 0.0, 'humidity': 82, 'cloud': 75, 'feelslike_c': 11.9, 'feelslike_f': 53.5, 'vis_km': 10.0, 'vis_miles': 6.0, 'uv': 3.0, 'gust_mph': 11.9, 'gust_kph': 19.1>>

Now lets parse this data into a nice piece

import requests api_key = "your_API_key" base_url = "http://api.weatherapi.com/v1" city = "london" parameters = # URL parameters r = requests.get(f"/current.json", params=parameters) data = r.json() # retrieve json # retriving Data location = data['location']['name'] time = data['location']['localtime'] condition = data['current']['condition']['text'] temperature_celcius = data['current']['temp_c'] temperature_farenheit = data['current']['temp_f'] feelslike_celcius = data['current']['feelslike_c'] wind_direction = data['current']['wind_dir'] # printing data print(f"Location: ") print(f"Current Time: ") print() print(f"Weather Condition: ") print(f"Temperature in Celcius: ") print(f"Temperature in farenheit: ") print() print(f"Temperature feels like: Celcius") print(f"Wind Direction: ")
Location: London Current Time: 2020-11-25 11:53 Weather Condition: Light rain Temperature in Celcius: 14.0 Temperature in farenheit: 57.2 Temperature feels like: 13.1 Celcius Wind Direction: SSW 

Источник

Читайте также:  Java integral data types
Оцените статью