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 from flask.ext.security import Security, SQLAlchemyUserDatastore, \ UserMixin, RoleMixin, login_required, utils import uuid import hashlib import time from functools import wraps app = Flask(__name__) DATABASE = '/data/rollerverbrauch.db' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+DATABASE db = SQLAlchemy(app) app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'development key' app.config['SECURITY_PASSWORD_HASH'] = 'pbkdf2_sha512' app.config['SECURITY_PASSWORD_SALT'] = 'xxxxxxxxxxxxxxxxxxxxxx' app.config.from_object(__name__) roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) def __str__(self): return self.name def __hash__(self): return hash(self.name) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship( 'Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic') ) def __repr__(self): return '' % self.username class Pitstop(db.Model): id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) odometer = db.Column(db.Integer) litres = db.Column(db.Numeric(5,2)) def __init__(self, odometer, litres, date): self.odometer = odometer self.litres = litres self.date = date def __repr__(self): return '' % (self.odometer, self.litres) user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) @app.before_first_request def before_first_request(): db.create_all() user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='end-user', description='End user') encrypted_password = utils.encrypt_password('password') if not user_datastore.get_user('someone@example.com'): user_datastore.create_user(email='someone@example.com', password=encrypted_password) if not user_datastore.get_user('admin@example.com'): user_datastore.create_user(email='admin@example.com', password=encrypted_password) # Commit any database changes; the User and Roles must exist before we can add a Role to the User db.session.commit() # Give one User has the "end-user" role, while the other has the "admin" role. (This will have no effect if the # Users already have these Roles.) Again, commit any database changes. user_datastore.add_role_to_user('someone@example.com', 'end-user') user_datastore.add_role_to_user('admin@example.com', 'admin') db.session.commit() @app.before_request def before_request(): g.data = {} @app.route('/') @login_required def index(): return redirect(url_for('get_pit_stops')) @app.route('/pitstops', methods=['POST']) @login_required def create_pit_stop(): last_pitstop = Pitstop.query.order_by(Pitstop.date.desc()).first() if last_pitstop is None: last_pitstop = Pitstop(0, 0, None) error_msg = {} date_of_pitstop = request.form['date'] try: date_of_pitstop = datetime.strptime(date_of_pitstop, '%Y-%m-%d').strftime('%Y-%m-%d') except ValueError: error_msg['date'] = 'invalid date, only YYYY-MM-DD is allowed' date_of_pitstop = request.form['date'] odometer = request.form['odometer'] try: odometer = int(odometer) except ValueError: error_msg['odometer'] = 'Illegal Value, only Integers allowed' odometer = None if odometer is not None and odometer <= last_pitstop.odometer: error_msg['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: error_msg['litres'] = 'Illegal Value, only floating point allowed' litres = None if litres is not None and litres <= 0: error_msg['litres'] = 'Litres must not be 0' litres = request.form['litres'] if litres is None: litres = request.form['litres'] # error checking here if len(error_msg) > 0: data = {'last': {'date': date_of_pitstop, 'odometer': odometer, 'litres': litres}, 'error': error_msg} return render_template('newPitStopForm.html', data=data) new_stop = Pitstop(odometer, litres, datetime.strptime(date_of_pitstop, '%Y-%m-%d')) db.session.add(new_stop) db.session.commit() return redirect(url_for('get_pit_stops')) @app.route('/pitstops/createForm', methods=['GET']) @login_required def create_pit_stop_form(): last_stop = Pitstop.query.order_by(Pitstop.date.desc()).first() if last_stop is None: last_stop = Pitstop(0, 0, date(1970, 1, 1)) values = dict() values['odometer'] = last_stop.odometer values['litres'] = last_stop.litres values['date'] = time.strftime("%Y-%m-%d") g.data['last'] = values g.data['error'] = None return render_template('newPitStopForm.html', data=g.data) @app.route('/pitstops', methods=['GET']) @login_required 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']) @login_required def get_manual(): return render_template('manual.html', data=g.data) @app.route('/statistics', methods=['GET']) @login_required 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')