• 【7.6】通过元类实现简单的orm


      1 #!/user/bin/env python
      2 # -*- coding:utf-8 -*-
      3 # 需求
      4 import numbers
      5 
      6 
      7 class Field:
      8     pass
      9 
     10 
     11 class IntField(Field):
     12     def __init__(self, db_column, min_value=None, max_value=None):
     13         self._value = None
     14         self.db_column = db_column
     15         self.min_value = min_value
     16         self.max_value = max_value
     17         if min_value is not None:
     18             if not isinstance(min_value, numbers.Integral):
     19                 raise ValueError('min_value must be int')
     20             elif min_value < 0:
     21                 raise ValueError('min_value must be positive int')
     22         if max_value is not None:
     23             if not isinstance(max_value, numbers.Integral):
     24                 raise ValueError('max_value must be int')
     25             elif min_value < 0:
     26                 raise ValueError('max_value must be positive int')
     27         if min_value is not None and max_value is not None:
     28             if min_value > max_value:
     29                 raise ValueError('min_value must be smaller than max_value')
     30 
     31     def __get__(self, instance, owner):
     32         return self._value
     33 
     34     def __set__(self, instance, value):
     35         if not isinstance(value, numbers.Integral):
     36             raise ValueError('int value need')
     37         if value < self.min_value or value > self.max_value:
     38             raise ValueError('value must between min_value and max_value')
     39         self._value = value
     40 
     41 
     42 class CharField(Field):
     43     def __init__(self, db_column, max_length=None):
     44         self._value = None
     45         self.db_column = db_column
     46         if max_length is None:
     47             raise ValueError('you must spcify max_length for CharField')
     48         self.max_length = max_length
     49 
     50     def __get__(self, instance, owner):
     51         return self._value
     52 
     53     def __set__(self, instance, value):
     54         if not isinstance(value, str):
     55             raise ValueError('string value need')
     56 
     57         if len(value) > self.max_length:
     58             raise ValueError('value len excess len of max_length')
     59         self._value = value
     60 
     61 
     62 class ModelMetaClass(type):
     63     def __new__(cls, name, bases, attrs, **kwargs):
     64         if name == 'BaseModel':
     65             return super().__new__(cls, name, bases, attrs, **kwargs)
     66         fields = {}
     67         for key, value in attrs.items():
     68             if isinstance(value, Field):
     69                 fields[key] = value
     70         attrs_meta = attrs.get('Meta', None)
     71         _meta = {}
     72         db_table = name.lower()
     73         if attrs_meta is not None:
     74             table = getattr(attrs_meta, 'db_table', None)
     75             if table is None:
     76                 db_table = table
     77         _meta['db_table'] = db_table
     78         attrs['_meta'] = _meta
     79         attrs['fields'] = fields
     80         del attrs['Meta']
     81         return super().__new__(cls, name, bases, attrs, **kwargs)
     82 
     83 
     84 class BaseModel(metaclass=ModelMetaClass):
     85     def __init__(self, *args, **kwargs):
     86         for key, value in kwargs.items():
     87             setattr(self, key, value)
     88         return super().__init__()
     89 
     90     def save(self):
     91         fields = []
     92         values = []
     93         for key, value in self.fields.items():
     94             db_column = value.db_column
     95             if db_column is None:
     96                 db_column = key.lower()
     97             fields.append(db_column)
     98             value = getattr(self, key)
     99             values.append(str(value))
    100 
    101         sql = 'insert {db_table}({fields}) value({values})'.format(db_table=self._meta['db_table'], fields=','.join(fields), values=','.join(values))
    102         print(sql)
    103 
    104 
    105 class User(BaseModel):
    106     name = CharField(db_column='name', max_length=10)
    107     age = IntField(db_column='age', min_value=0, max_value=100)
    108 
    109     class Meta:
    110         db_table = 'user'
    111 
    112 
    113 if __name__ == '__main__':
    114     user = User()
    115     user.name = 'zy'
    116     user.age = 21
    117     user.save()
    insert user(name,age) value(zy,21)
    

      

  • 相关阅读:
    sort-list leetcode C++
    sum-root-to-leaf-numbers leetcode C++
    sum-root-to-leaf-numbers leetcode C++
    path-sum-ii leetcode C++
    path-sum-ii leetcode C++
    0139 函数的两种声明方式
    0138 函数可以调用另外一个函数
    0137 函数案例:数组翻转、冒泡排序、判断闰年
    0136 JavaScript中 arguments 的使用
    0135 函数的返回值:return 语句、终止函数 、只能返回一个值、没有 return 返回 undefined、break &continue&return 的区别
  • 原文地址:https://www.cnblogs.com/zydeboke/p/11269854.html
Copyright © 2020-2023  润新知