kebab-collector/app.py
2020-09-24 17:09:02 +02:00

73 lines
1.9 KiB
Python

from flask import Flask, render_template, request, abort
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
import os
import json
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI', "sqlite://")
db = SQLAlchemy(app)
KEY = os.environ['KEBAB_KEY']
class ResultRecord(db.Model):
id = db.Column(db.Integer, primary_key=True, auto_increment=True)
score = db.Column(db.Integer, unique=False, nullable=False)
content = db.Column(db.Text)
class Workers(db.Model):
id = db.Column(db.Integer, primary_key=True, auto_increment=True)
ipaddr = db.Column(db.String, unique=True, nullable=False)
last_seen = db.Column(db.TIMESTAMP, nullable=False, server_default=func.now())
@app.before_first_request
def create_db():
db.create_all()
@app.route(f'/result/{KEY}', methods=['POST'])
def save_result():
result = request.get_json()
if not result:
abort(400)
if not isinstance(result, list):
abort(400)
rr = ResultRecord(content=json.dumps(result), score=len(result))
db.session.add(rr)
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip = request.remote_addr
w = Workers.query.filter_by(ipaddr=ip).first()
if not w:
w = Workers(ipaddr=ip)
else:
w.last_seen = datetime.now()
db.session.add(w)
db.session.commit()
return "stored", 200
@app.route(f'/result/{KEY}', methods=['GET'])
def get_result():
best_result = ResultRecord.query.filter(ResultRecord.score == func.min(ResultRecord.score).select()).first_or_404()
res_count = ResultRecord.query.count()
workers = Workers.query.all()
best_result_content = json.loads(best_result.content)
return render_template('report.html', best_result=best_result_content, result_count=res_count, workers=workers)
if __name__ == '__main__':
app.run()