2017-10-12 11:14:23 +00:00
|
|
|
import cgi
|
|
|
|
import datetime
|
2017-10-12 11:59:10 +00:00
|
|
|
import configparser
|
2017-10-12 11:14:23 +00:00
|
|
|
|
|
|
|
import pymysql
|
|
|
|
|
2017-10-12 11:59:10 +00:00
|
|
|
def getDatabase(path = "config.cfg"):
|
|
|
|
config = configparser.RawConfigParser()
|
|
|
|
config.read(path)
|
|
|
|
|
|
|
|
host = config.get("Database", "host")
|
|
|
|
user = config.get("Database", "user")
|
|
|
|
pwd = config.get("Database", "pass")
|
|
|
|
name = config.get("Database", "name")
|
|
|
|
|
|
|
|
conn = pymysql.connect(host, user, pwd, name)
|
|
|
|
cur = conn.cursor()
|
|
|
|
|
|
|
|
return conn, cur
|
|
|
|
|
2017-10-12 11:14:23 +00:00
|
|
|
def application(env, re):
|
|
|
|
if env["REQUEST_METHOD"] == "POST":
|
|
|
|
args = cgi.parse_qs(env['wsgi.input'].readline().decode(), True)
|
|
|
|
elif env["REQUEST_METHOD"] == "GET":
|
|
|
|
args = cgi.parse_qs(env['QUERY_STRING'], True)
|
|
|
|
else:
|
|
|
|
re("405 Method Not Allowed", [])
|
|
|
|
return
|
|
|
|
|
|
|
|
if env["PATH_INFO"] == "/endpoint":
|
|
|
|
try:
|
|
|
|
device = args["device"][0]
|
|
|
|
except:
|
|
|
|
re("400 Bad Request", [])
|
|
|
|
yield "<h1>400 Bad Request</h1>".encode()
|
|
|
|
yield "device is required.".encode()
|
|
|
|
|
|
|
|
try:
|
|
|
|
latitude = float(args["lat"][0].replace(",", "."))
|
|
|
|
longitude = float(args["lon"][0].replace(",", "."))
|
|
|
|
except Exception as e:
|
|
|
|
re("400 Bad Request", [])
|
|
|
|
yield "<h1>400 Bad Request</h1>".encode()
|
|
|
|
yield "lat and lon are required.".encode()
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
altitude = float(args["alt"][0].replace(",", "."))
|
|
|
|
except:
|
|
|
|
altitude = None
|
|
|
|
|
|
|
|
try:
|
|
|
|
timestamp = datetime.datetime.fromtimestamp(float(args["t"][0]) / 1000)
|
|
|
|
except:
|
|
|
|
timestamp = datetime.datetime.now()
|
|
|
|
|
|
|
|
timestr = timestamp.strftime('%Y-%m-%d %H:%M:%S')
|
|
|
|
|
2017-10-12 11:59:10 +00:00
|
|
|
conn, cur = getDatabase()
|
|
|
|
sql = "INSERT INTO tracker(ts, device, lat, lon, alt) VALUES (%s, %s, %s, %s, %s);"
|
|
|
|
|
|
|
|
cur.execute(sql, (timestr, device, str(latitude), str(longitude), str(altitude) if altitude != None else None))
|
|
|
|
conn.commit()
|
2017-10-12 11:14:23 +00:00
|
|
|
|