Simple implementation of a thinkphp-like data model for MySQL operations using Python

Source: Internet
Author: User

From the previous CI implementation of the mall system, do the application needs to implement the data interface, it is implemented with Python.


Suppose there is a table tp_article

Id Title Type
1 Ha ha 1
2 Pattern Wansen Slope 1

Use the thinphp implementation to remove the type 1 data as follows

M ()->from (' tp_article ')->where (' type=1 ')->select ();


A package similar to the operation of MySQL is now implemented via Python

Db.select (' * '). FM (' Tp_article '). where (' type ', 1). All ()


Required: The DB module under Django


First implement the mydb.py file, placed in the core directory, the implementation of the model class file requires import

From django.db Import connectioncursor = Connection.cursor () "Simple function for one result sql" #返回一条结果def Fetchone (S QL):    cursor.execute (SQL)    try:        col_names = [row[0] for row in cursor.description]        rs = dict (Zip (col_ Names,cursor.fetchone ())            except:        rs = {}                  return RS
<pre name= "code" class= "Python" > #返回多条结果
def fetchall (SQL): Cursor.execute (sql) try:col_names = [row[0] for row in cursor.description] data = Cursor.fetchall () RS = [Dict (Zip (col_names,raw)) for raw in data] except:rs=[] return RS


then it is implementing the Model class file db_mysql.py


