-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathputDataAPI.py
More file actions
83 lines (72 loc) · 2.14 KB
/
Copy pathputDataAPI.py
File metadata and controls
83 lines (72 loc) · 2.14 KB
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
77
78
79
80
81
82
83
#!/usr/bin/python
# Copyright (c) 2017 Logicc Systems Ltd.
# Author: Andre Neto
import time
import subprocess
import os
import requests
import settings
import sqlite3
import sys
try:
DB_NAME = settings.DB_NAME
url = settings.URL
api_key = settings.API_KEY
apipost = settings.APIPOST
verbose = settings.VERBOSE
except:
print "Could not read settings"
sys.exit(1)
def postToUrl(key,data):
headers = {'content-type': 'application/x-www-form-urlencoded'}
payload = {"key":api_key,"id":data[0],"datecollected": data[1], "probeid": data[2],"temp": data[3], "type":data[4]}
try:
response = requests.request("POST", url, data=payload, headers=headers)
except Exception, e:
print e
print __name__ + ": error on url post"
# Show additional info for troubleshooting
if verbose:
print "Posted to API : " + str(payload)
print "Response - " + str(response.status_code)
# print response.text
return response.status_code
def postDBData():
try:
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
t = ('measure',)
c.execute('SELECT table_idx FROM read_idx WHERE table_name=?',t)
try :
last_idx = c.fetchone()[0]
except :
last_idx = 0
t = (int(last_idx),)
c.execute('SELECT * FROM measure WHERE idx>?', t)
measures = c.fetchall()
c.close()
conn.close()
except Exception, e:
print e
print __name__ + ": Could not read from DB"
return
post = ''
lastIdx = None
for mm in measures:
post = postToUrl(api_key,mm)
if post == 200 :
lastIdx = mm[0]
else :
break
time.sleep(1)
try:
if (len(measures)>0 and lastIdx is not None):
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute('UPDATE read_idx SET table_idx = ? WHERE table_name = ?',( mm[0],'measure'))
conn.commit()
c.close()
conn.close()
except Exception, e:
print e
print __name__ + ": Could not close connection to DB"