-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload_to_database.py
76 lines (62 loc) · 2.17 KB
/
upload_to_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
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
71
72
73
74
75
76
import requests
import mysql.connector
import json
import os
def load_configs(c):
d = {}
for key, value in c.items():
if type(value) == str and value.startswith('$'):
d[key] = os.environ.get(value[1:])
elif type(value) == str and \
(value.startswith('i$') or value.startswith('I$')):
d[key] = int(os.environ.get(value[2:]))
elif type(value) == dict:
d[key] = load_configs(value)
else:
d[key] = value
return d
with open('configs.json') as file:
configs = json.load(file)
configs = load_configs(configs)
def main():
if 'flask' in configs.keys() and 'port' in configs['flask'].keys():
http_port = configs['flask']['port']
else:
http_port = 5000
r = requests.get(f'http://localhost:{http_port}/api/current_reading')
rj = r.json()
try:
bme280_temperature = rj['bme280']['temperature']
bme280_humidity = rj['bme280']['humidity']
bme280_pressure = rj['bme280']['pressure']
except Exception:
bme280_temperature = None
bme280_humidity = None
bme280_pressure = None
try:
ds18b20_temperature = rj['ds18b20']['temperature']
except Exception:
ds18b20_temperature = None
try:
pms5003_pm_1_0 = rj['pms5003']['pm1.0']
pms5003_pm_2_5 = rj['pms5003']['pm2.5']
pms5003_pm_10 = rj['pms5003']['pm10']
except Exception:
pms5003_pm_1_0 = None
pms5003_pm_2_5 = None
pms5003_pm_10 = None
db = mysql.connector.connect(**configs['mysql'])
cursor = db.cursor()
sql = 'INSERT INTO readings (bme280_temperature, bme280_humidity, bme280_pressure, ds18b20_temperature, pms5003_pm_1_0, pms5003_pm_2_5, pms5003_pm_10) VALUES (%s, %s, %s, %s, %s, %s, %s)'
cursor.execute(sql, (bme280_temperature,
bme280_humidity,
bme280_pressure,
ds18b20_temperature,
pms5003_pm_1_0,
pms5003_pm_2_5,
pms5003_pm_10))
db.commit()
cursor.close()
db.close()
if __name__ == '__main__':
main()