Skip to content

Commit c994805

Browse files
committed
add webapp
1 parent 268cf44 commit c994805

File tree

1 file changed

+197
-0
lines changed
  • webapp/www/transwarp

1 file changed

+197
-0
lines changed

webapp/www/transwarp/db.py

Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
__author__ = 'coolcoding'
5+
6+
import logging,threading,functools
7+
8+
class Dict(dict):
9+
10+
11+
def __init__(self,names=(),values=(),**kw):
12+
super(Dict,self).__init__()
13+
for k,v in zip(names,values):
14+
self[k] = v
15+
16+
def __getattr__(self,k):
17+
try:
18+
return self[k]
19+
except KeyError:
20+
raise AttributeError('Dict object has not attribute %s' % k)
21+
22+
def __setattr__(self,k,v):
23+
self[k] = v
24+
25+
26+
# global engine object:
27+
engine = None
28+
29+
class _Engine(object):
30+
def __init__(self,connect):
31+
self._connect = connect
32+
33+
def connect(self):
34+
return self._connect()
35+
36+
37+
38+
def create_engine(user,password,database,host='127.0.0.1',port=3306,**kw):
39+
import mysql.connector
40+
global engine
41+
if engine is not None:
42+
raise DBError('Engine is already initialized.')
43+
params = dict(user=user,password=password,database=database,host=host,port=port)
44+
defaults = dict(use_unicode=True, charset='utf8', collation='utf8_general_ci', autocommit=False)
45+
for k, v in defaults.iteritems():
46+
params[k] = kw.pop(k, v)
47+
params.update(kw)
48+
params['buffered'] = True
49+
engine = _Engine(lambda: mysql.connector.connect(**params))
50+
logging.info('Init mysql engine <%s> ok.' % hex(id(engine)))
51+
52+
53+
class _LasyConnection(object):
54+
55+
def __init__(self):
56+
self.connection = None
57+
58+
def cursor(self):
59+
if self.connection is None:
60+
connection = engine.connect()
61+
logging.info('open connection <%s>...' % hex(id(connection)))
62+
self.connection = connection
63+
return self.connection.cursor()
64+
65+
def commit(self):
66+
self.connection.commit()
67+
68+
def rollback(self):
69+
self.connection.rollback()
70+
71+
def cleanup(self):
72+
if self.connection:
73+
connection = self.connection
74+
self.connection = None
75+
logging.info('close connection <%s>' % hex(id(connection)))
76+
connection.close()
77+
78+
79+
class _DbCtx(threading.local):
80+
81+
def __init__(self):
82+
self.connection = None
83+
84+
def isInit(self):
85+
return not self.connection is None
86+
87+
def init(self):
88+
logging.info('open lasy connection...')
89+
self.connection = _LasyConnection()
90+
self.connection.cursor()
91+
92+
def cleanup(self):
93+
self.connection.cleanup()
94+
self.connection = None
95+
96+
def cursor(self):
97+
return self.connection.cursor()
98+
99+
100+
#thread-local db context
101+
_db_ctx = _DbCtx()
102+
103+
104+
class _ConnectionCtx(object):
105+
def __enter__(self):
106+
global _db_ctx
107+
self.should_cleanup = False
108+
if not _db_ctx.isInit():
109+
_db_ctx.init()
110+
self.should_cleanup = True
111+
return self
112+
113+
def __exit__(self, exctype, excvalue, traceback):
114+
global _db_ctx
115+
if self.should_cleanup:
116+
_db_ctx.cleanup()
117+
118+
119+
def with_connection(func):
120+
'''
121+
Decorator for reuse connection
122+
'''
123+
@functools.wraps(func)
124+
def _wrapper(*args,**kw):
125+
with _ConnectionCtx():
126+
return func(*args,**kw)
127+
return _wrapper
128+
129+
@with_connection
130+
def _update(sql,*args):
131+
global _db_ctx
132+
cursor = None
133+
sql = sql.replace('?','%s')
134+
logging.info('SQL: %s, ARGS: %s' % (sql,args))
135+
try:
136+
cursor = _db_ctx.connection.cursor()
137+
cursor.execute(sql,args)
138+
_db_ctx.connection.commit()
139+
r = cursor.rowcount
140+
return r
141+
finally:
142+
if cursor:
143+
cursor.close()
144+
145+
def insert(table,**kw):
146+
cols, args = zip(*kw.iteritems())
147+
sql = 'insert into `%s` (%s) values (%s)' % (table,','.join(['`%s`' % col for col in cols]),','.join(['?' for i in range(len(cols))]))
148+
print sql
149+
return _update(sql,*args)
150+
151+
152+
def update(sql,*args):
153+
return _update(sql,*args)
154+
155+
156+
def delete(table,**kw):
157+
cols, args = zip(*kw.iteritems())
158+
where = 'and'.join(['`%s`= %s' % (i,'?') for i,j in zip(cols,args)])
159+
sql = 'delete from `%s` where %s' % (table,where)
160+
return _update(sql,*args)
161+
162+
@with_connection
163+
def select(sql,first,*args):
164+
165+
global _db_ctx
166+
cursor = None
167+
sql = sql.replace('?','%s')
168+
logging.info('SQL:%s ,ARGS: %s' % (sql,args))
169+
try:
170+
cursor = _db_ctx.connection.cursor()
171+
cursor.execute(sql,args)
172+
names =[x[0] for x in cursor.description]
173+
if first:
174+
values = cursor.fetchone()
175+
print values
176+
if not values:
177+
return None
178+
return Dict(names,values)
179+
return [Dict(names,x) for x in cursor.fetchall()]
180+
finally:
181+
if cursor:
182+
cursor.close()
183+
184+
185+
186+
187+
188+
if __name__ == '__main__':
189+
logging.basicConfig(
190+
level=logging.DEBUG,
191+
format='%(asctime)s %(filename)s [line:%(lineno)d] method:(%(funcName)s) message:{%(message)s}'
192+
)
193+
create_engine('root','root','test')
194+
# print insert('user',id='2',name='lo')
195+
# print update('update user set name = ? where id = ?','good','1')
196+
# print delete('user',id='1')
197+
print select('select * from user',False)

0 commit comments

Comments
 (0)