change database controller without multithreading

This commit is contained in:
Tim Gröger 2020-01-19 21:32:58 +01:00
parent f782be934d
commit 635051d615
6 changed files with 97 additions and 152 deletions

View File

@ -5,6 +5,8 @@
"""
from .logger import getLogger
from geruecht.controller import dbConfig
from flask_mysqldb import MySQL
LOGGER = getLogger(__name__)
LOGGER.info("Initialize App")
@ -16,6 +18,12 @@ LOGGER.info("Build APP")
app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
app.config['MYSQL_HOST'] = dbConfig['URL']
app.config['MYSQL_USER'] = dbConfig['user']
app.config['MYSQL_PASSWORD'] = dbConfig['passwd']
app.config['MYSQL_DB'] = dbConfig['database']
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
db = MySQL(app)
from geruecht import routes
from geruecht.baruser.routes import baruser

View File

@ -1,6 +1,7 @@
import yaml
import sys
from . import LOGGER
from .logger import getLogger
LOGGER = getLogger(__name__)
default = {
'AccessTokenLifeTime': 1800,

View File

@ -1,17 +1,10 @@
import pymysql
from . import Singleton
from geruecht import db
from geruecht.model.user import User
from geruecht.model.creditList import CreditList
from datetime import datetime, timedelta
def connected(func):
def wrapper(*args, **kwargs):
self = args[0]
if not self.db.open:
self.connect()
return func(*args,**kwargs)
return wrapper
class DatabaseController(metaclass=Singleton):
'''
DatabaesController
@ -19,25 +12,13 @@ class DatabaseController(metaclass=Singleton):
Connect to the Database and execute sql-executions
'''
def __init__(self, url='192.168.5.108', user='wu5', password='E1n$tein', database='geruecht'):
self.url = url
self.user = user
self.password = password
self.database = database
self.connect()
def __init__(self):
self.db = db
def connect(self):
try:
self.db = pymysql.connect(self.url, self.user, self.password, self.database, cursorclass=pymysql.cursors.DictCursor)
except Exception as err:
raise err
@connected
def getAllUser(self):
cursor = self.db.cursor()
cursor = self.db.connection.cursor()
cursor.execute("select * from user")
data = cursor.fetchall()
self.db.close()
if data:
retVal = []
@ -47,26 +28,24 @@ class DatabaseController(metaclass=Singleton):
user.initGeruechte(creditLists)
retVal.append(user)
return retVal
@connected
def getUser(self, username):
retVal = None
cursor = self.db.cursor()
cursor = self.db.connection.cursor()
cursor.execute("select * from user where uid='{}'".format(username))
data = cursor.fetchone()
self.db.close()
if data:
retVal = User(data)
creditLists = self.getCreditListFromUser(retVal)
retVal.initGeruechte(creditLists)
return retVal
@connected
def getUserById(self, id):
retVal = None
cursor = self.db.cursor()
cursor = self.db.connection.cursor()
cursor.execute("select * from user where id={}".format(id))
data = cursor.fetchone()
self.db.close()
if data:
retVal = User(data)
creditLists = self.getCreditListFromUser(retVal)
@ -81,72 +60,49 @@ class DatabaseController(metaclass=Singleton):
retVal += group
return retVal
@connected
def insertUser(self, user):
cursor = self.db.cursor()
cursor = self.db.connection.cursor()
groups = self._convertGroupToString(user.group)
try:
cursor.execute("insert into user (uid, dn, firstname, lastname, gruppe, lockLimit, locked, autoLock, mail) VALUES ('{}','{}','{}','{}','{}',{},{},{},'{}')".format(
user.uid, user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail))
self.db.commit()
except Exception as err:
self.db.rollback()
self.db.close()
raise err
self.db.close()
self.db.connection.commit()
@connected
def updateUser(self, user):
cursor = self.db.cursor()
cursor = self.db.connection.cursor()
groups = self._convertGroupToString(user.group)
try:
sql = "update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}', lockLimit={}, locked={}, autoLock={}, mail='{}' where uid='{}'".format(
user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail, user.uid)
print(sql)
cursor.execute(sql)
self.db.commit()
except Exception as err:
self.db.rollback()
self.db.close()
print(err.__traceback__)
raise err
self.db.connection.commit()
self.db.close()
@connected
def getCreditListFromUser(self, user, **kwargs):
cursor = self.db.cursor()
cursor = self.db.connection.cursor()
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()
if len(data) == 1:
return [CreditList(data[0])]
else:
return [CreditList(value) for value in data]
@connected
def createCreditList(self, user_id, year=datetime.now().year):
cursor = self.db.cursor()
try:
cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id))
self.db.commit()
self.db.close()
except Exception as err:
self.db.rollback()
self.db.close()
raise err
@connected
def createCreditList(self, user_id, year=datetime.now().year):
cursor = self.db.connection.cursor()
cursor.execute("insert into creditList (year_date, user_id) values ({},{})".format(year, user_id))
self.db.connection.commit()
def updateCreditList(self, creditlist):
cursor = self.db.cursor()
try:
cursor = self.db.connection.cursor()
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)
sql = "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,
@ -163,54 +119,34 @@ class DatabaseController(metaclass=Singleton):
creditlist.dez_guthaben, creditlist.dez_schulden,
creditlist.last_schulden, creditlist.year, creditlist.user_id)
print(sql)
self.connect()
cursor = self.db.cursor()
cursor = self.db.connection.cursor()
cursor.execute(sql)
self.db.commit()
self.db.close()
except Exception as err:
self.db.rollback()
self.db.close()
raise err
@connected
self.db.connection.commit()
def getWorker(self, user, date):
cursor = self.db.cursor()
cursor = self.db.connection.cursor()
cursor.execute("select * from bardienste where user_id={} and startdatetime='{}'".format(user.id, date))
data = cursor.fetchone()
self.db.close()
return {"user": user, "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} if data else None
return {"user": user.toJSON(), "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} if data else None
@connected
def getWorkers(self, date):
cursor = self.db.cursor()
cursor = self.db.connection.cursor()
cursor.execute("select * from bardienste where startdatetime='{}'".format(date))
data = cursor.fetchall()
self.db.close()
return [{"user": self.getUserById(work['user_id']).toJSON(), "startdatetime": work['startdatetime'], "enddatetime": work['enddatetime']} for work in data]
@connected
def setWorker(self, user, date):
try:
cursor = self.db.cursor()
cursor.execute("insert into bardienste (user_id, startdatetime, enddatetime) values ({},'{}','{}')".format(user.id, date, date + timedelta(days=1)))
self.db.commit()
self.db.close()
except Exception as err:
self.db.rollback()
self.db.close()
raise err
@connected
def setWorker(self, user, date):
cursor = self.db.connection.cursor()
cursor.execute("insert into bardienste (user_id, startdatetime, enddatetime) values ({},'{}','{}')".format(user.id, date, date + timedelta(days=1)))
self.db.connection.commit()
def deleteWorker(self, user, date):
try:
cursor = self.db.cursor()
cursor = self.db.connection.cursor()
cursor.execute("delete from bardienste where user_id={} and startdatetime='{}'".format(user.id, date))
self.db.commit()
self.db.close()
except Exception as err:
self.db.rollback()
self.db.close()
raise err
self.db.connection.commit()
if __name__ == '__main__':
db = DatabaseController()

View File

@ -6,7 +6,7 @@ from geruecht.model.user import User
from geruecht.exceptions import PermissionDenied
from datetime import datetime, timedelta
db = dc.DatabaseController(dbConfig['URL'], dbConfig['user'], dbConfig['passwd'], dbConfig['database'])
db = dc.DatabaseController()
ldap = lc.LDAPController(ldapConfig['URL'], ldapConfig['dn'])
emailController = ec.EmailController(mailConfig['URL'], mailConfig['user'], mailConfig['passwd'], mailConfig['port'], mailConfig['email'])
@ -25,10 +25,11 @@ class UserController(metaclass=Singleton):
user = self.getUser(username)
if (not db.getWorker(user, date)):
db.setWorker(user, date)
return self.getWorker(date, username=username)
def deleteWorker(self, username, date):
user = self.getUser(username)
db.setWorker(user, date)
db.deleteWorker(user, date)
def lockUser(self, username, locked):
user = self.getUser(username)

View File

@ -1,17 +0,0 @@
from geruecht.controller import db
class PriceList(db.Model):
""" Database Model for PriceList
PriceList has lots of Drinks and safe all Prices (normal, for club, for other clubs, which catagory, etc)
"""
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False, unique=True)
price = db.Column(db.Integer, nullable=False)
price_club = db.Column(db.Integer, nullable=False)
price_ext_club = db.Column(db.Integer, nullable=False)
category = db.Column(db.Integer, nullable=False)
upPrice = db.Column(db.Integer)
upPrice_club = db.Column(db.Integer)
upPrice_ext_club = db.Column(db.Integer)

View File

@ -9,9 +9,8 @@ userController = uc.UserController()
@vorstand.route("/sm/addUser", methods=['POST', 'GET'])
@login_required(groups=[MONEY, GASTRO])
def _addUser():
def _addUser(**kwargs):
if request.method == 'GET':
return "<h1>HEllo World</h1>"
@ -19,7 +18,24 @@ def _addUser():
data = request.get_json()
user = data['user']
date = datetime.utcfromtimestamp(int(data['date']))
userController.addWorker(user['username'], date)
retVal = userController.addWorker(user['username'], date)
print(retVal)
return jsonify(retVal)
print(data)
return jsonify({"date": date})
@vorstand.route("/sm/getUser", methods=['POST'])
@login_required(groups=[MONEY, GASTRO])
def _getUser(**kwargs):
data = request.get_json()
date = datetime.utcfromtimestamp(int(data['date']))
retVal = userController.getWorker(date)
print(retVal)
return jsonify(retVal)
@vorstand.route("/sm/deleteUser", methods=['POST'])
@login_required(groups=[MONEY, GASTRO])
def _deletUser(**kwargs):
data = request.get_json()
user = data['user']
date = datetime.utcfromtimestamp(int(data['date']))
userController.deleteWorker(user['username'], date)
return jsonify({"ok": "ok"})