Python DBHelper (Simple orm)

Source: Internet
Author: User

# coding:utf-8Import PymysqlclassField (Object): PassclassEXPR (Object): Def __init__ (self, model, Kwargs): Self.model=Model # How to deal with a non-dict parameter?Self .params=kwargs.values () equations= [key +'=%s'  forKeyinchKwargs.keys ()] self.where_expr='where'+' and'. Join (equations)ifLen (equations) >0 Else "'def update (self,**Kwargs): _keys=[] _params= []         forKey, ValinchKwargs.iteritems ():ifVal isNone or Key notinchSelf.model.fields:Continue_keys.append (Key) _params.append (Val) _params.extend (self.params) SQL='Update%s set%s%s;'%(self.model.db_table,', '. join ([key +'=%s'  forKeyinch_keys]), self.where_expr)returndatabase.execute (SQL, _params) def limit (self, rows, offset=None): self.where_expr+='Limit%s%s'% (            '%s,'% OffsetifOffset isNot NoneElse "', rows)returnSelf defSelect(self): SQL='Select%s from%s%s;'% (', '. Join (Self.model.fields.keys ()), self.model.db_table, self.where_expr) forRowinchDatabase.execute (SQL, self.params). Fetchall (): Inst=Self.model () forIDX, FinchEnumerate (Row): SetAttr (Inst, Self.model.fields.keys () [IDX], F)yieldInst def count (self): SQL='Select COUNT (*) from%s%s;'%(Self.model.db_table, self.where_expr) (row_cnt,)= Database.execute (sql, self.params). Fetchone ()returnrow_cntclassMetamodel (type): Db_table=None Fields={} def __init__ (CLS, name, bases, Attrs): Super (Metamodel, CLS). __INIT__ (name, bases, attrs) fields = {}         forKey, ValinchCls.__dict__.iteritems ():ifIsinstance (Val, Field): Fields[key]=Val Cls.fields=Fields Cls.attrs=AttrsclassModel (Object): __metaclass__=Metamodel def Save (self): Insert='Insert ignore into%s (%s) values (%s);'%(self.db_table,', '. Join (Self.__dict__.keys ()),', '. Join (['%s'] *Len (self.__dict__))) returndatabase.execute (INSERT, self.__dict__.values ()) @classmethod defwhere(CLS, * *Kwargs):returnExpr (CLS, Kwargs)classDatabase (Object): Autocommit=True Conn=None Db_config={} @classmethod def connect (CLS,**db_config): Cls.conn= Pymysql.connect (host=db_config.Get('Host','localhost'), port=int(Db_config.Get('Port',3306)), user=db_config.Get('User','Root'), Passwd=db_config.Get('Password',"'), DB=db_config.Get('Database','Test'), Charset=db_config.Get('CharSet','UTF8') ) Cls.conn.autocommit (cls.autocommit) cls.db_config.update (db_config) @classmethod def get_conn ( CLS):ifNot Cls.conn or not Cls.conn.open:cls.connect (**cls.db_config)Try: cls.conn.ping () except Pymysql. OperationalError:cls.connect (**cls.db_config)returncls.conn @classmethod def execute (CLS,*args): Cursor=cls.get_conn (). Cursor () Cursor.execute (*args)returncursor def __del__ (self):ifSelf.conn and Self.conn.open:self.conn.close () def execute_raw_sql (SQL,params=None):returnDatabase.execute (SQL,params)if params ElseDatabase.execute (SQL)

Python DBHelper (Simple orm)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.