-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatabase.py
45 lines (39 loc) · 1.47 KB
/
database.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
import pymysql
# database credentials
import db_credentials
db_host = db_credentials.hostname
db_user = db_credentials.username
db_pass = db_credentials.password
db_name = 'weather'
# database functions
class Database:
def connect(self, database=db_name):
return pymysql.connect(host=db_host,
user=db_user,
passwd=db_pass,
db=database)
def get_weather_data(self):
connection = self.connect()
try:
query = 'SELECT `when`, temperature, humidity FROM dht order by `when` desc'
with connection.cursor() as cursor:
cursor.execute(query)
data = cursor.fetchone()
current_weather = {'when': data[0], 'temperature': data[1], 'humidity': data[2]}
return current_weather
except Exception as ex:
print ex
return {'when': 'error', 'temperature': 'error', 'humidity': 'error'}
finally:
connection.close()
def rec_weather_data(self, temperature, humidity):
connection = self.connect()
try:
query = 'INSERT INTO dht (`when`, temperature, humidity) VALUES (now(), %s, %s)'
with connection.cursor() as cursor:
cursor.execute(query, (temperature, humidity))
connection.commit()
except Exception as ex:
print ex
finally:
connection.close()