Sunday, May 10, 2020

Weather data from openweathermap.org

Sharing my python code to pull data from OpenWeatherMap.  As of this writing, API access is free for some data.  Below is a sample to get the data and display it.

Here is a sample of the output produced by the script below:

07:14 PM
Feels Like: 35.7°F
Outside Temp: 48.6°F
Weather Look: Rain
Weather Desc: moderate rain
Humidity: 87%
Wind Speed: 20.80 mph
Wind Degree: 270°

In the code below, the city code: 5391959 is for San Francisco, CA.  You can modify your city search as needed.  The API documentation will show you how.

In the script, I'm using configparser to store critical data like the API Key.  An example of the file's content:

[openweathermap]
apiKey=439d4b804bc8187953eb36d2a8c26a02

The source for openweather.py is seen below and is available for download too:

<--- Begin Code --->

#!/usr/bin/python3

import sys, os, time, json, configparser, datetime, signal
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

def signal_handler (signal, frame):
    sys.exit(0)

def openweather():

    # Read Config parameters
    config = configparser.ConfigParser()
    config.read('/home/config.ini')
    apiKey = config['openweathermap']['apiKey']
    
    base_url = "https://api.openweathermap.org/data/2.5/weather?"
    complete_url = base_url + 'id=5391959&appid=' + apiKey
    response = requests.get(complete_url)
    if response.status_code == 200:
        return response.json()
    else:
        print(response.text)
        sys.exit(2)

def main():

    response = openweather()
    outtemp = float((response['main']['temp']-273.15)*9/5+32)
    feeltemp = float((response['main']['feels_like']-273.15)*9/5+32)
    outtemp = str("{0:.1f}".format(outtemp))
    feeltemp = str("{0:.1f}".format(feeltemp))
    weather_main = response['weather'][0]['main']
    weather_desc = response['weather'][0]['description']
    humidity = response['main']['humidity']
    wind_speed = float(response['wind']['speed'])
    wind_mph = format(wind_speed*2.2369363, '.2f')
    wind_deg = response['wind']['deg']
    currenttime = datetime.datetime.now()
    print(currenttime.strftime("%I:%M %p"))
    print("Feels Like: "+str(feeltemp)+u'\u00b0' + "F")
    print("Outside Temp: "+str(outtemp)+u'\u00b0' + "F")
    print("Weather Look: "+str(weather_main))
    print("Weather Desc: "+str(weather_desc))
    print("Humidity: "+str(humidity)+"%")
    print("Wind Speed: "+str(wind_mph)+" mph")
    print("Wind Degree: "+str(wind_deg)+u'\u00b0')

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal_handler)
    while True:
        main()
        time.sleep(30)

<--- End Code --->