# coding:utf-

import pymysql

class Field(object):
pass class Expr(object):
def __init__(self, model, kwargs):
self.model = model
# How to deal with a non-dict parameter?
self.params = kwargs.values()
equations = [key + ' = %s' for key in kwargs.keys()]
self.where_expr = 'where ' + ' and '.join(equations) if len(equations) > else '' def update(self, **kwargs):
_keys = []
_params = []
for key, val in kwargs.iteritems():
if val is None or key not in self.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' for key in _keys]), self.where_expr)
return Database.execute(sql, _params) def limit(self, rows, offset=None):
self.where_expr += ' limit %s%s' % (
'%s, ' % offset if offset is not None else '', rows)
return self def select(self):
sql = 'select %s from %s %s;' % (', '.join(self.model.fields.keys()), self.model.db_table, self.where_expr)
for row in Database.execute(sql, self.params).fetchall():
inst = self.model()
for idx, f in enumerate(row):
setattr(inst, self.model.fields.keys()[idx], f)
yield inst def count(self):
sql = 'select count(*) from %s %s;' % (self.model.db_table, self.where_expr)
(row_cnt, ) = Database.execute(sql, self.params).fetchone()
return row_cnt class MetaModel(type):
db_table = None
fields = {} def __init__(cls, name, bases, attrs):
super(MetaModel, cls).__init__(name, bases, attrs)
fields = {}
for key, val in cls.__dict__.iteritems():
if isinstance(val, Field):
fields[key] = val
cls.fields = fields
cls.attrs = attrs class Model(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__)))
return Database.execute(insert, self.__dict__.values()) @classmethod
def where(cls, **kwargs):
return Expr(cls, kwargs) class Database(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', )),
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):
if not cls.conn or not cls.conn.open:
cls.connect(**cls.db_config)
try:
cls.conn.ping()
except pymysql.OperationalError:
cls.connect(**cls.db_config)
return cls.conn @classmethod
def execute(cls, *args):
cursor = cls.get_conn().cursor()
cursor.execute(*args)
return cursor def __del__(self):
if self.conn and self.conn.open:
self.conn.close() def execute_raw_sql(sql, params=None):
return Database.execute(sql, params) if params else Database.execute(sql)

python dbhelper(simple orm)的更多相关文章

  1. python下的orm基本操作(1)--Mysql下的CRUD简单操作(含源码DEMO)

    最近逐渐打算将工作的环境转移到ubuntu下,突然发现对于我来说,这ubuntu对于我这种上上网,收收邮件,写写博客,写写程序的时实在是太合适了,除了刚接触的时候会不怎么完全适应命令行及各种权限管理, ...

  2. 使用国内镜像通过pip安装python的一些包 Cannot fetch index base URL http://pypi.python.org/simple/

    原文地址:http://www.xuebuyuan.com/1157602.html 学习flask,安装virtualenv环境,这些带都ok,但是一安装包总是出错无法安装, 比如这样超时的问题: ...

  3. python 之路,Day11(上) - python mysql and ORM

    python 之路,Day11 - python mysql and ORM   本节内容 数据库介绍 mysql 数据库安装使用 mysql管理 mysql 数据类型 常用mysql命令 创建数据库 ...

  4. pip安装python包出现Cannot fetch index base URL http://pypi.python.org/simple/

    pipinstall***安装python包,出现 Cannot fetch index base URL  http://pypi.python.org/simple /错误提示或者直接安装不成功. ...

  5. 46 Simple Python Exercises-Very simple exercises

    46 Simple Python Exercises-Very simple exercises 4.Write a function that takes a character (i.e. a s ...

  6. python pymysql和orm

    pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同. 1. 安装 管理员打开cmd,切换到python的安装路径,进入到Scripts目录下(如:C:\Users\A ...

  7. python——Django(ORM连表操作)

    千呼万唤始出来~~~当当当,终于系统讲了django的ORM操作啦!!!这里记录的是django操作数据库表一对多.多对多的表创建及操作.对于操作,我们只记录连表相关的内容,介绍增加数据和查找数据,因 ...

  8. python decorator simple example

    Why we need the decorator in python ? Let's see a example: #!/usr/bin/python def fun_1(x): return x* ...

  9. Python-Day12 Python mysql and ORM

    一.Mysql数据库 1.什么是数据库? 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库,    每个数据库都有一个或多个不同的API用于创建,访问,管理,搜索和复制所保存的数据 ...

随机推荐

  1. 【贪心】【TOJ4107】【A simple problem】

    Given three integers n(1≤n≤1018), m(1≤m≤105), k(1≤k≤1018). you should find a list of integer A1,A2,- ...

  2. 只获取linux ip的命令

    ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'

  3. 关于C#重写,隐藏的一些事

    第一次开始写技术博客,不知该从何处下手,本人算是菜鸟一枚,每每看到博客园里面的大牛们分享的技术文章,只能望其项背,高不可攀.但细细想来,若不尝试着从小处从低处慢慢去积累分享,想要成为技术大牛也只能沦为 ...

  4. Web QQ自动强制加好友代码

    也许见过强行聊天的代码:  tencent://Message/?Uin=574201314&websiteName=www.oicqzone.com&Menu=yes 但是你应该不知 ...

  5. python image show()方法的预览问题

      在windows下面使用PIL中Image的show()函数时,执行下列代码: from PIL import Image img = Image.open("1.png") ...

  6. Python学习之编写登陆接口(Day1,作业一)

    作业一:编写登陆接口 输入用户名密码 认证成功后显示欢迎信息 输错三次后锁定(下次登陆还是锁定) 知识点:while循环,for循环,文件操作,if判断,列表操作 思路: 1.登陆,三次登陆失败,锁定 ...

  7. js cookie读取

    /**存放Cookies: 两个参数,一个是cookie的名子,一个是值*/ function SetCookie(name,value){ var Days = 30; //此 cookie 将被保 ...

  8. [C#]6.0新特性浅谈

    原文:[C#]6.0新特性浅谈 C#6.0出来也有很长一段时间了,虽然新的特性和语法趋于稳定,但是对于大多数程序猿来说,想在工作中用上C#6.0估计还得等上不短的一段时间.所以现在再来聊一聊新版本带来 ...

  9. 中国市场 Android App 兼容性报告

      由于手机操作系统的不同,以及操作系统版本之间的差异,使得真机测试这个过程尤其复杂,涉及终端.人员.工具.时间.管理等方面的问题,Android系统的设备因操作系统多样性和终端类型的庞杂,问题尤为复 ...

  10. CSS实现页面背景自动切换功能

    From here:http://xiaomiya.iteye.com/blog/2047728 请看效果图: 完整代码如下: <!DOCTYPE HTML> <html> & ...