用python简单实现类似thinkphp的针对Mysql操作的数据模型

摘自以前CI实现的商城系统,做APP时需要实现数据接口,便用python实现了。

假设有表tp_article

id title type
1 哈哈 1
2 图样涂森坡 1

使用thinphp实现取出type为1的数据如下

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

现通过python实现类似对mysql进行操作的封装

DB.select(‘*‘).fm(‘tp_article‘).where(‘type‘,1).all()

需要:django下的db模块

首先实现 mydb.py 文件,放于core目录下,实现模型类文件时需要import

from django.db import connection
cursor = connection.cursor()
'''
Simple function for one result sql
'''
#返回一条结果
def fetchone(sql):
    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


然后就是实现模型类文件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,因为from是python保留关键词,所以用fm代替
    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],'type':args[1]})
            except:
                where_list.append({'key':seg,'val':args[0],'type':False})
        elif isinstance(seg,dict):
            for key in seg.keys():
                where_list.append({'key':key,'val':seg[key]})

        self.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 self

    def like(self,key,words):
        if not isinstance(self.options['where'],list):
            self.options['where']=[]
        self.options['where'].append({'key':key,'val':str(words),'type':'like'})
        return self

    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
        self.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(self):
        '''
        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,fields,' '])
                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['table'],' 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'] is '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

        '''
        combile limit sql
        '''
        try:
            self.sql=''.join([self.sql,' limit ',self.options['limit']['offset'],',',self.options['limit']['size']])
            self.history.append(self.sql)
            self.options = {}
        except KeyError:
            pass

        return self

   #查询操作,类似tp李的find
    def get(self,table=False):
        if not isinstance(table,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
    #查询操作,类似tp里的select
    def all(self,table=False):
        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 isinstance(table,bool):
            self.sql=''.join(['update ',table,' set '])
        else:
            return False
<span style="white-space:pre">	</span>#判断方法接收的参数是字符串还是字典,做不同处理
        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(["'",args[0][key],"'"])
                else:
                    val = str(args[0][key])
                self.sql = ''.join([self.sql,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,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'] is 'like':
                    self.sql=''.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 isinstance(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(['delete 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 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'] is 'like':
                    self.sql=''.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
#测试
DB = Db_mysql()
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);
DB.get()

经测试,没有什么大问题,如果有问题建议请告诉我哦

时间: 2024-10-15 10:57:50

用python简单实现类似thinkphp的针对Mysql操作的数据模型的相关文章

python学习道路(day12note)(mysql操作,python链接mysql,redis)

1,针对mysql操作 1 SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpass'); 设置密码 2 update user set password=passworD("test") where user='root';修改密码 3 flush privileges; 4 grant all on *.* to [email protected]'%' identified by 'your_password'; 5 mysq

python网络爬虫入门(二)——用python简单实现调用谷歌翻译

最近在看国外的文档,有些生词不认识.就用谷歌翻译来理解,用着用着闲来无事就按F12查看了下页面的源代码.发现可以用python简单的实现下谷歌翻译的页面功能.于是先上网搜下有没有类似的文章博客,发现几篇不错的,于是参考其他代码与自己的思路,简单的实现了下翻译的功能,代码如下: import re import urllib,urllib2 #----------模拟浏览器的行为,向谷歌翻译发送数据,然后抓取翻译结果,这就是大概的思路------- def Gtranslate(text): #t

Python简单爬虫入门二

接着上一次爬虫我们继续研究BeautifulSoup Python简单爬虫入门一 上一次我们爬虫我们已经成功的爬下了网页的源代码,那么这一次我们将继续来写怎么抓去具体想要的元素 首先回顾以下我们BeautifulSoup的基本结构如下 #!/usr/bin/env python # -*-coding:utf-8 -*- from bs4 import BeautifulSoup import requests headers = { 'User-Agent':'Mozilla/5.0 (Win

python简单学------------python函数

如果在开发程序时,需要某块代码多次,但是为了提高编写的效率以及代码的重用,所以把具有独立功能的代码块组织为一个小模块,这就是函数 函数定义和调用 <1>定义函数 定义函数的格式如下: def 函数名(): 代码 demo: # 定义一个函数,能够完成打印信息的功能 def printInfo(): print '------------------------------------' print ' 人生苦短,我用Python' print '------------------------

制作类似ThinkPHP框架中的PATHINFO模式功能(二)

距离上一次发布的<制作类似ThinkPHP框架中的PATHINFO模式功能>(文章地址:http://www.cnblogs.com/phpstudy2015-6/p/6242700.html)已经过去好多天了,今晚就将剩下的一些东西扫尾吧. 上一篇文章已经实现了PATHINFO模式的URL,即我们访问MVC模式搭建的站点时,只需要在域名后面加上(/module/controller/action)即可,很智能化.并且通过new Object时的自动触发函数实现类文件的自动载入,因此只要我们搭

Python简单操作笔记

Python 类型转换 str(),repr()|format() : 将非字符类型转成子串 int() : 转为整形 float() : 转为浮点型 list(s) : 将字串s转成列表 tuple(s) : 将字串s转成元组 set(s) : 将字串s转成集合 frozenset(s) : 将字串s转成不可变集合 dict(s) : 创建字典 其d必须是(key,value)的元组序列; chr(x) : 将整形转成字符 ord(x) : 将字符转成整形 hex(x) : 将整形转换成16进

Python简单实现基于VSM的余弦相似度计算

在知识图谱构建阶段的实体对齐和属性值决策.判断一篇文章是否是你喜欢的文章.比较两篇文章的相似性等实例中,都涉及到了向量空间模型(Vector Space Model,简称VSM)和余弦相似度计算相关知识.        这篇文章主要是先叙述VSM和余弦相似度相关理论知识,然后引用阮一峰大神的例子进行解释,最后通过Python简单实现百度百科和互动百科Infobox的余弦相似度计算. 一. 基础知识 第一部分参考我的文章: 基于VSM的命名实体识别.歧义消解和指代消解 第一步,向量空间模型VSM 

Python 简单爬虫

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import os import time import webbrowser as web import random count = random.randint(20,40) j = 0 while j < count:     i = 0     while i <= 5:         web.open_new_tab('http://www.cnblogs.com/evilxr/p/37642

【美妙的Python之中的一个】Python简单介绍及环境搭建

美妙的Python之Python简单介绍及安装         简而言之: Python 是能你无限惊喜的语言,与众不同.             1.Python:          Python英文意思为蟒蛇,故又称为蟒蛇语言,在图标设计上有所体现,贵铎·范·罗萨姆(Guido van Rossum)于1989年创立.Python的特质,简单,优雅,健壮,继承传统编程语言的强大性与通用性,同一时候兼具简单脚本的简单性.         Python的哲学:仅仅用一种方法,最好是仅仅有一种方法