Open weather maps python

How to use the OpenWeatherMap API with Python

In this article we’ll explore the powerful OpenWeatherMap API, which allows you to access and use weather data in your programs. It can be used to display information such as the temperature, wind, and humidity, for the current weather and for the forecasted weather. We’ll use the Python programming language and an awesome library called Python OpenWeatherMap (PyOWM) to make it easier to use the OpenWeatherMap API in Python. This article is based on an interactive course I released on Next XYZ. The course has Python and the PyOWM library preinstalled and lets you use both directly from your browser. If you want to learn even more about PyOWM , you can check out the course and get started for free!

Setting Up Your Environment

To run the code snippets in this article you’ll need to have Python and the pyowm library installed (install instructions for pyowm can be found here). Once you have this installed, you can open up a Python shell from your command line (usually using python or python3 , depending on which version of Python you’re using) and use it to run the commands below.

Читайте также:  Setupcomp ru activator html

Getting your OpenWeatherMap API Key

Once you have your environment setup, the next step is to get your free API key from the OpenWeatherMap website. After you’ve signed up on OpenWeatherMap’s website, you’ll see this at the top of the page: Click on «API keys» and you’ll see the API key. When you work with the the examples below, you’ll need to replace with this API key.

Weather Conditions

Now that you have your API key, let’s check the weather! First we’ll start by checking if there are any clouds in the five-day forecast for Los Angeles. Here’s the code to do that:

import pyowm owm = pyowm.OWM('') # TODO: Replace with your API key la = owm.three_hours_forecast('Los Angeles, US') print(la.will_have_clouds()) 

Let’s break this down. We start by importing the pyowm library, then we authenticate using an API key. The authenticated connection to the API is stored in the owm variable. Next we use the three_hours_forecast() method to get the forecast for a specified location (in this case, Los Angeles) and store it in the la variable. Note that the three_hours_forecast() method returns a five-day forecast with weather data sampled every three hours. Now that we have the weather object, we can call the will_have_clouds() method on it to check if there will be clouds! Within the pyowm library, this will check the weather at each three-hour interval and if any weather sample indicates there will be clouds, the method will return true, otherwise it will return false. We can also use PyOWM to see if it will rain, be foggy, or check for other common weather conditions. OpenWeatherMap has data from all around the world as well. For example, let’s take a look at the weather in London:

import pyowm owm = pyowm.OWM('') # TODO: Replace with your API key london = owm.three_hours_forecast('London, GB') print(london.will_have_rain()) print(london.will_have_fog()) 

Awesome! With just a few lines of code you can get and display some amazing information in your program.

Читайте также:  Как шифровать пароли php

Current Temperature

import pyowm owm = pyowm.OWM('') # TODO: Replace with your API key sf = owm.weather_at_place('San Francisco, US') weather = sf.get_weather() print(weather.get_temperature('fahrenheit')['temp']) 

As you might guess from the use of ‘fahrenheit’ in the above code, you can also request the data in Celsius by passing ‘celsius’ to the get_temperature() method.

Sunrise and Sunset Times

Another cool thing you can do with PyOWM is request and display the sunrise and sunset times. The get_sunrise_time() and get_sunset_time() methods can be called to get this info. There is a catch when using these methods though- they return the time in unix time by default (e.g., 1542800608). Passing the timeformat=’iso’ parameter converts the time to a more human-readable format (e.g., 2018–11–21 21:16:54+00). Also, the times are in the GMT timezone (in the Next XYZ course we cover how to convert the times to a specific timezone). Here’s an example of getting the sunrise and sunset times:

 import pyowm owm = pyowm.OWM('') # TODO: Replace with your API key boston = owm.weather_at_place('Boston, US') weather = boston.get_weather() print(weather.get_sunrise_time(timeformat='iso')) # Prints time in GMT timezone print(weather.get_sunset_time(timeformat='iso')) # Prints time in GMT timezone 

Wrapping Up

If you enjoyed this post and want to learn more about using Python OpenWeatherMap to access weather data, check out the course on Next XYZ, which goes more in-depth into how to use PyOWM. It also includes interactive tasks and quizzes which will help you master the material in the course. By the end of it you’ll have created a weather GUI just like the image below! Have any questions or comments? Just leave a note below! Thanks for reading, and happy coding!

Источник

PyOWM

PyOWM is a client Python wrapper library for OpenWeatherMap (OWM) web APIs. It allows quick and easy consumption of OWM data from Python applications via a simple object model and in a human-friendly fashion.

Former Dark Sky API users: you can can use PyOWM to get OpenWeatherMap’s OneCall API data as an easy replacement to Dark Sky

What kind of data can I get with PyOWM ?

With PyOWM you can integrate into your code any of the following OpenWeatherMap web APIs:

  • Weather API v2.5 + OneCall API, providing current weather data, weather forecasts, weather history
  • Agro API v1.0, providing soil data and satellite imagery search and download
  • Air Pollution API v3.0, providing data about CO, O3, NO2 and SO2
  • UV Index API v3.0, providing data about Ultraviolet exposition
  • Stations API v3.0, allowing to create and manage meteostation and publish local weather measurements
  • Weather Alerts API v3.0, allowing to set triggers on weather conditions and areas and poll for spawned alerts
  • Image tiles for several map layers provided by OWM
  • Geocoding API v1.0 allowing to perform direct/reverse geocoding

In case of trouble.

Please read the FAQ before filing a new issue on GitHub! There are many common issues, therefore a fix for your issue might come easier than you think

Get started

API key

As OpenWeatherMap APIs need a valid API key to allow responses, PyOWM won’t work if you don’t provide one. This stands for both free and paid (pro) subscription plans. You can signup for a free API key on the OWM website Please notice that the free API subscription plan is subject to requests throttling.

Example

         Install with pip for your ease:

There are alternatives: setuptools, Windows installers and common Linux package managers such as Yaourt (Arch Linux) YaST/Zypper (OpenSuse) (please refer to the documentation for more detail)

Eager to fetch the very latest updates to PyOWM? Install the development trunk (which might be unstable). Eg on Linux:

$ git clone https://github.com/csparpa/pyowm.git $  pyowm  git checkout develop $ pip install -r requirements.txt  python setup.py install

Documentation

The library software API documentation is available on Read the Docs.

The Code recipes section comes in handy!

Community & Contributing

Join the PyOWM public Slack team by signing up here

Contributors (coding, testing, packaging, reporting issues) are welcome! See the the official documentation website for details or the CONTRIBUTING.md file for a quick primer.

Источник

Узнаем текущую погоду и прогноз простеньким скриптом на 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.

Источник

Оцените статью