Skip to content

Commit

Permalink
使用元类替换之前的装饰器方式
Browse files Browse the repository at this point in the history
  • Loading branch information
wuranxu committed Jul 28, 2022
1 parent 9d2b5c5 commit 98821ee
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 30 deletions.
40 changes: 23 additions & 17 deletions app/crud/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,15 @@
from config import Config


class Mapper(object):
log = None
model = None
class Mapper(type):
__log__ = None
__model__ = None

def __new__(mcs, name, bases, attrs):
res = super().__new__(mcs, name, bases, attrs)
mcs.__log__ = attrs['__log__']
mcs.__model__ = attrs['__model__']
return res

@classmethod
@RedisHelper.cache("dao")
Expand All @@ -49,7 +55,7 @@ async def list_record(cls, condition=None, **kwargs):
return result.scalars().all()
except Exception as e:
# 这边调用cls本身的log参数,写入日志+抛出异常
cls.log.error(f"获取{cls.model}列表失败, error: {e}")
cls.__log__.error(f"获取{cls.__model__}列表失败, error: {e}")
raise Exception(f"获取数据失败")

@classmethod
Expand All @@ -67,14 +73,14 @@ async def list_record_with_pagination(cls, page, size, **kwargs):
sql = cls.query_wrapper(**kwargs)
return await DatabaseHelper.pagination(page, size, session, sql)
except Exception as e:
cls.log.error(f"获取{cls.model}列表失败, error: {e}")
cls.__log__.error(f"获取{cls.__model__}列表失败, error: {e}")
raise Exception(f"获取数据失败")

@classmethod
def query_wrapper(cls, condition=None, **kwargs):
conditions = condition if condition else list()
if getattr(cls.model, "deleted_at", None):
conditions.append(getattr(cls.model, "deleted_at") == 0)
if getattr(cls.__model__, "deleted_at", None):
conditions.append(getattr(cls.__model__, "deleted_at") == 0)
_sort = kwargs.get("_sort")
if _sort is not None:
# 需要去掉desc,不然会影响之前的sql执行
Expand All @@ -86,9 +92,9 @@ def query_wrapper(cls, condition=None, **kwargs):
if like and len(v) == 2:
continue
# 如果是like模式,则使用Model.字段.like 否则用 Model.字段 等于
DatabaseHelper.where(v, getattr(cls.model, k).like(v) if like else getattr(cls.model, k) == v,
DatabaseHelper.where(v, getattr(cls.__model__, k).like(v) if like else getattr(cls.__model__, k) == v,
conditions)
sql = select(cls.model).where(*conditions)
sql = select(cls.__model__).where(*conditions)
if _sort and isinstance(_sort, tuple):
for d in _sort:
sql = getattr(sql, "order_by")(d)
Expand All @@ -107,7 +113,7 @@ async def query_record(cls, session=None, **kwargs):
result = await session.execute(sql)
return result.scalars().first()
except Exception as e:
cls.log.error(f"查询{cls.model}失败, error: {e}")
cls.__log__.error(f"查询{cls.__model__}失败, error: {e}")
raise Exception(f"查询记录失败")

@classmethod
Expand Down Expand Up @@ -136,7 +142,7 @@ async def insert_record(cls, model, log=False, ss=None):
key=model.id))
return model
except Exception as e:
cls.log.error(f"添加{cls.model}记录失败, error: {e}")
cls.__log__.error(f"添加{cls.__model__}记录失败, error: {e}")
raise Exception(f"添加记录失败")

@classmethod
Expand All @@ -145,11 +151,11 @@ async def update_by_map(cls, user, *condition, **kwargs):
try:
async with async_session() as session:
async with session.begin():
sql = update(cls.model).where(*condition).values(**kwargs, updated_at=datetime.now(),
sql = update(cls.__model__).where(*condition).values(**kwargs, updated_at=datetime.now(),
update_user=user)
await session.execute(sql)
except Exception as e:
cls.log.error(f"更新数据失败: {e}")
cls.__log__.error(f"更新数据失败: {e}")
raise Exception("更新数据失败")

@classmethod
Expand All @@ -174,7 +180,7 @@ async def update_record_by_id(cls, user: int, model, not_null=False, log=False):
changed=changed))
return now
except Exception as e:
cls.log.error(f"更新{cls.model}记录失败, error: {e}")
cls.__log__.error(f"更新{cls.__model__}记录失败, error: {e}")
raise Exception(f"更新数据失败")

