205 lines
6.0 KiB
Python
205 lines
6.0 KiB
Python
from datetime import date
|
|
from datetime import datetime
|
|
from flask import Flask
|
|
from flask import render_template, make_response
|
|
from flask import request, redirect, g
|
|
from flask import url_for
|
|
from flask_sqlalchemy import SQLAlchemy
|
|
import uuid
|
|
import hashlib
|
|
import time
|
|
from functools import wraps
|
|
|
|
from flask_wtf import Form
|
|
from wtforms import DateField, IntegerField, DecimalField
|
|
from wtforms.validators import DataRequired
|
|
|
|
app = Flask(__name__)
|
|
DATABASE = '/data/rollerverbrauch.db'
|
|
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+DATABASE
|
|
sqldb = SQLAlchemy(app)
|
|
|
|
DEBUG = True
|
|
SECRET_KEY = 'development key'
|
|
app.config.from_object(__name__)
|
|
|
|
|
|
class User(sqldb.Model):
|
|
id = sqldb.Column(sqldb.Integer, primary_key=True)
|
|
username = sqldb.Column(sqldb.String(80), unique=True)
|
|
email = sqldb.Column(sqldb.String(120), unique=True)
|
|
salt = sqldb.Column(sqldb.String(8))
|
|
password_hash = sqldb.Column(sqldb.String(64))
|
|
|
|
def __init__(self, username, email, password):
|
|
self.username = username
|
|
self.email = email
|
|
self.salt = uuid.uuid4().hex
|
|
m = hashlib.sha256(password.encode('utf-8'))
|
|
m = hashlib.sha256((m.hexdigest() + self.salt).encode('utf-8')).hexdigest()
|
|
self.password_hash = m
|
|
pass
|
|
|
|
def __repr__(self):
|
|
return '<User %r>' % self.username
|
|
|
|
|
|
class Pitstop(sqldb.Model):
|
|
id = sqldb.Column(sqldb.Integer, primary_key=True)
|
|
date = sqldb.Column(sqldb.Date)
|
|
odometer = sqldb.Column(sqldb.Integer)
|
|
litres = sqldb.Column(sqldb.Numeric(5,2))
|
|
|
|
def __init__(self, odometer, litres, date):
|
|
self.odometer = odometer
|
|
self.litres = litres
|
|
self.date = date
|
|
|
|
def __repr__(self):
|
|
return '<Pitstop %r km, %r l>' % (self.odometer, self.litres)
|
|
|
|
sqldb.create_all()
|
|
if User.query.filter_by(username='jlusiardi').first() is None:
|
|
user1 = User('jlusiardi', 'joachim@lusiardi.de', 'pitstops')
|
|
sqldb.session.add(user1)
|
|
sqldb.session.commit()
|
|
|
|
|
|
def check_auth(username, password):
|
|
user = User.query.filter_by(username=username).first()
|
|
if user is None:
|
|
return False
|
|
salt = user.salt
|
|
m = hashlib.sha256(password.encode('utf-8'))
|
|
m = hashlib.sha256((m.hexdigest()+salt).encode('utf-8'))
|
|
digest = m.hexdigest()
|
|
ok = (User.query.filter_by(username=username, password_hash=digest).first() is not None)
|
|
if not ok:
|
|
app.logger.error("digest: " + digest)
|
|
return ok
|
|
|
|
|
|
def authenticate():
|
|
resp = make_response(render_template('login_required.html'), 401)
|
|
resp.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
|
|
return resp
|
|
|
|
|
|
def requires_auth(f):
|
|
@wraps(f)
|
|
def decorated(*args, **kwargs):
|
|
auth = request.authorization
|
|
if not auth or not check_auth(auth.username, auth.password):
|
|
return authenticate()
|
|
return f(*args, **kwargs)
|
|
return decorated
|
|
|
|
|
|
@app.before_request
|
|
def before_request():
|
|
g.data = {}
|
|
|
|
|
|
@app.teardown_request
|
|
def teardown_request(exception):
|
|
pass
|
|
|
|
|
|
@app.route('/')
|
|
@requires_auth
|
|
def index():
|
|
return redirect(url_for('get_pit_stops'))
|
|
|
|
class CreatePitstopForm(Form):
|
|
date = DateField('Date of Pitstop')
|
|
odometer = IntegerField('Odometer (km)')
|
|
litres = DecimalField('Litres (l)', places=1)
|
|
|
|
|
|
@app.route('/pitstops/createForm', methods=['GET', 'POST'])
|
|
@requires_auth
|
|
def create_pit_stop_form():
|
|
form = CreatePitstopForm()
|
|
if form.validate_on_submit():
|
|
new_stop = Pitstop(form.odometer.data, form.litres.data, form.date.data)
|
|
sqldb.session.add(new_stop)
|
|
sqldb.session.commit()
|
|
return redirect(url_for('get_pit_stops'))
|
|
|
|
last_pitstop = Pitstop.query.order_by(Pitstop.date.desc()).first()
|
|
if last_pitstop is None:
|
|
last_pitstop = Pitstop(0, 0, None)
|
|
|
|
# dynamically set values
|
|
form.odometer.default = last_pitstop.odometer
|
|
form.litres.default = last_pitstop.litres
|
|
form.date.default = datetime.now()
|
|
form.process()
|
|
return render_template('newPitStopForm.html', form=form)
|
|
|
|
|
|
@app.route('/pitstops', methods=['GET'])
|
|
@requires_auth
|
|
def get_pit_stops():
|
|
data = prepare_pit_stops(Pitstop.query.all())
|
|
g.data['pitstops'] = data
|
|
return render_template('pitstops.html', data=g.data)
|
|
|
|
|
|
@app.route('/manual', methods=['GET'])
|
|
@requires_auth
|
|
def get_manual():
|
|
return render_template('manual.html', data=g.data)
|
|
|
|
|
|
@app.route('/statistics', methods=['GET'])
|
|
@requires_auth
|
|
def get_statistics():
|
|
pitstops = Pitstop.query.all()
|
|
count = len(pitstops)
|
|
distance = 0
|
|
sum_litres = 0
|
|
average_distance = 0
|
|
average_litres_fuelled = 0
|
|
average_litres_used = 0
|
|
|
|
if count > 0:
|
|
sum_litres = 0
|
|
for pitstop in pitstops:
|
|
sum_litres += pitstop.litres
|
|
average_litres_fuelled = sum_litres/count
|
|
if count > 1:
|
|
distance = pitstops[-1].odometer - pitstops[0].odometer
|
|
average_distance = distance/(count - 1)
|
|
average_litres_used = 100 * (sum_litres-pitstops[0].litres)/distance
|
|
g.data['distance'] = distance
|
|
g.data['count'] = count
|
|
g.data['litres'] = sum_litres
|
|
g.data['averageDistance'] = average_distance
|
|
g.data['averageListresFuelled'] = average_litres_fuelled
|
|
g.data['averageListresUsed'] = average_litres_used
|
|
return render_template('statistics.html', data=g.data)
|
|
|
|
|
|
def prepare_pit_stops(pss):
|
|
pitstops = []
|
|
for pitstop_index in range(0, len(pss)):
|
|
p = dict()
|
|
p['odometer'] = pss[pitstop_index].odometer
|
|
p['litres'] = pss[pitstop_index].litres
|
|
p['date'] = pss[pitstop_index].date
|
|
pitstops.append(p)
|
|
for pitstop_index in range(1, len(pitstops)):
|
|
last = pitstops[pitstop_index - 1]
|
|
curr = pitstops[pitstop_index]
|
|
curr['distance'] = curr['odometer'] - last['odometer']
|
|
curr['average'] = 100 * curr['litres']/curr['distance']
|
|
last_date = last['date']
|
|
curr_date = curr['date']
|
|
curr['days'] = (curr_date - last_date).days
|
|
pitstops.reverse()
|
|
return pitstops
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True, host='0.0.0.0')
|