88 lines
2.7 KiB
Python
88 lines
2.7 KiB
Python
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
|
|
|
|
app = Flask(__name__)
|
|
DATABASE = '/tmp/rollerverbrauch.db'
|
|
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
|
|
|
|
@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)
|
|
|
|
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.datetime.strftime(datetime.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__':
|
|
app.run(debug=True) |