Created
July 28, 2014 21:44
-
-
Save Tafkas/fe7dc920b288fc5d5b45 to your computer and use it in GitHub Desktop.
Fetch current weather from openweathermap api and save it to a sqlite database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlite3 | |
import json | |
import urllib | |
import datetime | |
import calendar | |
WEATHER_DATA_URL = 'http://api.openweathermap.org/data/2.5/weather?q=Berlin,de&units=metric' | |
DB_PATH = '' | |
def get_data(): | |
"""get weather data from openweathermap""" | |
response = urllib.urlopen(WEATHER_DATA_URL) | |
data = json.loads(response.read()) | |
print data | |
temp = data['main']['temp'] | |
pressure = data['main']['pressure'] | |
temp_min = data['main']['temp_min'] | |
temp_max = data['main']['temp_max'] | |
humidity = data['main']['humidity'] | |
wind_speed = data['wind']['speed'] | |
try: | |
wind_gust = data['wind']['gust'] | |
except KeyError: | |
wind_gust = None | |
wind_deg = data['wind']['deg'] | |
clouds = data['clouds']['all'] | |
try: | |
rain = data['rain']['3h'] | |
except KeyError: | |
rain = None | |
try: | |
snow = data['snow']['3h'] | |
except KeyError: | |
snow = None | |
weather_id = data['weather'][0]['id'] | |
sunrise = data['sys']['sunrise'] | |
sunset = data['sys']['sunset'] | |
return [temp, pressure, temp_min, temp_max, humidity, wind_speed, wind_gust, wind_deg, clouds, rain, snow, | |
weather_id, sunrise, sunset] | |
def save_data_to_db(data): | |
con = sqlite3.connect(DB_PATH) | |
con.isolation_level = None | |
cur = con.cursor() | |
query = '''INSERT INTO weather_data VALUES (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''' | |
cur.execute(query, tuple([datetime.datetime.now().isoformat()] + data[:-2])) | |
con.commit() | |
con.close() | |
def main(): | |
data = get_data() | |
now = calendar.timegm(datetime.datetime.now().timetuple()) | |
#only save data after sunrise and before sunset | |
if data[-2] < now < data[-1]: | |
save_data_to_db(data) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment