change database controller without multithreading
This commit is contained in:
parent
f782be934d
commit
635051d615
|
@ -5,6 +5,8 @@
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from .logger import getLogger
|
from .logger import getLogger
|
||||||
|
from geruecht.controller import dbConfig
|
||||||
|
from flask_mysqldb import MySQL
|
||||||
|
|
||||||
LOGGER = getLogger(__name__)
|
LOGGER = getLogger(__name__)
|
||||||
LOGGER.info("Initialize App")
|
LOGGER.info("Initialize App")
|
||||||
|
@ -16,6 +18,12 @@ LOGGER.info("Build APP")
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
CORS(app)
|
CORS(app)
|
||||||
app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
|
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 import routes
|
||||||
from geruecht.baruser.routes import baruser
|
from geruecht.baruser.routes import baruser
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
import yaml
|
import yaml
|
||||||
import sys
|
import sys
|
||||||
from . import LOGGER
|
from .logger import getLogger
|
||||||
|
LOGGER = getLogger(__name__)
|
||||||
|
|
||||||
default = {
|
default = {
|
||||||
'AccessTokenLifeTime': 1800,
|
'AccessTokenLifeTime': 1800,
|
||||||
|
|
|
@ -1,17 +1,10 @@
|
||||||
import pymysql
|
import pymysql
|
||||||
from . import Singleton
|
from . import Singleton
|
||||||
|
from geruecht import db
|
||||||
from geruecht.model.user import User
|
from geruecht.model.user import User
|
||||||
from geruecht.model.creditList import CreditList
|
from geruecht.model.creditList import CreditList
|
||||||
from datetime import datetime, timedelta
|
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):
|
class DatabaseController(metaclass=Singleton):
|
||||||
'''
|
'''
|
||||||
DatabaesController
|
DatabaesController
|
||||||
|
@ -19,25 +12,13 @@ class DatabaseController(metaclass=Singleton):
|
||||||
Connect to the Database and execute sql-executions
|
Connect to the Database and execute sql-executions
|
||||||
'''
|
'''
|
||||||
|
|
||||||
def __init__(self, url='192.168.5.108', user='wu5', password='E1n$tein', database='geruecht'):
|
def __init__(self):
|
||||||
self.url = url
|
self.db = db
|
||||||
self.user = user
|
|
||||||
self.password = password
|
|
||||||
self.database = database
|
|
||||||
self.connect()
|
|
||||||
|
|
||||||
|
|
||||||
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):
|
def getAllUser(self):
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.connection.cursor()
|
||||||
cursor.execute("select * from user")
|
cursor.execute("select * from user")
|
||||||
data = cursor.fetchall()
|
data = cursor.fetchall()
|
||||||
self.db.close()
|
|
||||||
|
|
||||||
if data:
|
if data:
|
||||||
retVal = []
|
retVal = []
|
||||||
|
@ -47,26 +28,24 @@ class DatabaseController(metaclass=Singleton):
|
||||||
user.initGeruechte(creditLists)
|
user.initGeruechte(creditLists)
|
||||||
retVal.append(user)
|
retVal.append(user)
|
||||||
return retVal
|
return retVal
|
||||||
@connected
|
|
||||||
def getUser(self, username):
|
def getUser(self, username):
|
||||||
retVal = None
|
retVal = None
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.connection.cursor()
|
||||||
cursor.execute("select * from user where uid='{}'".format(username))
|
cursor.execute("select * from user where uid='{}'".format(username))
|
||||||
data = cursor.fetchone()
|
data = cursor.fetchone()
|
||||||
self.db.close()
|
|
||||||
if data:
|
if data:
|
||||||
retVal = User(data)
|
retVal = User(data)
|
||||||
creditLists = self.getCreditListFromUser(retVal)
|
creditLists = self.getCreditListFromUser(retVal)
|
||||||
retVal.initGeruechte(creditLists)
|
retVal.initGeruechte(creditLists)
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
@connected
|
|
||||||
def getUserById(self, id):
|
def getUserById(self, id):
|
||||||
retVal = None
|
retVal = None
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.connection.cursor()
|
||||||
cursor.execute("select * from user where id={}".format(id))
|
cursor.execute("select * from user where id={}".format(id))
|
||||||
data = cursor.fetchone()
|
data = cursor.fetchone()
|
||||||
self.db.close()
|
|
||||||
if data:
|
if data:
|
||||||
retVal = User(data)
|
retVal = User(data)
|
||||||
creditLists = self.getCreditListFromUser(retVal)
|
creditLists = self.getCreditListFromUser(retVal)
|
||||||
|
@ -81,136 +60,93 @@ class DatabaseController(metaclass=Singleton):
|
||||||
retVal += group
|
retVal += group
|
||||||
return retVal
|
return retVal
|
||||||
|
|
||||||
@connected
|
|
||||||
def insertUser(self, user):
|
def insertUser(self, user):
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.connection.cursor()
|
||||||
groups = self._convertGroupToString(user.group)
|
groups = self._convertGroupToString(user.group)
|
||||||
try:
|
cursor.execute("insert into user (uid, dn, firstname, lastname, gruppe, lockLimit, locked, autoLock, mail) VALUES ('{}','{}','{}','{}','{}',{},{},{},'{}')".format(
|
||||||
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))
|
||||||
user.uid, user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail))
|
self.db.connection.commit()
|
||||||
self.db.commit()
|
|
||||||
except Exception as err:
|
|
||||||
self.db.rollback()
|
|
||||||
self.db.close()
|
|
||||||
raise err
|
|
||||||
self.db.close()
|
|
||||||
|
|
||||||
@connected
|
|
||||||
def updateUser(self, user):
|
def updateUser(self, user):
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.connection.cursor()
|
||||||
groups = self._convertGroupToString(user.group)
|
groups = self._convertGroupToString(user.group)
|
||||||
try:
|
sql = "update user set dn='{}', firstname='{}', lastname='{}', gruppe='{}', lockLimit={}, locked={}, autoLock={}, mail='{}' where uid='{}'".format(
|
||||||
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)
|
||||||
user.dn, user.firstname, user.lastname, groups, user.limit, user.locked, user.autoLock, user.mail, user.uid)
|
print(sql)
|
||||||
print(sql)
|
cursor.execute(sql)
|
||||||
cursor.execute(sql)
|
self.db.connection.commit()
|
||||||
self.db.commit()
|
|
||||||
except Exception as err:
|
|
||||||
self.db.rollback()
|
|
||||||
self.db.close()
|
|
||||||
print(err.__traceback__)
|
|
||||||
raise err
|
|
||||||
|
|
||||||
self.db.close()
|
|
||||||
|
|
||||||
@connected
|
|
||||||
def getCreditListFromUser(self, user, **kwargs):
|
def getCreditListFromUser(self, user, **kwargs):
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.connection.cursor()
|
||||||
if 'year' in kwargs:
|
if 'year' in kwargs:
|
||||||
sql = "select * from creditList where user_id={} and year_date={}".format(user.id, kwargs['year'])
|
sql = "select * from creditList where user_id={} and year_date={}".format(user.id, kwargs['year'])
|
||||||
else:
|
else:
|
||||||
sql = "select * from creditList where user_id={}".format(user.id)
|
sql = "select * from creditList where user_id={}".format(user.id)
|
||||||
cursor.execute(sql)
|
cursor.execute(sql)
|
||||||
data = cursor.fetchall()
|
data = cursor.fetchall()
|
||||||
self.db.close()
|
|
||||||
if len(data) == 1:
|
if len(data) == 1:
|
||||||
return [CreditList(data[0])]
|
return [CreditList(data[0])]
|
||||||
else:
|
else:
|
||||||
return [CreditList(value) for value in data]
|
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):
|
def updateCreditList(self, creditlist):
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.connection.cursor()
|
||||||
try:
|
cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year))
|
||||||
cursor.execute("select * from creditList where user_id={} and year_date={}".format(creditlist.user_id, creditlist.year))
|
data = cursor.fetchall()
|
||||||
data = cursor.fetchall()
|
if len(data) == 0:
|
||||||
self.db.close()
|
self.createCreditList(creditlist.user_id, creditlist.year)
|
||||||
if len(data) == 0:
|
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,
|
||||||
self.createCreditList(creditlist.user_id, creditlist.year)
|
creditlist.feb_guthaben, creditlist.feb_schulden,
|
||||||
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,
|
creditlist.maer_guthaben, creditlist.maer_schulden,
|
||||||
creditlist.feb_guthaben, creditlist.feb_schulden,
|
creditlist.apr_guthaben, creditlist.apr_schulden,
|
||||||
creditlist.maer_guthaben, creditlist.maer_schulden,
|
creditlist.mai_guthaben, creditlist.mai_schulden,
|
||||||
creditlist.apr_guthaben, creditlist.apr_schulden,
|
creditlist.jun_guthaben, creditlist.jun_schulden,
|
||||||
creditlist.mai_guthaben, creditlist.mai_schulden,
|
creditlist.jul_guthaben, creditlist.jul_schulden,
|
||||||
creditlist.jun_guthaben, creditlist.jun_schulden,
|
creditlist.aug_guthaben, creditlist.aug_schulden,
|
||||||
creditlist.jul_guthaben, creditlist.jul_schulden,
|
creditlist.sep_guthaben, creditlist.sep_schulden,
|
||||||
creditlist.aug_guthaben, creditlist.aug_schulden,
|
creditlist.okt_guthaben, creditlist.okt_schulden,
|
||||||
creditlist.sep_guthaben, creditlist.sep_schulden,
|
creditlist.nov_guthaben, creditlist.nov_schulden,
|
||||||
creditlist.okt_guthaben, creditlist.okt_schulden,
|
creditlist.dez_guthaben, creditlist.dez_schulden,
|
||||||
creditlist.nov_guthaben, creditlist.nov_schulden,
|
creditlist.last_schulden, creditlist.year, creditlist.user_id)
|
||||||
creditlist.dez_guthaben, creditlist.dez_schulden,
|
print(sql)
|
||||||
creditlist.last_schulden, creditlist.year, creditlist.user_id)
|
cursor = self.db.connection.cursor()
|
||||||
print(sql)
|
cursor.execute(sql)
|
||||||
self.connect()
|
self.db.connection.commit()
|
||||||
cursor = self.db.cursor()
|
|
||||||
cursor.execute(sql)
|
|
||||||
self.db.commit()
|
|
||||||
self.db.close()
|
|
||||||
except Exception as err:
|
|
||||||
self.db.rollback()
|
|
||||||
self.db.close()
|
|
||||||
raise err
|
|
||||||
@connected
|
|
||||||
def getWorker(self, user, date):
|
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))
|
cursor.execute("select * from bardienste where user_id={} and startdatetime='{}'".format(user.id, date))
|
||||||
data = cursor.fetchone()
|
data = cursor.fetchone()
|
||||||
self.db.close()
|
return {"user": user.toJSON(), "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} if data else None
|
||||||
return {"user": user, "startdatetime": data['startdatetime'], "enddatetime": data['enddatetime']} if data else None
|
|
||||||
|
|
||||||
@connected
|
|
||||||
def getWorkers(self, date):
|
def getWorkers(self, date):
|
||||||
cursor = self.db.cursor()
|
cursor = self.db.connection.cursor()
|
||||||
cursor.execute("select * from bardienste where startdatetime='{}'".format(date))
|
cursor.execute("select * from bardienste where startdatetime='{}'".format(date))
|
||||||
data = cursor.fetchall()
|
data = cursor.fetchall()
|
||||||
self.db.close()
|
|
||||||
return [{"user": self.getUserById(work['user_id']).toJSON(), "startdatetime": work['startdatetime'], "enddatetime": work['enddatetime']} for work in data]
|
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):
|
def deleteWorker(self, user, date):
|
||||||
try:
|
cursor = self.db.connection.cursor()
|
||||||
cursor = self.db.cursor()
|
cursor.execute("delete from bardienste where user_id={} and startdatetime='{}'".format(user.id, date))
|
||||||
cursor.execute("delete from bardienste where user_id={} and startdatetime='{}'".format(user.id, date))
|
self.db.connection.commit()
|
||||||
self.db.commit()
|
|
||||||
self.db.close()
|
|
||||||
except Exception as err:
|
|
||||||
self.db.rollback()
|
|
||||||
self.db.close()
|
|
||||||
raise err
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
db = DatabaseController()
|
db = DatabaseController()
|
||||||
|
|
|
@ -6,7 +6,7 @@ from geruecht.model.user import User
|
||||||
from geruecht.exceptions import PermissionDenied
|
from geruecht.exceptions import PermissionDenied
|
||||||
from datetime import datetime, timedelta
|
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'])
|
ldap = lc.LDAPController(ldapConfig['URL'], ldapConfig['dn'])
|
||||||
emailController = ec.EmailController(mailConfig['URL'], mailConfig['user'], mailConfig['passwd'], mailConfig['port'], mailConfig['email'])
|
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)
|
user = self.getUser(username)
|
||||||
if (not db.getWorker(user, date)):
|
if (not db.getWorker(user, date)):
|
||||||
db.setWorker(user, date)
|
db.setWorker(user, date)
|
||||||
|
return self.getWorker(date, username=username)
|
||||||
|
|
||||||
def deleteWorker(self, username, date):
|
def deleteWorker(self, username, date):
|
||||||
user = self.getUser(username)
|
user = self.getUser(username)
|
||||||
db.setWorker(user, date)
|
db.deleteWorker(user, date)
|
||||||
|
|
||||||
def lockUser(self, username, locked):
|
def lockUser(self, username, locked):
|
||||||
user = self.getUser(username)
|
user = self.getUser(username)
|
||||||
|
|
|
@ -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)
|
|
|
@ -9,9 +9,8 @@ userController = uc.UserController()
|
||||||
|
|
||||||
|
|
||||||
@vorstand.route("/sm/addUser", methods=['POST', 'GET'])
|
@vorstand.route("/sm/addUser", methods=['POST', 'GET'])
|
||||||
|
|
||||||
@login_required(groups=[MONEY, GASTRO])
|
@login_required(groups=[MONEY, GASTRO])
|
||||||
def _addUser():
|
def _addUser(**kwargs):
|
||||||
|
|
||||||
if request.method == 'GET':
|
if request.method == 'GET':
|
||||||
return "<h1>HEllo World</h1>"
|
return "<h1>HEllo World</h1>"
|
||||||
|
@ -19,7 +18,24 @@ def _addUser():
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
user = data['user']
|
user = data['user']
|
||||||
date = datetime.utcfromtimestamp(int(data['date']))
|
date = datetime.utcfromtimestamp(int(data['date']))
|
||||||
userController.addWorker(user['username'], date)
|
retVal = userController.addWorker(user['username'], date)
|
||||||
|
print(retVal)
|
||||||
|
return jsonify(retVal)
|
||||||
|
|
||||||
print(data)
|
@vorstand.route("/sm/getUser", methods=['POST'])
|
||||||
return jsonify({"date": date})
|
@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"})
|
Loading…
Reference in New Issue