-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenweather.py
70 lines (53 loc) · 2.29 KB
/
openweather.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python3
import requests
import os
# for more details on openweathermap api please refer to https://openweathermap.org/current
OPENWEATHERMAP_URL = 'https://api.openweathermap.org/data/2.5/'
# a valid APPID is needed [Get by creating an openweathermap account (free)]
APPID = os.environ.get('OPENWEATHERMAP_APPID', '')
CITY_ID = os.environ.get('OPENWEATHERMAP_CITY_ID', '')
class Weather:
def __init__(self, condition="", description="", temp=0.0, icon=""):
self.condition = condition
self.description = description
self.temp = temp
self.icon = icon
def apiGet(url):
return requests.get(url)
def getWeather(city_id, appid, weather_mode='weather', units='metric'):
'''
Calls openweathermap url and returns a Weather object.
Valid OPENWEATHERMAP_APPID and OPENWEATHERMAP_CITY_ID
need to be defined as environment variables to get the correct results.
'''
if (appid is None) or (not isinstance(appid, str)):
raise TypeError('appid must be a str')
if units not in ['metric', 'imperial', '']:
raise Exception('units not valid')
# build url
url = '{}{}?id={}&appid={}&units={}'.format(
OPENWEATHERMAP_URL, weather_mode, city_id, appid, units)
# get weather response
resp = apiGet(url)
# return response text if not sucessfull
if resp.status_code != 200:
raise Exception('GET /tasks/ status_code:{}'.format(resp.status_code))
json_resp = resp.json()
weather_condition_resp = ""
weather_description_resp = ""
weather_icon_resp = ""
temp_resp = 0.0
if 'weather' in json_resp:
if len(json_resp['weather']) > 0:
first_weather_elem = json_resp['weather'][0]
weather_condition_resp = first_weather_elem['main']
weather_description_resp = first_weather_elem['description']
weather_icon_resp = first_weather_elem['icon']
if 'main' in json_resp and 'temp' in json_resp['main']:
temp_resp = json_resp['main']['temp']
return Weather(weather_condition_resp, weather_description_resp, temp_resp, weather_icon_resp)
# e.g.
# weather_now = getWeather(city_id=CITY_ID, appid=APPID, units='imperial')
# print(weather_now.condition, weather_now.description, weather_now.temp)
# out:
# Smoke smoke 72.46