From 33333561f3c049030cce7c4bef9e0079dd884cc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Gr=C3=B6ger?= Date: Thu, 19 Dec 2019 18:26:41 +0100 Subject: [PATCH] add creditList support but can't update database --- .gitignore | 5 +- geruecht/__init__.py | 22 +++-- geruecht/controller/accesTokenController.py | 2 +- geruecht/controller/databaseController.py | 90 +++++++++++++++++-- geruecht/finanzer/routes.py | 16 ++-- geruecht/model/creditList.py | 99 ++++++++++++++------- geruecht/model/user.py | 55 +++++++----- geruecht/routes.py | 8 +- 8 files changed, 217 insertions(+), 80 deletions(-) diff --git a/.gitignore b/.gitignore index 716695e..037f03d 100644 --- a/.gitignore +++ b/.gitignore @@ -116,4 +116,7 @@ dmypy.json .pyre/ #ide -.idea \ No newline at end of file +.idea + +.vscode/ +*.log \ No newline at end of file diff --git a/geruecht/__init__.py b/geruecht/__init__.py index 09d744b..39b790e 100644 --- a/geruecht/__init__.py +++ b/geruecht/__init__.py @@ -40,15 +40,28 @@ class Singleton(type): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] + from .controller.databaseController import DatabaseController db = DatabaseController() from .controller.ldapController import LDAPController ldapController = LDAPController() +def getDatabesController(): + if db is not None: + return db + else: + return DatabaseController() +def getLDAPController(): + if ldapController is not None: + return ldapController + else: + return LDAPController() + + + from flask import Flask from flask_sqlalchemy import SQLAlchemy -from flask_bcrypt import Bcrypt from flask_cors import CORS from .controller.accesTokenController import AccesTokenController @@ -59,7 +72,6 @@ CORS(app) # app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' #db = SQLAlchemy(app) -bcrypt = Bcrypt(app) accesTokenController = AccesTokenController("GERUECHT") accesTokenController.start() # login_manager = LoginManager(app) @@ -71,8 +83,8 @@ accesTokenController.start() from geruecht import routes #from geruecht.baruser.routes import baruser -#from geruecht.finanzer.routes import finanzer +from geruecht.finanzer.routes import finanzer -#LOGGER.info("Registrate bluebrints") +LOGGER.info("Registrate bluebrints") #app.register_blueprint(baruser) -#app.register_blueprint(finanzer) +app.register_blueprint(finanzer) diff --git a/geruecht/controller/accesTokenController.py b/geruecht/controller/accesTokenController.py index c8594e1..6943371 100644 --- a/geruecht/controller/accesTokenController.py +++ b/geruecht/controller/accesTokenController.py @@ -106,7 +106,7 @@ class AccesTokenController(Thread, metaclass=Singleton): Verify that the AccesToken are not out of date. If one AccessToken out of date it will be deletet from tokenList. """ - valid_time=120 + valid_time=7200 LOGGER.info("Start Thread for verification that the AccessToken are not out of date.") while True: self.LOGGER.debug("Name: {}".format(self.getName())) diff --git a/geruecht/controller/databaseController.py b/geruecht/controller/databaseController.py index c73ecb0..3d5f98f 100644 --- a/geruecht/controller/databaseController.py +++ b/geruecht/controller/databaseController.py @@ -1,6 +1,8 @@ import pymysql from geruecht import Singleton from geruecht.model.user import User +from geruecht.model.creditList import CreditList +from datetime import datetime class DatabaseController(metaclass=Singleton): ''' @@ -24,17 +26,31 @@ class DatabaseController(metaclass=Singleton): raise err def getAllUser(self): + self.connect() cursor = self.db.cursor() + try: + cursor.execute("select * from user") + data = cursor.fetchall() + self.db.close() + except Exception as err: + raise err + + if data: + return [User(value) for value in data] def getUser(self, username): self.connect() retVal = None cursor = self.db.cursor() - cursor.execute("select * from user where cn='{}'".format(username)) - data = cursor.fetchone() + try: + cursor.execute("select * from user where cn='{}'".format(username)) + data = cursor.fetchone() + self.db.close() + except Exception as err: + raise err if data: retVal = User(data) - self.db.close() + return retVal @@ -42,7 +58,7 @@ class DatabaseController(metaclass=Singleton): self.connect() cursor = self.db.cursor() try: - cursor.execute("insert into user (cn, dn, firstname, lastname, `group`) VALUES ('{}','{}','{}','{}','{}')".format( + cursor.execute("insert into user (cn, dn, firstname, lastname, gruppe) VALUES ('{}','{}','{}','{}','{}')".format( data['cn'], data['dn'], data['givenName'], data['sn'], data['group'])) self.db.commit() except Exception as err: @@ -55,7 +71,7 @@ class DatabaseController(metaclass=Singleton): self.connect() cursor = self.db.cursor() try: - cursor.execute("update user dn='{}', firstname='{}', lastname='{}', group='{}' where cn='{}'".format( + cursor.execute("update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}' where cn='{}'".format( data['dn'], data['givenName'], data['sn'], data['group'], data['cn'])) self.db.commit() except Exception as err: @@ -64,5 +80,67 @@ class DatabaseController(metaclass=Singleton): raise err self.db.close() + def getCreditListFromUser(self, user, **kwargs): + self.connect() + cursor = self.db.cursor() + try: + if 'year' in kwargs: + sql = "select * from creditList where user_id={} and year_date={}".format(user.id, kwargs['year']) + else: + sql = "select * from creditList where user_id={}".format(user.id) + cursor.execute(sql) + data = cursor.fetchall() + self.db.close() + except Exception as err: + self.db.close() + raise err + if len(data) == 1: + return CreditList(data[0]) + else: + return [CreditList(value) for value in data] + + def createCreditList(self, user_id, year=datetime.now().year): + self.connect() + cursor = self.db.cursor() + try: + cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id)) + self.db.close() + except Exception as err: + self.db.close() + raise err + + def updateCreditList(self, creditlist): + self.connect() + cursor = self.db.cursor() + try: + cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year)) + data = cursor.fetchall() + self.db.close() + if len(data) == 0: + self.createCreditList(creditlist.user_id, creditlist.year) + self.connect() + cursor = self.db.cursor() + cursor.execute("update creditList set jan_guthaben={}, jan_schulden={},feb_guthaben={}, feb_schulden={}, maer_guthaben={}, maer_schulden={}, apr_guthaben={}, apr_schulden={}, mai_guthaben={}, mai_schulden={}, jun_guthaben={}, jun_schulden={}, jul_guthaben={}, jul_schulden={}, aug_guthaben={}, aug_schulden={},sep_guthaben={}, sep_schulden={},okt_guthaben={}, okt_schulden={}, nov_guthaben={}, nov_schulden={}, dez_guthaben={}, dez_schulden={}, last_schulden={} where year_date={} and user_id={}".format(creditlist.jan_guthaben, creditlist.jan_schulden, + creditlist.feb_guthaben, creditlist.feb_schulden, + creditlist.maer_guthaben, creditlist.maer_schulden, + creditlist.apr_guthaben, creditlist.apr_schulden, + creditlist.mai_guthaben, creditlist.mai_schulden, + creditlist.jun_guthaben, creditlist.jun_schulden, + creditlist.jul_guthaben, creditlist.jul_schulden, + creditlist.aug_guthaben, creditlist.aug_schulden, + creditlist.sep_guthaben, creditlist.sep_schulden, + creditlist.okt_guthaben, creditlist.okt_schulden, + creditlist.nov_guthaben, creditlist.nov_schulden, + creditlist.dez_guthaben, creditlist.dez_schulden, + creditlist.last_schulden, creditlist.year, creditlist.user_id)) + self.db.close() + except Exception as err: + self.db.rollback() + self.db.close() + raise err + + if __name__ == '__main__': - db = DatabaseController(user='tim') + db = DatabaseController() + user = db.getUser('jhille') + db.getCreditListFromUser(user, year=2018) diff --git a/geruecht/finanzer/routes.py b/geruecht/finanzer/routes.py index b134e1e..bf2c5c2 100644 --- a/geruecht/finanzer/routes.py +++ b/geruecht/finanzer/routes.py @@ -1,7 +1,7 @@ from flask import Blueprint, request, jsonify from geruecht.finanzer import LOGGER from datetime import datetime -from geruecht import MONEY +from geruecht import MONEY, db from geruecht.routes import verifyAccessToken from geruecht.model.user import User @@ -24,11 +24,11 @@ def _getFinanzer(): accToken = verifyAccessToken(token, MONEY) if accToken is not None: LOGGER.debug("Get all Useres") - users = User.query.all() + users = db.getAllUser() dic = {} for user in users: LOGGER.debug("Add User {} to ReturnValue".format(user)) - dic[user.userID] = user.toJSON() + dic[user.cn] = user.toJSON() LOGGER.debug("ReturnValue is {}".format(dic)) LOGGER.info("Send main for Finanzer") return jsonify(dic) @@ -56,13 +56,13 @@ def _getFinanzerYear(): LOGGER.debug("Get data {}".format(data)) userID = data['userId'] LOGGER.debug("UserID is {}".format(userID)) - user = User.query.filter_by(userID=userID).first() + user = db.getUser(userID) LOGGER.debug("User is {}".format(user)) - dic[user.userID] = {} + dic[user.cn] = {} LOGGER.debug("Build ReturnValue") for geruecht in user.geruechte: LOGGER.debug("Add Geruecht {} to ReturnValue".format(geruecht)) - dic[user.userID][geruecht.year] = geruecht.toJSON() + dic[user.cn][geruecht.year] = geruecht.toJSON() LOGGER.debug("ReturnValue is {}".format(dic)) LOGGER.info("Send Geruechte from User {}".format(user)) return jsonify(dic) @@ -103,7 +103,7 @@ def _addAmount(): LOGGER.error("KeyError in month. Month is set to default.") month = datetime.now().month LOGGER.debug("Year is {} and Month is {}".format(year, month)) - user = User.query.filter_by(userID=userID).first() + user = db.getUser(userID) LOGGER.debug("User is {}".format(user)) LOGGER.debug("Add amount to User {} in year {} and month {}".format(user, year, month)) user.addAmount(amount, year=year, month=month) @@ -149,7 +149,7 @@ def _addCredit(): month = datetime.now().month LOGGER.debug("Year is {} and Month is {}".format(year, month)) - user = User.query.filter_by(userID=userID).first() + user = db.getUser(userID) LOGGER.debug("User is {}".format(user)) LOGGER.debug("Add credit to User {} in year {} and month {}".format(user, year, month)) user.addCredit(credit, year=year, month=month) diff --git a/geruecht/model/creditList.py b/geruecht/model/creditList.py index 2370001..70fcaa8 100644 --- a/geruecht/model/creditList.py +++ b/geruecht/model/creditList.py @@ -1,7 +1,38 @@ from datetime import datetime from geruecht import getLogger +import geruecht LOGGER = getLogger(__name__) +def create_empty_data(): + empty_data = {'id': 0, + 'jan_guthaben': 0, + 'jan_schulden': 0, + 'feb_guthaben': 0, + 'feb_schulden': 0, + 'maer_guthaben': 0, + 'maer_schulden': 0, + 'apr_guthaben': 0, + 'apr_schulden': 0, + 'mai_guthaben': 0, + 'mai_schulden': 0, + 'jun_guthaben': 0, + 'jun_schulden': 0, + 'jul_guthaben': 0, + 'jul_schulden': 0, + 'aug_guthaben': 0, + 'aug_schulden': 0, + 'sep_guthaben': 0, + 'sep_schulden': 0, + 'okt_guthaben': 0, + 'okt_schulden': 0, + 'nov_guthaben': 0, + 'nov_schulden': 0, + 'dez_guthaben': 0, + 'dez_schulden': 0, + 'last_schulden': 0, + 'year_date': datetime.now().year, + 'user_id': 0} + return empty_data class CreditList(): """ DataBase Object Credit List: @@ -15,50 +46,53 @@ class CreditList(): year: Year of all Credits and Debts. user_id: id from the User. """ - LOGGER.debug("Initialize Geruecht") - id = db.Colum(db.Integer, primary_key=True) + def __init__(self, data): + LOGGER.debug("Initialize Geruecht") + self.id = int(data['id']) - jan_guthaben = db.Column(db.Integer, nullable=False, default=0) - jan_schulden = db.Column(db.Integer, nullable=False, default=0) + self.jan_guthaben = int(data['jan_guthaben']) + self.jan_schulden = int(data['jan_schulden']) - feb_guthaben = db.Column(db.Integer, nullable=False, default=0) - feb_schulden = db.Column(db.Integer, nullable=False, default=0) + self.feb_guthaben = int(data['feb_guthaben']) + self.feb_schulden = int(data['feb_schulden']) - maer_guthaben = db.Column(db.Integer, nullable=False, default=0) - maer_schulden = db.Column(db.Integer, nullable=False, default=0) + self.maer_guthaben = int(data['maer_guthaben']) + self.maer_schulden = int(data['maer_schulden']) - apr_guthaben = db.Column(db.Integer, nullable=False, default=0) - apr_schulden = db.Column(db.Integer, nullable=False, default=0) + self.apr_guthaben = int(data['apr_guthaben']) + self.apr_schulden = int(data['apr_schulden']) - mai_guthaben = db.Column(db.Integer, nullable=False, default=0) - mai_schulden = db.Column(db.Integer, nullable=False, default=0) + self.mai_guthaben = int(data['mai_guthaben']) + self.mai_schulden = int(data['mai_schulden']) - jun_guthaben = db.Column(db.Integer, nullable=False, default=0) - jun_schulden = db.Column(db.Integer, nullable=False, default=0) + self.jun_guthaben = int(data['jun_guthaben']) + self.jun_schulden = int(data['jun_schulden']) - jul_guthaben = db.Column(db.Integer, nullable=False, default=0) - jul_schulden = db.Column(db.Integer, nullable=False, default=0) + self.jul_guthaben = int(data['jul_guthaben']) + self.jul_schulden = int(data['jul_schulden']) - aug_guthaben = db.Column(db.Integer, nullable=False, default=0) - aug_schulden = db.Column(db.Integer, nullable=False, default=0) + self.aug_guthaben = int(data['aug_guthaben']) + self.aug_schulden = int(data['aug_schulden']) - sep_guthaben = db.Column(db.Integer, nullable=False, default=0) - sep_schulden = db.Column(db.Integer, nullable=False, default=0) + self.sep_guthaben = int(data['sep_guthaben']) + self.sep_schulden = int(data['sep_schulden']) - okt_guthaben = db.Column(db.Integer, nullable=False, default=0) - okt_schulden = db.Column(db.Integer, nullable=False, default=0) + self.okt_guthaben = int(data['okt_guthaben']) + self.okt_schulden = int(data['okt_schulden']) - nov_guthaben = db.Column(db.Integer, nullable=False, default=0) - nov_schulden = db.Column(db.Integer, nullable=False, default=0) + self.nov_guthaben = int(data['nov_guthaben']) + self.nov_schulden = int(data['nov_schulden']) - dez_guthaben = db.Column(db.Integer, nullable=False, default=0) - dez_schulden = db.Column(db.Integer, nullable=False, default=0) + self.dez_guthaben = int(data['dez_guthaben']) + self.dez_schulden = int(data['dez_schulden']) - last_schulden = db.Column(db.Integer, nullable=False, default=0) + self.last_schulden = int(data['last_schulden']) - year = db.Column(db.Integer, nullable=False, default=datetime.now().year) + self.year = int(data['year_date']) - user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) + self.user_id = int(data['user_id']) + + self.db = geruecht.getDatabesController() def getSchulden(self): """ Get Schulden @@ -184,7 +218,8 @@ class CreditList(): self.dez_schulden += amount retValue = (self.dez_guthaben, self.dez_schulden) - db.session.commit() + #db.session.commit() + self.db.updateCreditList(self) LOGGER.debug("Credit and Amount is {}".format(retValue)) return retValue @@ -238,8 +273,8 @@ class CreditList(): elif month == 12: self.dez_guthaben += credit retValue = (self.dez_guthaben, self.dez_schulden) - - db.session.commit() + self.db.updateCreditList(self) + #db.session.commit() LOGGER.debug("Credit and Amount is {}".format(retValue)) return retValue diff --git a/geruecht/model/user.py b/geruecht/model/user.py index 89d63f5..d549732 100644 --- a/geruecht/model/user.py +++ b/geruecht/model/user.py @@ -1,10 +1,11 @@ from geruecht import getLogger -from geruecht import db -#from geruecht.model.creditList import CreditList +import geruecht +from geruecht.model.creditList import CreditList, create_empty_data from datetime import datetime LOGGER = getLogger(__name__) + class User(): """ Database Object for User @@ -25,10 +26,17 @@ class User(): self.dn = data['dn'] self.firstname = data['firstname'] self.lastname = data['lastname'] - self.group = data['group'] - + self.group = data['gruppe'] + self.db = geruecht.getDatabesController() + self.ldap = geruecht.getLDAPController() + self.geruechte = [] + geruechte = self.db.getCreditListFromUser(self) + if type(geruechte) == list: + self.geruechte = geruechte + elif type(geruechte) == CreditList: + self.geruechte.append(geruechte) #geruechte = db.relationship('CreditList', backref='user', lazy=True) - ''' + def createGeruecht(self, amount=0, year=datetime.now().year): """ Create Geruecht @@ -43,10 +51,14 @@ class User(): the created geruecht """ LOGGER.debug("Create Geruecht for user {} in year {}".format(self, year)) - credit = CreditList(user_id=self.id, last_schulden=amount, year=year) - db.session.add(credit) - db.session.commit() - credit = CreditList.query.filter_by(year=year, user_id=self.id).first() + data = create_empty_data() + data['user_id'] = self.id, + data['last_schulden'] = amount, + data['year_date'] = year + credit = CreditList(data) + self.geruechte.append(credit) + self.db.updateCreditList(credit) + credit = self.db.getCreditListFromUser(self, year=year) LOGGER.debug("Created Geruecht {}".format(credit)) return credit @@ -93,8 +105,7 @@ class User(): geruecht = self.getGeruecht(year=year) retVal = geruecht.addAmount(amount, month=month) - db.session.add(geruecht) - db.session.commit() + self.db.updateCreditList(geruecht) self.updateGeruecht() @@ -118,8 +129,7 @@ class User(): geruecht = self.getGeruecht(year=year) retVal = geruecht.addCredit(credit, month=month) - db.session.add(geruecht) - db.session.commit() + self.db.updateCreditList(geruecht) self.updateGeruecht() @@ -138,8 +148,7 @@ class User(): geruecht.last_schulden = 0 if index != 0: geruecht.last_schulden = (self.geruechte[index - 1].getSchulden() * -1) - - db.session.commit() + self.db.updateCreditList(geruecht) def sortYear(self, geruecht): """ Sort Year @@ -154,7 +163,7 @@ class User(): int year of the geruecht """ return geruecht.year - ''' + def toJSON(self): """ Create Dic to dump in JSON @@ -170,10 +179,10 @@ class User(): } return dic - def update(self): - data = ldap.getUserData(self.cn) - data['group'] = ldap.getGroup(self.cn) - db.updateUser(data) + def updateUser(self): + data = self.ldap.getUserData(self.cn) + data['group'] = self.ldap.getGroup(self.cn) + self.db.updateUser(data) def login(self, password): """ Login for the User @@ -185,13 +194,13 @@ class User(): """ LOGGER.debug("Login User {}".format(self)) try: - from geruecht import ldapController as ldap - ldap.login(self.cn, password) + self.ldap.login(self.cn, password) - self.update() + self.updateUser() return True except: return False def __repr__(self): return "User({}, {}, {})".format(self.cn, self.dn, self.group) + diff --git a/geruecht/routes.py b/geruecht/routes.py index 2685794..6aa742f 100644 --- a/geruecht/routes.py +++ b/geruecht/routes.py @@ -1,11 +1,11 @@ from geruecht import app, db, accesTokenController, MONEY, BAR, USER, GASTRO, LOGGER from geruecht import ldapController as ldap from geruecht.model.user import User -#from geruecht.model.creditList import CreditList -#from geruecht.model.priceList import PriceList -from datetime import datetime from flask import request, jsonify +def login(user, password): + return user.login(password) + def verifyAccessToken(token, group): """ Verify Accestoken @@ -83,7 +83,7 @@ def _login(): LOGGER.debug("User is {}".format(user)) if user: LOGGER.debug("Check login for User {}".format(user)) - if user.login(password): + if login(user, password): token = accesTokenController.createAccesToken(user) dic = user.toJSON() dic["token"] = token