@classmethod
Expand Down Expand Up @@ -216,7 +222,7 @@ async def delete_record_by_id(cls, session, user: int, value: int, log=True, key
async with session.begin():
return await cls._inner_delete(session, user, value, log, key, exists)
except Exception as e:
cls.log.exception(f"删除{cls.model.__name__}记录失败: \n{e}")
cls.__log__.exception(f"删除{cls.__model__.__name__}记录失败: \n{e}")
raise Exception(f"删除失败")

@classmethod
Expand All @@ -237,7 +243,7 @@ async def delete_records(cls, session, user, id_list: List[int], column="id", lo
await asyncio.create_task(
cls.insert_log(session, user, OperationType.DELETE, original, key=id_))
except Exception as e:
cls.log.exception(f"删除{cls.model}记录失败, error: {e}")
cls.__log__.exception(f"删除{cls.__model__}记录失败, error: {e}")
raise Exception(f"删除记录失败")

@classmethod
Expand Down Expand Up @@ -428,7 +434,7 @@ async def delete_by_id(cls, id):
raise Exception("记录不存在")
session.delete(original)
except Exception as e:
cls.log.error(f"逻辑删除{cls.model}记录失败, error: {e}")
cls.__log__.error(f"逻辑删除{cls.__model__}记录失败, error: {e}")
raise Exception(f"删除记录失败")


Expand Down
7 changes: 3 additions & 4 deletions app/crud/config/AddressDao.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
from sqlalchemy import select

from app.crud import Mapper
from app.middleware.RedisManager import RedisHelper
from app.models import async_session
from app.models.address import PityGateway
from app.utils.decorator import dao
from app.utils.logger import Log


@dao(PityGateway, Log("PityRedisConfigDao"))
class PityGatewayDao(Mapper):
class PityGatewayDao(Mapper, metaclass=Mapper):
__log__ = Log("PityRedisConfigDao")
__model__ = PityGateway

@staticmethod
# @RedisHelper.cache(f"gateway", 1800)
Expand Down
18 changes: 9 additions & 9 deletions app/crud/test_case/ConstructorDao.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
from app.models.constructor import Constructor
from app.models.test_case import TestCase
from app.schema.constructor import ConstructorForm, ConstructorIndex
from app.utils.decorator import dao
from app.utils.logger import Log


@dao(Constructor, Log("ConstructorDao"))
class ConstructorDao(Mapper):
class ConstructorDao(Mapper, metaclass=Mapper):
__model__ = Constructor
__log__ = Log("ConstructorDao")

@staticmethod
async def list_constructor(case_id: int) -> List[Constructor]:
Expand All @@ -29,7 +29,7 @@ async def list_constructor(case_id: int) -> List[Constructor]:
result = await session.execute(sql)
return result.scalars().all()
except Exception as e:
ConstructorDao.log.error(f"获取初始化数据失败, {e}")
ConstructorDao.__log__.error(f"获取初始化数据失败, {e}")
raise Exception(f"获取初始化数据失败, {e}")

@staticmethod
Expand All @@ -46,7 +46,7 @@ async def insert_constructor(data: ConstructorForm, user_id: int) -> None:
constructor.index = await constructor.get_index(session, data.case_id)
session.add(constructor)
except Exception as e:
ConstructorDao.log.error(f"新增前/后置条件: {data.name}失败, {e}")
ConstructorDao.__log__.error(f"新增前/后置条件: {data.name}失败, {e}")
raise Exception(f"新增前/后置条件失败, {e}")

@staticmethod
Expand All @@ -67,7 +67,7 @@ async def update_constructor(data: ConstructorForm, user_id: int) -> None:
raise Exception(f"{data.name}不存在")
DatabaseHelper.update_model(query, data, user_id)
except Exception as e:
ConstructorDao.log.error(f"编辑前后置条件: {data.name}失败, {e}")
ConstructorDao.__log__.error(f"编辑前后置条件: {data.name}失败, {e}")
raise Exception(f"编辑前后置条件失败, {e}")

@classmethod
Expand All @@ -88,7 +88,7 @@ async def delete_constructor(cls, id: int, user_id: int) -> None:
raise Exception(f"前后置条件{id}不存在")
DatabaseHelper.delete_model(query, user_id)
except Exception as e:
cls.log.error(f"删除前后置条件: {id}失败, {e}")
cls.__log__.error(f"删除前后置条件: {id}失败, {e}")
raise Exception(f"删除前后置条件失败, {e}")

@classmethod
Expand All @@ -105,7 +105,7 @@ async def update_constructor_index(cls, data: List[ConstructorIndex]) -> None:
await session.execute(
update(Constructor).where(Constructor.id == item.id).values(index=item.index))
except Exception as e:
cls.log.error(f"更新前后置条件顺序失败, {e}")
cls.__log__.error(f"更新前后置条件顺序失败, {e}")
raise Exception("更新前后置条件顺序失败")

@classmethod
Expand Down Expand Up @@ -139,7 +139,7 @@ async def get_constructor_tree(cls, name: str, suffix: bool) -> List[dict]:
})
return result
except Exception as e:
cls.log.error(f"获取前后置条件树失败, {e}")
cls.__log__.error(f"获取前后置条件树失败, {e}")
raise Exception("获取前后置条件失败")

@staticmethod
Expand Down

0 comments on commit 98821ee

Please sign in to comment.