lorawan/web-to-db.py

55 lines
1.4 KiB
Python
Raw Normal View History

2016-09-16 15:20:11 +00:00
#!/usr/bin/env python3
2016-09-16 15:29:57 +00:00
import urllib
2016-09-16 15:43:00 +00:00
import psycopg2
2016-09-16 15:20:11 +00:00
from http.server import BaseHTTPRequestHandler, HTTPServer
2016-09-16 15:43:00 +00:00
2016-09-16 15:20:11 +00:00
# HTTPRequestHandler class
class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):
2016-09-16 15:29:15 +00:00
# not used, just a sample
def do_GET(self):
# Send response status code
2016-09-16 15:20:11 +00:00
self.send_response(200)
# Send headers
self.send_header('Content-type','text/html')
self.end_headers()
# Send message back to client
message = "Hello world!"
# Write content as utf-8 data
self.wfile.write(bytes(message, "utf8"))
return
2016-09-16 15:26:08 +00:00
def do_POST(self):
length = int(self.headers['Content-Length'])
2016-09-16 16:10:33 +00:00
post_data = self.rfile.read(length).decode('utf-8')
2016-09-16 15:43:00 +00:00
# Print on stdout
2016-09-16 15:26:08 +00:00
print(post_data)
2016-09-16 15:20:11 +00:00
2016-09-16 15:43:00 +00:00
# And insert into the db
self.insert_xml(post_data)
2016-09-16 15:44:05 +00:00
def insert_xml(self, data):
2016-09-16 15:43:00 +00:00
try:
conn = psycopg2.connect("dbname=hackzurich")
2016-09-16 16:01:45 +00:00
cursor = conn.cursor()
2016-09-16 16:17:58 +00:00
cursor.execute("insert into data (packet) values (%s)", (data, ))
2016-09-16 16:27:44 +00:00
cursor.connection.commit()
2016-09-16 16:01:45 +00:00
conn.close()
2016-09-16 15:43:00 +00:00
except Exception as e:
print("DB Insert failed: %s" % e)
2016-09-16 15:20:11 +00:00
if __name__ == '__main__':
2016-09-16 15:28:23 +00:00
server_address = ('0.0.0.0', 8000)
httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
print('running server...')
httpd.serve_forever()