rollerverbrauch/app/main.py

128 lines
4.1 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-07 09:51:38 +01:00
DATABASE = '/data/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():
date = request.form['date']
odometer = request.form['odometer']
litres = request.form['litres']
# error checking here
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
count = len(pitstops)
if len(pitstops) > 0:
sumLitres = 0
for pitstop in pitstops:
sumLitres += pitstop['litres']
averageLitresFuelled = round(sumLitres/count, 2)
if len(pitstops) > 1:
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')