[python] ORM 第一次注释

不懂的东西还太多,就当是自己监督自己吧

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'Michael Liao'

import asyncio, logging

import aiomysql

def log(sql, args=()):
    logging.info('SQL: %s' % sql)
#用来打印sql的?args没有用到。

async def create_pool(loop, **kw):
    # 建立一个异步io的连接池
    logging.info('create database connection pool...')
    # logging 的东西只是打印日志的
    global __pool
    # 这个pool的即使全局变量,他又想不让其他人调用
    # 创建的方法就是 aiomysql.create_pool
    #kw的得取方法倒是知道了,it is kw.get('host','default')
    #if do not have defaultvalue, just kw['port']
    __pool = await aiomysql.create_pool(
        host=kw.get('host', 'localhost'),
        port=kw.get('port', 3306),
        user=kw['user'],
        password=kw['password'],
        db=kw['db'],
        charset=kw.get('charset', 'utf8'),
        autocommit=kw.get('autocommit', True),
        maxsize=kw.get('maxsize', 10),
        minsize=kw.get('minsize', 1),
        loop=loop
        #这个 loop = loop get不到。
    )

async def select(sql, args, size=None):
    # all the opreating nead the asyncio
    log(sql, args)
    # 这个以后已经拼接好了???
    global __pool
    async with __pool.get() as conn:
        #连接上,然后使用这个连接的get方法,as 为conn
        async with conn.cursor(aiomysql.DictCursor) as cur:
            #使用conn的 cursor AS 为 cur
            await cur.execute(sql.replace('?', '%s'), args or ())
            #游标执行占位符转换 ‘?’ → ‘%s’
            if size:
                #这个 size 哪里来的啊???
                #大哥,上边的size已经定义出来了。
                #None 就和False一样
                rs = await cur.fetchmany(size)
            else:
                rs = await cur.fetchall()
        logging.info('rows returned: %s' % len(rs))
        #这里就是返回值了
        return rs
        # rs 就是这个rows

async def execute(sql, args, autocommit=True):
    log(sql)
    #这里就是sql中的执行,好像还不是commit
    async with __pool.get() as conn:
        #仍然是用实例化出来的__pool 的get函数来建立一个连接 conn
        if not autocommit:
            #不太清楚在什么情况下这个autocommit 会 = False
            await conn.begin()
        try:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                #还是用连接创建游标
                await cur.execute(sql.replace('?', '%s'), args)
                #替换cursor的占位符
                affected = cur.rowcount
            if not autocommit:
                #这个 atuocommit的作用还是没明白
                await conn.commit()
        except BaseException as e:
            if not autocommit:
                await conn.rollback()
            raise
        return affected

def create_args_string(num):
    #创建评论参数字符串???
    L = []
    for n in range(num):
        L.append('?')
    return ', '.join(L)

class Field(object):
    #类型的被继承类

    def __init__(self, name, column_type, primary_key, default):
        self.name = name
        self.column_type = column_type
        self.primary_key = primary_key
        self.default = default

    def __str__(self):
        return '<%s, %s:%s>' % (self.__class__.__name__, self.column_type, self.name)

class StringField(Field):
    #字符,全都继承了Field

    def __init__(self, name=None, primary_key=False, default=None, ddl='varchar(100)'):
        super().__init__(name, ddl, primary_key, default)

class BooleanField(Field):
    #布尔

    def __init__(self, name=None, default=False):
        super().__init__(name, 'boolean', False, default)

class IntegerField(Field):
    #整型

    def __init__(self, name=None, primary_key=False, default=0):
        super().__init__(name, 'bigint', primary_key, default)

class FloatField(Field):
    #浮点

    def __init__(self, name=None, primary_key=False, default=0.0):
        super().__init__(name, 'real', primary_key, default)

class TextField(Field):
    #文本

    def __init__(self, name=None, default=None):
        super().__init__(name, 'text', False, default)