From Core.mydb  import *class Db_mysql (object):    ' Build sql ' '    sql= '    options={}    history=[]        def Select (self,fields):        select_list = Fields.split (', ')        self.options[' select ']=select_list        return self
    #实现from because the from is a python reserved keyword, so use FM instead
 def FM (        self,table): self.options[' from '] = table return self def where (Self,seg,*args): "'            SQL query of where tag ' try:where_list=self.options[' where '] except: Where_list=[] If Isinstance (SEG,STR): Try:where_list.append ({' key ': Seg, ' val ': args[0], ' Ty PE ': args[1]}) except:where_list.append ({' key ': Seg, ' val ': args[0], ' type ': False}) elif Isin Stance (SEG,DICT): for key in Seg.keys (): Where_list.append ({' key ': Key, ' Val ': Seg[key]}) se lf.options[' where ']= where_list return self 
    def where_in (self,key,val): If not isinstance (self.options[' where '],list): self.options[' where ']=[] self.options[' where '].append ({' key ': Key, ' Val ': Str (val), ' type ': ' in ') ' Return to ' Def ' like (self,key,wo RDS): If not isinstance (self.options[' where '],list): self.options[' where ']=[] self.options[' where        '].append ({' key ': Key, ' Val ': str (words), ' type ': ' Like '}) ' Return to ' Def ' join (self,table,on,type= ' left '):        self.options[' join ']= {' table ': Table, ' on ': On, ' type ': type} return self def limit (self,offset=0,size=0): offset = Int (offset) size = Int (size) if size = = 0:size=offset offset=0 se        lf.options[' limit ']= {' offset ': str (offset), ' size ': str (size)} return self def order (self,oby,desc= ' desc '): self.options[' order ']={' order ': Str (oby), ' desc ': str (DESC)} return self #组装sql就靠这个方法了 def combile_sql (sel f): "CoMbile Select SQL "If not isinstance (self.options[' select '],list): self.options[' select ']=[' * '] Self.sql= '. Join ([' SELECT ']) length = Len (self.options[' select ')) for I in range (length ): Fields = self.options[' SELECT '][i] if i==length-1: self.sql= '. Join ([Self.sql,fiel        DS, "]) break self.sql=". Join ([Self.sql,fields, ', ']) ' Combile from SQL        ' Self.sql= '. Join ([Self.sql, ' from ', self.options[' from '], ' "]) ' Combile join SQL        "' Try:if isinstance (self.options[' join '],dict): join_str = self.options[' Join '] Except:pass else:self.sql= '. Join ([self.sql,join_str[' type '], ' join ', join_str[' tabl E '], ' on ', join_str[' on ', ']) ' combile where SQL and where in SQL ' try : where_list= Self.options[' where '] except:where_list = [] else:if len (where_list):  Self.sql= '. Join ([Self.sql, ' where ']) count=0 for item in Where_list:if Count is 0:segment = ' else:segment = ' and ' count=count+ 1 if not item.get (' type ', False): Self.sql= '. Join ([self.sql,segment,item[' key '], ' = ', str ( Item[' Val '])]) elif item[' type '] is ' in ': self.sql= '. Join ([self.sql,segment,item[' key '] , ' In (', str (item[' Val '), ') ') ') elif item[' type '] was ' like ': self.sql= '. Join ([Self.sql            , segment,item[' key '], ' like% ', str (item[' Val '), '% ']) ' combile order SQL ' try: Order_dict = self.options[' order '] if Isinstance (order_dict,dict): self.sql= '. Join ([ Self.sql, ' ORDER by ', order_dict[' order '], ' ', order_dict[' desc ']]) except:pass "Combil e limit SQL ' try:self.sql= '. Join ([Self.sql, ' limit ', self.options[' limit '] [' offset '], ', ', sel             f.options[' limit ' [' size ']] self.history.append (self.sql) self.options = {} except Keyerror: Pass return self #查询操作, like TP Lee's Find def get (self,table=false): If not isinstance (tabl E,bool): self.options[' from '] Self.combile_sql () rs={} Try:rs = Fetchone (self. SQL) except Exception as E:print e print Self.sql self.sql= "return RS #查询        Operation, like Select Def All (Self,table=false) in TP: If not isinstance (table,bool): self.options[' from ']            Self.combile_sql () rs = [] Try:rs = Fetchall (self.sql) except Exception as E: Print e PrinT self.sql self.sql= "return RS #修改操作 def update (Self,table=false,*args): If not ISINs Tance (Table,bool): self.sql= ". Join ([' Update ', table, ' Set ']) Else:return False
<span style= "White-space:pre" ></span> #判断方法接收的参数是字符串还是字典, do different processing if isinstance (ARGS[0],STR): if Isinstance (ARGS[1],STR): val = ". Join ([" ' "", args[1], "'"]) Else:val = str (args[1            ]) Self.sql = '. Join ([self.sql,args[0], ' = ', Val, ']) elif isinstance (args[0],dict): count=0                    For key in Args[0].keys (): if count is 0:segment = ' else: Segment = ', ' If Isinstance (args[0][key],str): val = '. Join (["'", arg S[0][key], "'"]) Else:val = str (Args[0][key]) Self.sql = '. Join ([self.sq                 L,segment,key, ' = ', Val, ']) count = count+1 ' combile where SQL and where in SQL '            Try:where_list = self.options[' where '] except:where_list = [] Else: If Len (where_List): Self.sql= '. Join ([Self.sql, ' where ']) count=0 for item in Where_list:                If count is 0:segment = ' else:segment = ' and ' Count=count+1 if not item.get (' type ', False): Self.sql= '. Join ([self.sql,segment,i tem[' key '], ' = ', str (item[' Val ')]) elif item[' type '] is ' in ': self.sql= '. Join ([Self.sql, segment,item[' key '], ' in (', str (item[' Val '), ') ') elif item[' type '] was ' like ': self.sq  L= ". Join ([self.sql,segment,item[' key '], ' like% ', str (item[' Val ')"), '% ']) ' combile where SQL and where in SQL "' rs = Fetchone (self.sql) self.options = {} self.sql= ' return RS
 #插入操作 def Insert (self,table=false,seg={}): If not isinstance (table,bool): self.sql= ". Join ([' INSERT INTO ')            , table, "]) Else:return False if Isinstance (seg,dict): count=0 keystr="                Valstr= ' for key in Seg.keys (): if count is 0:segment = ' Else:segment = ', ' keystr = '. Join ([Keystr,segment,key]) if I Sinstance (SEG[KEY],STR): val = ". Join ([" ' "", Seg[key], "'"]) else:val = str (Seg[key]) Valstr = '. Join ([valstr,segment,val]) self.sql= '. Join ([Self.sql, ' (', Keystr, ') ', ' Values ', ' (', Valstr, ') ') rs = Fetchone (self.sql) self.options = {} self.sql= ' return Rs
    #删除操作 def Delete (self,table=false): If not isinstance (table,bool): self.sql= '. Join ([' Del Ete from ', table, ']) else:return False "combile where SQL and where in SQL '             ' try:where_list = self.options[' where '] except:where_list = [] Else: If Len (where_list): self.sql= ". Join ([Self.sql, ' where ']) count=0 for it EM in where_list:if count is 0:segment = ' else:s Egment = ' and ' count=count+1 if not item.get (' type ', False): Self.sql= ' . Join ([self.sql,segment,item[' key '], ' = ', str (item[' Val ')]) elif item[' type '] is ' in ': SE                    Lf.sql= '. Join ([self.sql,segment,item[' key '], ' in (', str (item[' Val ') '), ') ') elif item[' type '] was ' like ': Self.sQl= ". Join ([self.sql,segment,item[' key '], ' like% ', str (item[' Val ')"), '% ']) ' combile where SQL and where I N SQL "' rs = Fetchone (self.sql) self.options = {} self.sql=" return rs# test Db = db_m Ysql () db.select (' Attr_id,attr_name '). FM (' Hr_attribute '). where (' Attr_type ', 0). where_in (' attr_id ', ' 3,4,6 '). Join ( ' Goods as G ', ' g.id=a.id ', ' left '). Order (' attr_id '). Limit (3,5);D b.get ()

After testing, there is no big problem, if you have any questions, please let me know.


Simple implementation of a thinkphp-like data model for MySQL operations using Python

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.