您现在的位置是:课程教程文章
python简单实现了一个ORM
2023-12-14 22:17课程教程文章 人已围观
(推荐操作系统:windows7系统、Python 3.9.1、DELL G3电脑。)
1、定义Field类,它负责保存数据库表的字段名和字段的类型:
class Field(object): def __init__(self, name, column_type): self.name = name self.column_type = column_type
2、在Field的基础上,进一步定义各种具体类型的Field,比如StringField,IntegerField等等:
class StringField(Field): def __init__(self, name, max_length): super(StringField, self).__init__(name, 'varchar(%d)' % max_length) class IntegerField(Field): def __init__(self, name): super(IntegerField, self).__init__(name, 'int')
3、下一步,就是编写最复杂的ModelMetaclass了:
class ModelMetaclass(type): def __new__(cls, name, bases, attrs): if name == 'Model': return type.__new__(cls, name, bases, attrs) print('Found model: %s' % name) 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__'] = name return type.__new__(cls, name, bases, attrs)
4、创建User类,并调用save方法,保存:
class User(Model): id = IntegerField('id') name = StringField('username', max_length=48) email = StringField('email', max_length=128) password = StringField('password', max_length=24) # 创建一个实例: u = User(id=12345, name='xiaoming', email='xiaoming@xiaomi.com', password='test') # 保存到数据库: u.save()
以上就是python简单实现了一个ORM,希望能对大家有所帮助。更多Python学习指路:python基础教程
上一篇:python中*args的使用
下一篇:没有了