class ModelMetaclass(type):
    #继承type

    def __new__(cls, name, bases, attrs):
        # 这应该是新建方法
        if name=='Model':
            return type.__new__(cls, name, bases, attrs)
        #如果name 为 Model 我直接return type的 new方法???
        tableName = attrs.get('__table__', None) or name
        # 这个attr 是和**kw 的get 是一个意思吗??
        logging.info('found model: %s (table: %s)' % (name, tableName))
        #打印这个table
        mappings = dict()
        #把mappings 定义出来[]
        fields = []
        primaryKey = None
        #一直没太明白这个 primaryKey 的含义。
        for k, v in attrs.items():
            # attr的 type是??
            if isinstance(v, Field):
                logging.info('  found mapping: %s ==> %s' % (k, v))
                mappings[k] = v
                #用mappings 建立这个k v 的对应关系
                if v.primary_key:
                    # 找到主键: fengge的注释
                    #这里要处理我前边是for 出来的
                    if primaryKey:
                        #也就是说我这里默认不raise这个Error
                        raise StandardError('Duplicate primary key for field: %s' % k)
                        #!!!不知道为啥我这里的StandardError 报错了。
                    primaryKey = k
                    #这个时候我的 primaryKey 复制为k 就好比id
                else:
                    fields.append(k)
                    #如果不是主键,就简单的append进去
                    #但是主键好像没有被append啊
        if not primaryKey:
            raise StandardError('Primary key not found.')
            # !!!不知道为啥我这里的StandardError 报错了。
            #这里我看明白了,就是没找到主键
        for k in mappings.keys():
            attrs.pop(k)
            #这里为啥要把attrs里边的k pop出来?
            #而且mappings.key??? 还只有这两个地方有
        escaped_fields = list(map(lambda f: '`%s`' % f, fields))
        #这里是将fields 里边的所有sql 都给处理成 `sql` ??
        #明白了,attrs是dict
        attrs['__mappings__'] = mappings # 保存属性和列的映射关系
        attrs['__table__'] = tableName
        attrs['__primary_key__'] = primaryKey # 主键属性名
        attrs['__fields__'] = fields # 除主键外的属性名
        attrs['__select__'] = 'select `%s`, %s from `%s`' % (primaryKey, ', '.join(escaped_fields), tableName)
        attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' % (tableName, ', '.join(escaped_fields), primaryKey, create_args_string(len(escaped_fields) + 1))
        attrs['__update__'] = 'update `%s` set %s where `%s`=?' % (tableName, ', '.join(map(lambda f: '`%s`=?' % (mappings.get(f).name or f), fields)), primaryKey)
        attrs['__delete__'] = 'delete from `%s` where `%s`=?' % (tableName, primaryKey)
        # 这是他们的4个基础语句  那 left join 哪些呢??
        return type.__new__(cls, name, bases, attrs)

class Model(dict, metaclass=ModelMetaclass):
    #实例化Model 的时候 也顺带着将ModelMetaclass 也实例化出来了?

    def __init__(self, **kw):
        super(Model, self).__init__(**kw)
        #这里是说继承父类的所有参数吗?

    def __getattr__(self, key):
        try:
            return self[key]
            #getattr的时候return
        except KeyError:
            raise AttributeError(r"'Model' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value
        #set的时候直接把value也传过来了。

    def getValue(self, key):
        return getattr(self, key, None)

    def getValueOrDefault(self, key):
        value = getattr(self, key, None)
        if value is None:
            field = self.__mappings__[key]
            #如果是空就mappings??
            if field.default is not None:
                value = field.default() if callable(field.default) else field.default
                #如果不是空 就置给value
                logging.debug('using default value for %s: %s' % (key, str(value)))
                setattr(self, key, value)
                #然后还要setattr
        return value

    @classmethod
    async def findAll(cls, where=None, args=None, **kw):
        ' find objects by where clause. '
        sql = [cls.__select__]
        if where:
            sql.append('where')
            sql.append(where)
            #这里是处理where语句的??
        if args is None:
            args = []
        orderBy = kw.get('orderBy', None)
        if orderBy:
            sql.append('order by')
            sql.append(orderBy)
            #处理 orderby?
        limit = kw.get('limit', None)
        if limit is not None:
            sql.append('limit')
            #这里的limit 是啥啊。。。
            if isinstance(limit, int):
                sql.append('?')
                args.append(limit)
            elif isinstance(limit, tuple) and len(limit) == 2:
                sql.append('?, ?')
                args.extend(limit)
            else:
                raise ValueError('Invalid limit value: %s' % str(limit))
        rs = await select(' '.join(sql), args)
        return [cls(**r) for r in rs]

    @classmethod
    async def findNumber(cls, selectField, where=None, args=None):
        ' find number by select and where. '
        #为了查找什么number呢?
        sql = ['select %s _num_ from `%s`' % (selectField, cls.__table__)]
        if where:
            sql.append('where')
            sql.append(where)
        rs = await select(' '.join(sql), args, 1)
        if len(rs) == 0:
            return None
        return rs[0]['_num_']

    @classmethod
    async def find(cls, pk):
        ' find object by primary key. '
        rs = await select('%s where `%s`=?' % (cls.__select__, cls.__primary_key__), [pk], 1)
        if len(rs) == 0:
            return None
        return cls(**rs[0])

    async def save(self):
        args = list(map(self.getValueOrDefault, self.__fields__))
        args.append(self.getValueOrDefault(self.__primary_key__))
        rows = await execute(self.__insert__, args)
        if rows != 1:
            logging.warn('failed to insert record: affected rows: %s' % rows)

    async def update(self):
        args = list(map(self.getValue, self.__fields__))
        args.append(self.getValue(self.__primary_key__))
        rows = await execute(self.__update__, args)
        if rows != 1:
            logging.warn('failed to update by primary key: affected rows: %s' % rows)

    async def remove(self):
        args = [self.getValue(self.__primary_key__)]
        rows = await execute(self.__delete__, args)
        if rows != 1:
            logging.warn('failed to remove by primary key: affected rows: %s' % rows)
原文地址:https://www.cnblogs.com/danjawwi/p/6225352.html