rollerverbrauch/app/main.py

161 lines
5.3 KiB
Python
Raw Normal View History

2015-03-06 21:58:53 +01:00
import sqlite3
from datetime import datetime
from flask import Flask
from flask import render_template
from flask import url_for
from flask import request, redirect, g
from contextlib import closing
2015-03-07 09:51:38 +01:00
import os, os.path
2015-03-06 21:58:53 +01:00
app = Flask(__name__)
2015-03-09 20:06:17 +01:00
DATABASE = '../rollerverbrauch.db'
2015-03-06 21:58:53 +01:00
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
app.config.from_object(__name__)
def connect_db():
result = sqlite3.connect(app.config['DATABASE'])
return result
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql', mode='r') as f:
2015-03-07 09:51:38 +01:00
sql_commands = f.read()
print(sql_commands)
db.cursor().executescript(sql_commands)
2015-03-06 21:58:53 +01:00
db.commit()
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()
@app.route('/')
def index():
#data = {'pitstopsUrl': url_for('getPitStops')}
#return render_template('index.html', data=data)
return redirect(url_for('getPitStops'))
@app.route('/pitstops', methods=['POST'])
def createPitStop():
2015-03-09 20:06:17 +01:00
last_pitstop = getLastPitStop()
errorMsg = {}
2015-03-06 21:58:53 +01:00
date = request.form['date']
2015-03-09 20:06:17 +01:00
try:
date = datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m-%d')
except ValueError:
errorMsg['date'] = 'invalid date, only YYYY-MM-DD is allowed'
date = request.form['date']
2015-03-06 21:58:53 +01:00
odometer = request.form['odometer']
2015-03-09 20:06:17 +01:00
try:
odometer = int(odometer)
except ValueError:
errorMsg['odometer'] = 'Illegal Value, only Integers allowed'
odometer = None
if odometer is not None and odometer <= last_pitstop['odometer']:
errorMsg['odometer'] = 'Illegal Value, new Value must be bigger as given value'
odometer = request.form['odometer']
if odometer is None:
odometer = request.form['odometer']
2015-03-06 21:58:53 +01:00
litres = request.form['litres']
2015-03-09 20:06:17 +01:00
try:
litres = float(litres)
except ValueError:
errorMsg['litres'] = 'Illegal Value, only floating point allowed'
litres = None
if litres is not None and litres <= 0:
errorMsg['litres'] = 'Litres must not be 0'
litres = request.form['litres']
if litres is None:
litres = request.form['litres']
2015-03-06 21:58:53 +01:00
# error checking here
2015-03-09 20:06:17 +01:00
if len(errorMsg) > 0:
data = {'last': {'date': date, 'odometer': odometer, 'litres': litres}, 'error': errorMsg}
return render_template('newPitStopForm.html', data=data)
2015-03-06 21:58:53 +01:00
addPitStop(date, odometer, litres)
return redirect(url_for('getPitStops'))
@app.route('/pitstops/createForm', methods=['GET'])
def createPitStopForm():
data = {'last':getLastPitStop(), 'error': None}
return render_template('newPitStopForm.html', data=data)
@app.route('/pitstops', methods=['GET'])
def getPitStops():
data = {'pitstops': preparePitStops(getAllPitStops())}
return render_template('pitstops.html', data=data)
2015-03-07 09:51:38 +01:00
@app.route('/statistics', methods=['GET'])
def getStatistics():
pitstops = getAllPitStops()
count = len(pitstops)
distance = 0
sumLitres = 0
averageDistance = 0
averageLitresFuelled = 0
averageLitresUsed = 0
2015-03-09 20:06:17 +01:00
if count > 0:
2015-03-07 09:51:38 +01:00
sumLitres = 0
for pitstop in pitstops:
sumLitres += pitstop['litres']
averageLitresFuelled = round(sumLitres/count, 2)
2015-03-09 20:06:17 +01:00
if count > 1:
2015-03-07 09:51:38 +01:00
distance = pitstops[-1]['odometer'] - pitstops[0]['odometer']
averageDistance = round(distance/(count - 1), 2)
averageLitresUsed = round(100 * (sumLitres-pitstops[0]['litres'])/distance, 2)
data = {
'distance':distance,
'count': count,
'litres': round(sumLitres, 2),
'averageDistance': averageDistance,
'averageListresFuelled': averageLitresFuelled,
'averageListresUsed': averageLitresUsed}
return render_template('statistics.html', data=data)
2015-03-06 21:58:53 +01:00
def preparePitStops(pitstops):
for index in range(1, len(pitstops)):
last = pitstops[index - 1]
curr = pitstops[index]
curr['distance'] = curr['odometer'] - last['odometer']
curr['average'] = round(100 * curr['litres']/curr['distance'], 2)
last_date = datetime.strptime(last['date'], '%Y-%m-%d')
curr_date = datetime.strptime(curr['date'], '%Y-%m-%d')
curr['days'] = (curr_date - last_date).days
return pitstops
def getLastPitStop():
cur = g.db.execute('select date, odometer, litres from pitstops order by date desc limit 1')
pitstops = [dict(date=row[0], odometer=row[1], litres=row[2]) for row in cur.fetchall()]
if len(pitstops) == 0:
return {'date': datetime.strftime(datetime.now(), '%Y-%m-%d'), 'odometer': 0, 'litres': 0}
return pitstops[0]
def getAllPitStops():
cur = g.db.execute('select date, odometer, litres from pitstops order by id asc')
pitstops = [dict(date=row[0], odometer=row[1], litres=row[2]) for row in cur.fetchall()]
return pitstops
def addPitStop(date, odometer, litres):
g.db.execute('insert into pitstops (date, odometer, litres) values (?, ?, ?)', [date, odometer, litres])
g.db.commit()
if __name__ == '__main__':
2015-03-07 09:51:38 +01:00
if not os.path.isfile(DATABASE) or os.stat(DATABASE).st_size == 0:
init_db()
2015-03-06 21:58:53 +01:00
app.run(debug=True, host='0.0.0.0')