摘自以前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'] = tab