Pyton实现SQLHelper

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

看了廖老师的教程实现了这个模块,按照自己的思路实现了一个,代码附下。

需要说名的几点:

1. dbcontext继承自threading.local,确保每个线程中都有独立的一个dbcontext对象,保证个用户数据独立。

2. connection对象是对dbcontext对象的一个封装,实现了getcursor方法,和关闭方法。

3. 现在的代码不够DRY,select方法和update方法调用了connection对象后都要手动关闭,可以实现一个装饰器,把要调用connection对象的代码块儿包裹起来,初始化和关闭connection对象的代码提取到装饰器中。下次补上。

代码附下:

1importMySQLdb,logging,threading,time,uuid2logging.basicConfig(level=logging.INFO,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S')34defnext_id(t=None):5'''6Return next id as 50-char string.78Args:9t: unix timestamp, default to None and using time.time().10'''11iftisNone:12t =time.time()13return'%015d%s000'% (int(t * 1000), uuid.uuid4().hex)1415classDict(dict):16def__init__(self,names=(),values=(),**args):17super(Dict,self).__init__(**args)18fork,vinzip(names,values):19self[k]=v20def__getattr__(self, item):21try:22returnself[item]23exceptKeyError:24raiseAttributeError('it has no attribute named %s'%(str(item),))25def__setattr__(self, key, value):26self[key]=value2728classdbcontext(threading.local):29def__init__(self):30self.db= MySQLdb.connect(host="localhost",port=3306,passwd='toor',user='root',db='xdyweb')31defgetdb(self):32returnself.db3334classconntection(object):35def__init__(self):36self.dbctx=dbcontext()37self.db=self.dbctx.getdb()38self.cursor=self.db.cursor()39defgetcursor(self):40returnself.cursor41defclose(self):42self.db.close()43self.cursor=None44def_select(sql,first,*args):45conn=conntection()46csr=conn.getcursor()47sql=sql.replace('?','%s')48values=csr.execute(sql,*args)49try:50ifcsr.description:51names=[x[0]forxincsr.description]52iffirst:53values=csr.fetchone()54ifvaluesisNone:55returnNone56returnDict(names,values)57return[Dict(names,x)forxincsr.fetchall()]58finally:59conn.close()6061defselect(sql,first,*args):62return_select(sql,first,*args)63defselect_one(sql,pk):64return_select(sql,True,pk)6566defupdate(sql,*args):67r'''68Execute update SQL.6970>>> u1 = dict(id=1000, name='Michael', email='michael@test.org', passwd='123456', last_modified=time.time())71>>> insert('user', **u1)72173>>> u2 = select_one('select * from user where id=?', 1000)74>>> u2.email75u'michael@test.org'76>>> u2.passwd77u'123456'78>>> update('update user set email=?, passwd=? where id=?', 'michael@example.org', '654321', 1000)79180>>> u3 = select_one('select * from user where id=?', 1000)81>>> u3.email82u'michael@example.org'83>>> u3.passwd84u'654321'85>>> update('update user set passwd=? where id=?', '***', '123\' or id=\'456')86087'''88conn=conntection()89csr=conn.getcursor()90sql=sql.replace('?','%s')9192try:93csr.execute(sql,args)94returncsr.rowcount95finally:96conn.close()97definsert(table,**kw):98'''99Execute insert SQL.100101>>> u1 = dict(id=2000, name='Bob', email='bob@test.org', passwd='bobobob', last_modified=time.time())102>>> insert('user', **u1)1031104>>> u2 = select_one('select * from user where id=?', 2000)105>>> u2.name106u'Bob'107>>> insert('user', **u2)108Traceback (most recent call last):109...110IntegrityError: 1062 (23000): Duplicate entry '2000' for key 'PRIMARY'111'''112cols, args = zip(*kw.iteritems())113sql ='insert into `%s` (%s) values (%s)'% (table,','.join(['`%s`'% colforcolincols]),','.join(['?'foriinrange(len(cols))]))114logging.info(sql)115returnupdate(sql,*args)116117defmain():118#db=MySQLdb.connect(host="localhost",port=3306,passwd='toor',user='root',db='xdyweb')119120#conn=conntection()121#c=conn.getcursor()122#r=c.execute("select * from users where email=%s",('sss@sss.sss',))123#logging.warning(r)124125#f=_select('select * from users where email =?',False,('sss@sss.sss',))126#logging.info(f)127#pass128129u1 = dict(id=2000, name='Bob', email='bob@test.org', passwd='bobobob', last_modified=time.time())130r=insert('user', **u1)131logging.info(r)132if__name__=="__main__":133main()

View Code

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航