iot-data/iot_data/__init__.py

60 lines
1.6 KiB
Python

#!/usr/bin/env python3
from flask import Flask, abort, request, make_response
import json
import os
import time
app = Flask(__name__)
values = {}
config = {}
if "IOT_DATA_CONFIG" in os.environ:
config = json.loads(open(os.environ["IOT_DATA_CONFIG"]).read())
# just make the key lookup faster
keys = {}
for name, c in config.items():
if "key" in c:
if c["key"] in keys:
raise Exception("Keys need to be unique")
else:
keys[c["key"]] = name
@app.route("/ingress/<string:key>/", methods=["POST"])
def ingress(key):
if key in keys:
content_type = "text/plain"
if "content-type" in request.headers:
content_type = request.headers["content-type"]
values[keys[key]] = {
"payload": request.data,
"content-type": content_type,
"last-modified": time.time(),
}
else:
return make_response("", 404)
return make_response("", 201)
@app.route("/data/<string:name>/")
def data(name):
if not name in config:
return make_response("", 404)
if name in values:
if "delete-after" in config[name]:
if (values[name]["last-modified"] + config[name]["delete-after"]) < time.time():
values.pop(name)
if not name in values:
return make_response("", 404)
resp = make_response(values[name]["payload"], 200)
resp.headers['Content-Type'] = values[name]["content-type"]
resp.headers['Last-Modified'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(values[name]["last-modified"]))
return resp
if __name__ == "__main__":
app.run(debug=True)