]>
git.datanom.net - pwp.git/blob - app/DB/db.py
1 from enum
import IntEnum
, unique
3 from abc
import ABCMeta
4 from baseorm
import Observer
6 logging
.basicConfig(level
=logging
.INFO
)
7 logger
= logging
.getLogger(__name__
)
10 class DBDriver(IntEnum
):
14 class Singleton(ABCMeta
):
16 def __call__(cls
, password
, driver
= DBDriver
.PG
, user
= 'pwp', database
= 'pwp', host
= 'localhost', port
= None):
17 if cls
not in cls
._instances
:
18 cls
._instances
[cls
] = super(Singleton
, cls
).__call
__(password
, driver
= DBDriver
.PG
, user
= 'pwp', database
= 'pwp', host
= 'localhost', port
= None)
19 return cls
._instances
[cls
]
21 class DB(Observer
, metaclass
=Singleton
):
24 def __init__(self
, password
, driver
= DBDriver
.PG
, user
= 'pwp', database
= 'pwp', host
= 'localhost', port
= None):
25 self
.password
= password
27 self
.database
= database
32 if driver
== DBDriver
.PG
:
33 self
.__filename
__ = 'db_postgres.sql'
34 elif driver
== DBDriver
.MySQL
:
35 self
.__filename
__ = 'db_mysql.sql'
38 if self
.driver
is DBDriver
.PG
:
39 from postgres
import Postgres
41 logger
.info("Connect: database: {0} user: {1} host: {2} port: {3}".format(self
.database
, self
.user
, self
.host
, self
.port
))
42 self
.db
= Postgres(self
.database
, self
.user
, self
.password
, self
.host
, self
.port
)
43 except Exception as e
:
45 elif self
.driver
is DBDriver
.MySQL
:
46 from mysqld
import Mysql
48 self
.db
= Mysql(self
.database
, self
.user
, self
.password
, self
.host
, self
.port
)
49 except Exception as e
:
52 raise Exception("%s: Unknown DB driver" % self
.driver
)
54 def update(self
, subject
):
60 file = open(self
.__filename
__, "r")
67 def query(self
, object, **kwargs
):
69 if object.lower() == 'user' and self
.driver
is DBDriver
.PG
:
70 sql
= 'select * from "{0}" where '.format(object)
72 sql
= 'select * from {0} where '.format(object)
75 for name
, value
in kwargs
.items():
76 if name
.lower() == 'user' and self
.driver
is DBDriver
.PG
:
77 attr
= '"{0}"'.format(name
)
81 clause
+= ' and {0} = %s '.format(attr
)
83 clause
= '{0} = %s'.format(attr
)
84 placeholder
.append(value
)
86 logger
.info("{0} -> {1}".format(sql
, placeholder
))
87 return self
.db
.query(sql
, placeholder
)
89 raise Exception("{0}: Missing at least one query parameter".format(object))
91 def store(self
, object):
92 if inspect
.isclass(object):
93 raise Exception("{0}: Class not instance".format(object))
95 if hasattr(object, '__tablename__'):
96 table
= object.__tablename
__
98 table
= object.__class
__.__name
__
100 v
= [i
for i
in dir(object) if isinstance(getattr(type(object), i
, None), property)]
108 value
= getattr(object, p
)
118 if hasattr(value
, 'id'):
119 values
.append(value
.id)
123 if action
== 'insert':
124 if table
.lower() == 'user' and self
.driver
is DBDriver
.PG
:
125 sql
= 'insert into "' + table
+ '" ('
127 sql
= 'insert into ' + table
+ ' ('
128 for i
in range(0, len(column
)):
130 if field
.lower() == 'user' and self
.driver
is DBDriver
.PG
:
131 field
= '"{0}"'.format(field
)
137 for i
in range(0, len(values
)):
143 object.id = self
.db
.insert(sql
, values
)
145 if table
.lower() == 'user' and self
.driver
is DBDriver
.PG
:
146 sql
= 'update "' + table
+ '" set '
148 sql
= 'update ' + table
+ ' set '
149 for i
in range(0, len(column
)):
151 sql
+= '{0} = %s'.format(column
[i
])
153 sql
+= ', {0} = %s'.format(column
[i
])
154 sql
+= ' where id = {0}'.format(id)
155 self
.db
.update(sql
, values
)
158 default
= '<%s.%s object at %s>' % (self
.__class
__.__module
__, self
.__class
__.__name
__, hex(id(self
)))
159 return "%s <Driver: %s, User: %s, database: %s>" % (default
, self
.driver
.name
, self
.user
, self
.database
)
162 #print("%s: deleted" % self.__class__.__name__)
165 except AttributeError:
169 def __init__(self
, x
):
185 if __name__
== "__main__":
187 sys
.path
.append('../..')
188 from app
.models
import User
, Portfolio
, Album
, Photo
, AccessRight
189 #db = DB('test', DBDriver.MySQL)
193 user
= User('test', 'test@test.dk', 'test', 'sha256$1HX2n73E$ac27f843b4342df7b6c12e5ac340e063ea958d52ce62c3883c124385c96b263a')
197 portfolio
= Portfolio('test', user
)
199 album
= Album('test', portfolio
)
201 accessright
= AccessRight(user
)
203 photo
= Photo('test', album
)
This page took 0.170589 seconds and 6 git commands to generate.