-import sys
-sys.path.append('..')
-sys.path.append('../..')
-from models import User, Portfolio, Album, Photo, AccessRight
from enum import IntEnum, unique
import inspect
+from abc import ABCMeta
from baseorm import Observer
+import logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
@unique
class DBDriver(IntEnum):
PG = 1
MySQL = 2
-
-class DB(Observer):
+
+class Singleton(ABCMeta):
+ _instances = {}
+ def __call__(cls, password, driver = DBDriver.PG, user = 'pwp', database = 'pwp', host = 'localhost', port = None):
+ if cls not in cls._instances:
+ cls._instances[cls] = super(Singleton, cls).__call__(password, driver = DBDriver.PG, user = 'pwp', database = 'pwp', host = 'localhost', port = None)
+ return cls._instances[cls]
+
+class DB(Observer, metaclass=Singleton):
__filename__ = None
def __init__(self, password, driver = DBDriver.PG, user = 'pwp', database = 'pwp', host = 'localhost', port = None):
if self.driver is DBDriver.PG:
from postgres import Postgres
try:
+ logger.info("Connect: database: {0} user: {1} host: {2} port: {3}".format(self.database, self.user, self.host, self.port))
self.db = Postgres(self.database, self.user, self.password, self.host, self.port)
except Exception as e:
raise Exception(e)
raise Exception("%s: Unknown DB driver" % self.driver)
def update(self, subject):
- print("update: {0}".format(subject))
self.store(subject)
def initDb(self):
except:
raise
+ def query(self, object, **kwargs):
+ if kwargs:
+ if object.lower() == 'user' and self.driver is DBDriver.PG:
+ sql = 'select * from "{0}" where '.format(object)
+ else:
+ sql = 'select * from {0} where '.format(object)
+ placeholder = []
+ clause = None
+ for name, value in kwargs.items():
+ if name.lower() == 'user' and self.driver is DBDriver.PG:
+ attr = '"{0}"'.format(name)
+ else:
+ attr = name
+ if clause:
+ clause += ' and {0} = %s '.format(attr)
+ else:
+ clause = '{0} = %s'.format(attr)
+ placeholder.append(value)
+ sql += clause
+ logger.info("{0} -> {1}".format(sql, placeholder))
+ return self.db.query(sql, placeholder)
+ else:
+ raise Exception("{0}: Missing at least one query parameter".format(object))
+
def store(self, object):
if inspect.isclass(object):
raise Exception("{0}: Class not instance".format(object))
else:
table = object.__class__.__name__
- print("Table<{0}>".format(table))
v = [i for i in dir(object) if isinstance(getattr(type(object), i, None), property)]
- for p in v:
- print("{0}: {1}".format(p, getattr(object, p)))
action = None
column = []
else:
values.append(value)
column.append(p)
- print(action)
if action == 'insert':
if table.lower() == 'user' and self.driver is DBDriver.PG:
sql = 'insert into "' + table + '" ('
sql += ' where id = {0}'.format(id)
self.db.update(sql, values)
- print(sql)
- print(values)
-
def __repr__(self):
default = '<%s.%s object at %s>' % (self.__class__.__module__, self.__class__.__name__, hex(id(self)))
return "%s <Driver: %s, User: %s, database: %s>" % (default, self.driver.name, self.user, self.database)
else:
self.__x = x
-db = DB('test', DBDriver.MySQL)
-#db = DB('test')
-db.initDb()
+if __name__ == "__main__":
+ import sys
+ sys.path.append('../..')
+ from app.models import User, Portfolio, Album, Photo, AccessRight
+ #db = DB('test', DBDriver.MySQL)
+ db = DB('test')
+ db.initDb()
-user = User('test', 'test@test.dk', 'test', 'test')
-user.addObserver(db)
-print(user)
-db.store(user)
-portfolio = Portfolio('test', user)
-print(portfolio)
-album = Album('test', portfolio)
-print(album)
-accessright = AccessRight(user)
-print(accessright)
-photo = Photo('test', album)
-print(photo)
-db.store(portfolio)
-user.name = 'MIR'
-del db
+ user = User('test', 'test@test.dk', 'test', 'sha256$1HX2n73E$ac27f843b4342df7b6c12e5ac340e063ea958d52ce62c3883c124385c96b263a')
+ user.addObserver(db)
+ print(user)
+ db.store(user)
+ portfolio = Portfolio('test', user)
+ print(portfolio)
+ album = Album('test', portfolio)
+ print(album)
+ accessright = AccessRight(user)
+ print(accessright)
+ photo = Photo('test', album)
+ print(photo)
+ db.store(portfolio)
+ user.name = 'MIR'
+ del db