python 简单的ORM蟒蛇
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 简单的ORM蟒蛇相关的知识,希望对你有一定的参考价值。
#coding:utf-8
class Field(object):
def __init__(self,column_type, max_length, **kwargs):
self.column_type = column_type
self.max_length = max_length
self.default = None
if kwargs:
for k,v in kwargs.items():
if hasattr(self,k):
setattr(self,k,v)
def __str__(self):
return '<%s>'%(self.__class__.__name__)
'''
Field Type
'''
class StringField(Field):
def __init__(self, max_length=30, **kwargs):
# column_type:类型varchar,max_length:长度
super(StringField,self).__init__(column_type='varchar({})'.format(max_length),max_length=max_length,**kwargs)
class IntegerField(Field):
def __init__(self, **kwargs):
super(IntegerField,self).__init__(column_type='bigint', max_length=11)
class ModelMetaclass(type):
def __new__(cls, name, bases, attrs):
if name == 'Model':
return type.__new__(cls, name,bases,attrs)
mappings = dict()
for k,v in attrs.items():
if isinstance(v, Field):
mappings[k] = v
for k in mappings.keys():
attrs.pop(k)
attrs['__mappings__'] = mappings
attrs['__table__'] = attrs.get('Meta').table or name
return type.__new__(cls, name, bases, attrs)
from functools import reduce
class Model(dict):
__metaclass__ = ModelMetaclass
def __init__(self,**kw):
super(Model, self).__init__(**kw)
def __getattr__(self, item):
try:
return self[item]
except:
raise AttributeError(r"'Model' 对象没有%s属性"%item)
def __setattr__(self, key, value):
self[key] = value
def save(self):
'''
insert data in MySQL Table
:return: SQL about insert data
'''
fields = []
params = []
for k,v in self.__mappings__.items():
fields.append(k)
params.append(getattr(self,k,v.default))
sql = 'insert into {} ({}) values ({})'.format(self.__table__, self.join(fields), self.join(params))
print('SQL:%s'%sql)
return sql
def join(self, attrs, pattern=','):
return reduce(lambda x,y:'{}{}{}'.format(x,pattern,y),attrs)
'''
Test Model
'''
class User(Model):
class Meta:
table='users'
id = IntegerField()
name = StringField()
email = StringField(max_length=50, default='ayuliao@xx.com')
password = StringField(max_length=50)
if __name__ == '__main__':
u = User(id=12345, name='ayuliao', email='ayuliao@orm.org', password='my-pwd')
u.save()
以上是关于python 简单的ORM蟒蛇的主要内容,如果未能解决你的问题,请参考以下文章