• ❥纯手撸ORM❥


    from orm.mysql_class import MySql
    class Field(object):
        def __init__(self, name, field_type, primary_key, default):
            self.name = name
            self.field_type = field_type
            self.primary_key = primary_key
            self.default = default
    
    class StringField(Field):
        def __init__(self,name,field_type='varchar',primary_key=False,default=None):
            super(StringField, self).__init__(name, field_type, primary_key, default)
    
    class IntegerField(Field):
        def __init__(self,name,field_type='int',primary_key=False,default=0):
            super(IntegerField, self).__init__(name, field_type, primary_key, default)
    
    class MyMetaClass(type):
        def __new__(cls, class_name, class_bases, class_attrs):
            if class_name == 'Models':
                return type.__new__(cls, class_name, class_bases, class_attrs)
    
            table_name = class_attrs.get('table_name',class_name)
            primary_key = None
            mappings = {}
            for k, v in class_attrs.items():
                if isinstance(v,Field):
                    mappings[k] = v
                    if v.primary_key:
                        if primary_key:
                            raise TypeError('只能有一个主键')
                        primary_key = v.name
            for i in mappings:
                class_attrs.pop(i)
            if not primary_key:
                raise TypeError('没有主键')
            class_attrs['table_name'] = table_name
            class_attrs['primary_key'] = primary_key
            class_attrs['mappings'] = mappings
            return type.__new__(cls, class_name, class_bases, class_attrs)
    
    
    class Models(dict,metaclass=MyMetaClass):
        def __init__(self,**kwargs):
            super().__init__(**kwargs)
    
        def __getattr__(self, item):
            return self.get(item, '没有这个字段')
    
        def __setattr__(self, key, value):
            self[key] = value
    
        @classmethod
        def my_select(cls,**kwargs):
            md = MySql()
            if not kwargs:
                sql = "select * from %s"%cls.table_name
                res = md.select(sql)
            else:
                key = list(kwargs.keys())[0]
                values = kwargs.get(key)
                sql = "select * from %s where %s=?"%(cls.table_name,key)
                sql = sql.replace('?','%s')
                res = md.select(sql,values)
                print(res)
            if res:
                return [cls(**i) for i in res]
    
        def my_insert(self):
            ms = MySql()
            keys = []
            values = []
            wenhao = []
            for k,v in self.mappings.items():
                if not v.primary_key:
                    keys.append(v.name)
                    values.append(getattr(self,v.name,v.default))
                    wenhao.append('?')
            sql = "insert into %s(%s) values(%s)"%(self.table_name,','.join(keys),','.join(wenhao))
            sql = sql.replace('?','%s')
            ms.execute(sql,values)
    
        def my_update(self):
            ms = MySql()
            field = []
            values = []
            primary_key = None
            for k, v in self.mappings.items():
                if v.primary_key:
                    primary_key = getattr(self,v.name,v.default)
                else:
                    field.append(v.name+'=?')
                    values.append(getattr(self,v.name))
            sql = "update %s set %s where %s=%s"%(
                self.table_name,
                ','.join(field),
                self.primary_key,
                primary_key
            )
            print(self.primary_key)
            print(primary_key)
            sql = sql.replace('?','%s')
            ms.execute(sql,values)
  • 相关阅读:
    Python笔记_第四篇_高阶编程_再议装饰器和再议内置函数
    Python笔记_第四篇_高阶编程_实例化方法、静态方法、类方法和属性方法概念的解析。
    Python笔记_第四篇_高阶编程_二次封装
    Python笔记_第四篇_高阶编程_反射_(getattr,setattr,deattr,hasattr)
    Python笔记_第四篇_高阶编程_正则表达式_3.正则表达式深入
    Python笔记_第四篇_高阶编程_正则表达式_2.正则表达式入门
    Python笔记_第四篇_高阶编程_正则表达式_1.正则表达式简介(re模块)
    Python笔记_第四篇_高阶编程_检测_2.文档检测
    愿你的眼中总有光芒,活成你想要的模样!
    ruby-rails 环境搭建
  • 原文地址:https://www.cnblogs.com/lddragon/p/11683995.html
Copyright © 2020-2023  润新知