Skip to content

Instantly share code, notes, and snippets.

@gnilchee
Last active February 10, 2017 04:46
Show Gist options
  • Save gnilchee/8fb1a99e4c6930668e33793a825c06e8 to your computer and use it in GitHub Desktop.
Save gnilchee/8fb1a99e4c6930668e33793a825c06e8 to your computer and use it in GitHub Desktop.
Get Current Conditions by Zip Code. You need an openweathermap api key.
#!/usr/bin/env python3
import requests
import sys
from configparser import ConfigParser
class WeatherAPI:
def get_current_conditions(zip_code):
# Try and read in api key from default config
try:
config = ConfigParser()
config.read('weatherman.conf')
APP_ID = config['openweathermap']['api']
except Exception:
get_api_key = input('Please Provide OpenWeatherMap API Key: ')
config['openweathermap'] = {'api': get_api_key}
with open('weatherman.conf', 'w') as configfile:
config.write(configfile)
finally:
APP_ID = config['openweathermap']['api']
# Building weather_url
weather_url='http://api.openweathermap.org/data/2.5/weather?zip={},us&appid={}&units=imperial'.format(zip_code, APP_ID)
# Making a request to openweathermap
req = requests.get(weather_url)
# Bailing out if there are any non 200 OK responses
if req.status_code != 200:
print("Oh no, something went wrong. Got response {}".format(req.status_code))
sys.exit(1)
# Grabbing Temperature and dropping decimal without rounding
res_temp = str(req.json()['main']['temp']).split('.', 1)[0]
# Collecting multiple (if they exist) conditions into res_cond variable
res_main = req.json()['weather']
str_cond = ''
for cur in res_main:
str_cond += cur['main'] + '/'
res_cond = str_cond.rstrip('/')
# Grabing place from JSON Response
res_place = str(req.json()['name'])
# Building current conditions return
curr_cond = 'Current Conditions: {}°F {} in {}'.format(res_temp, res_cond, res_place)
# Returning curr_cond variable
return curr_cond
if __name__ == '__main__':
zip_code = int(input('Enter Zip Code: '))
currently = WeatherAPI.get_current_conditions(zip_code)
print(currently)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment