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 import os, os.path app = Flask(__name__) DATABASE = '/data/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 def init_db(): with closing(connect_db()) as db: with app.open_resource('schema.sql', mode='r') as f: sql_commands = f.read() print(sql_commands) db.cursor().executescript(sql_commands) 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(): last_pitstop = getLastPitStop() errorMsg = {} date = request.form['date'] 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'] odometer = request.form['odometer'] 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'] litres = request.form['litres'] 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'] # error checking here if len(errorMsg) > 0: data = {'last': {'date': date, 'odometer': odometer, 'litres': litres}, 'error': errorMsg} return render_template('newPitStopForm.html', data=data) 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) @app.route('/statistics', methods=['GET']) def getStatistics(): pitstops = getAllPitStops() count = len(pitstops) distance = 0 sumLitres = 0 averageDistance = 0 averageLitresFuelled = 0 averageLitresUsed = 0 if count > 0: sumLitres = 0 for pitstop in pitstops: sumLitres += pitstop['litres'] averageLitresFuelled = round(sumLitres/count, 2) if count > 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) 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__': if not os.path.isfile(DATABASE) or os.stat(DATABASE).st_size == 0: init_db() app.run(debug=True, host='0.0.0.0')