import urllib.request, json, datetime,os from urllib.error import URLError, HTTPError import sqlite3 now = datetime.datetime.now() day = now.strftime('%F') time = now.strftime('%H:%M') url = 'https://solar.lowtechmagazine.com/api/stats.json' if not os.path.exists('stats.db'): db = sqlite3.connect('stats.db') c = db.cursor() c.execute("""CREATE TABLE stats(date text, time text, error text, server text) """) db.commit() else: db = sqlite3.connect('stats.db') c = db.cursor() request = urllib.request.Request(url) try: response = urllib.request.urlopen(request) except HTTPError as e: print('The server couldn\'t fulfill the request.') print('Error code: ', e.code) error = e.code server = None pass except URLError as e: print('We failed to reach a server.') print('Reason: ', e.reason) error = e.reason server = None pass else: # everything is fine data = response.read().decode('utf-8') server = data error = None if error: error = error.args[1] c.execute("""INSERT INTO stats VALUES(?,?,?,?)""", (day, time, error, server)) db.commit() db.close()