rasolar/pyweb.py

100 lines
2.3 KiB
Python
Raw Normal View History

2019-07-31 05:48:24 -07:00
from bottle import get,post,request,Bottle,run,template
import threading,time,json,zlib,gnupg,socket,psutil
2019-07-31 03:30:42 -07:00
from queue import Queue
2019-07-30 22:19:30 -07:00
measdata={}
2019-07-31 03:30:42 -07:00
_HASH="hash"
_SIGNEDGPG="signed_gpg"
_PAYLOAD="payload"
_MEASURES="measure"
_BEGINSIGNATURE="-----BEGIN PGP SIGNATURE-----"
_BEGINMESSAGE="-----BEGIN PGP SIGNED MESSAGE-----"
_BEGINHASH="Hash:"
2019-07-30 22:19:30 -07:00
def sql_insert(q):
while True:
if q.empty():
time.sleep(0.1)
2019-07-31 05:48:24 -07:00
print("ping"+str(time.time()))
2019-07-30 22:19:30 -07:00
else:
try:
indata=q.get()
if indata is not None:
q.task_done()
except Exception as e:
print("Error during queuing")
print(e)
else:
print("Queue:")
print(indata)
if indata['hash'] in measdata:
for i in indata['payload']['measures']:
measdata[indata['hash']]['measures'][i]=indata['payload']['measures'][i]
else:
measdata[indata['hash']]=indata['payload']
print(measdata)
app=Bottle()
@app.get('/')
def approot():
2019-07-31 05:48:24 -07:00
return template('main.tpl',server=socket.gethostname(),cpupercent=psutil.cpu_percent(),measdata=measdata)
2019-07-30 22:19:30 -07:00
@app.post('/data/<hash_id:int>')
def dataimport(hash_id):
print(hash_id)
2019-07-31 03:30:42 -07:00
timestart=time.time()
2019-07-30 22:19:30 -07:00
try:
2019-07-31 03:30:42 -07:00
json_in=json.loads(request.json)
print(json_in)
2019-07-30 22:19:30 -07:00
except:
print("no json")
else:
2019-07-31 03:30:42 -07:00
if _HASH in json_in:
if int(json_in[_HASH]) == hash_id:
print("correct id")
2019-07-30 22:19:30 -07:00
bcorrect=False
2019-07-31 03:30:42 -07:00
if _PAYLOAD in json_in:
if _MEASURES in json_in[_PAYLOAD]:
q.put(json_in,block=False)
2019-07-30 22:19:30 -07:00
bcorrect=True
2019-07-31 03:30:42 -07:00
if _SIGNEDGPG in json_in:
if gpg.verify(json_in[_SIGNEDGPG]):
signed_in=json_in[_SIGNEDGPG].split("\n")
signed_in[signed_in.index(_BEGINSIGNATURE):]=""
del signed_in[signed_in.index(_BEGINMESSAGE)]
del signed_in[signed_in.index("")]
for h in signed_in:
if _BEGINHASH in h:
del signed_in[signed_in.index(h)]
if len(signed_in)>0:
print(time.time()-timestart)
q.put(json.loads(signed_in[0]),block=False)
else:
print("malformed signed packet")
print(json_in)
else:
print("could not verify gpg signature")
print(json_in)
2019-07-30 22:19:30 -07:00
else:
print("wrong id")
else:
print("json has no hash field")
2019-07-31 03:30:42 -07:00
print(json_in)
2019-07-30 22:19:30 -07:00
2019-07-31 03:30:42 -07:00
gpg=gnupg.GPG()
2019-07-30 22:19:30 -07:00
q=Queue(maxsize=0)
sql_worker=threading.Thread(target=sql_insert,args=(q,))
sql_worker.setDaemon(True)
sql_worker.start()
run(app,host="localhost",port=8080)