From 9b5a19a58b1f2996edbb47b2cbef548796f21f88 Mon Sep 17 00:00:00 2001 From: Wu Clan Date: Fri, 26 May 2023 16:13:32 +0800 Subject: [PATCH] simplify crud method naming (#75) * simplify crud method naming * update get_user_list to get_select --- backend/__init__.py | 2 -- backend/app/api/v1/user.py | 4 +-- backend/app/common/jwt.py | 2 +- backend/app/core/registrar.py | 29 ++++++++------- backend/app/crud/base.py | 8 ++--- backend/app/crud/crud_dept.py | 4 +-- backend/app/crud/crud_role.py | 4 +-- backend/app/crud/crud_user.py | 38 ++++++++++---------- backend/app/services/user_service.py | 54 ++++++++++++++-------------- 9 files changed, 72 insertions(+), 73 deletions(-) delete mode 100644 backend/__init__.py diff --git a/backend/__init__.py b/backend/__init__.py deleted file mode 100644 index 56fafa58..00000000 --- a/backend/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- diff --git a/backend/app/api/v1/user.py b/backend/app/api/v1/user.py index c4261d3c..b08033b9 100644 --- a/backend/app/api/v1/user.py +++ b/backend/app/api/v1/user.py @@ -50,8 +50,8 @@ async def update_avatar(username: str, avatar: Avatar, current_user: CurrentUser @router.get('', summary='获取所有用户', dependencies=[DependsUser, PageDepends]) async def get_all_users(db: CurrentSession): - user_list = await UserService.get_user_list() - page_data = await paging_data(db, user_list, GetUserInfo) + user_select = await UserService.get_select() + page_data = await paging_data(db, user_select, GetUserInfo) return response_base.success(data=page_data) diff --git a/backend/app/common/jwt.py b/backend/app/common/jwt.py index 536ed32a..306e86ef 100644 --- a/backend/app/common/jwt.py +++ b/backend/app/common/jwt.py @@ -150,7 +150,7 @@ async def get_current_user(db: CurrentSession, data: dict = Depends(jwt_authenti :return: """ user_id = data.get('sub') - user = await UserDao.get_user_with_relation(db, user_id=user_id) + user = await UserDao.get_with_relation(db, user_id=user_id) if not user: raise TokenError return user diff --git a/backend/app/core/registrar.py b/backend/app/core/registrar.py index 15d35d6b..387d090f 100644 --- a/backend/app/core/registrar.py +++ b/backend/app/core/registrar.py @@ -3,8 +3,6 @@ from contextlib import asynccontextmanager from fastapi import FastAPI -from fastapi.middleware.cors import CORSMiddleware -from fastapi.middleware.gzip import GZipMiddleware from fastapi_limiter import FastAPILimiter from fastapi_pagination import add_pagination @@ -14,9 +12,8 @@ from backend.app.common.redis import redis_client from backend.app.common.task import scheduler from backend.app.core.conf import settings from backend.app.database.db_mysql import create_table -from backend.app.middleware.access_middleware import AccessMiddleware -from backend.app.utils.openapi import simplify_operation_ids from backend.app.utils.health_check import ensure_unique_route_names +from backend.app.utils.openapi import simplify_operation_ids @asynccontextmanager @@ -57,9 +54,8 @@ def register_app(): lifespan=register_init, ) - if settings.STATIC_FILES: - # 注册静态文件 - register_static_file(app) + # 静态文件 + register_static_file(app) # 中间件 register_middleware(app) @@ -83,17 +79,20 @@ def register_static_file(app: FastAPI): :param app: :return: """ - import os - from fastapi.staticfiles import StaticFiles + if settings.STATIC_FILES: + import os + from fastapi.staticfiles import StaticFiles - if not os.path.exists('./static'): - os.mkdir('./static') - app.mount('/static', StaticFiles(directory='static'), name='static') + if not os.path.exists('./static'): + os.mkdir('./static') + app.mount('/static', StaticFiles(directory='static'), name='static') def register_middleware(app: FastAPI): # CORS if settings.MIDDLEWARE_CORS: + from fastapi.middleware.cors import CORSMiddleware + app.add_middleware( CORSMiddleware, allow_origins=['*'], @@ -103,9 +102,13 @@ def register_middleware(app: FastAPI): ) # Gzip if settings.MIDDLEWARE_GZIP: + from fastapi.middleware.gzip import GZipMiddleware + app.add_middleware(GZipMiddleware) # Api access logs if settings.MIDDLEWARE_ACCESS: + from backend.app.middleware.access_middleware import AccessMiddleware + app.add_middleware(AccessMiddleware) @@ -118,7 +121,7 @@ def register_router(app: FastAPI): """ app.include_router(v1) - # extra + # Extra ensure_unique_route_names(app) simplify_operation_ids(app) diff --git a/backend/app/crud/base.py b/backend/app/crud/base.py index d7c9cbff..cfef20a1 100644 --- a/backend/app/crud/base.py +++ b/backend/app/crud/base.py @@ -17,7 +17,7 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): def __init__(self, model: Type[ModelType]): self.model = model - async def get(self, db: AsyncSession, pk: int) -> ModelType | None: + async def get_(self, db: AsyncSession, pk: int) -> ModelType | None: """ 通过主键 id 获取一条数据 @@ -28,7 +28,7 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): model = await db.execute(select(self.model).where(self.model.id == pk)) return model.scalars().first() - async def create(self, db: AsyncSession, obj_in: CreateSchemaType, user_id: int | None = None) -> NoReturn: + async def create_(self, db: AsyncSession, obj_in: CreateSchemaType, user_id: int | None = None) -> NoReturn: """ 新增一条数据 @@ -43,7 +43,7 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): db_obj = self.model(**obj_in.dict()) db.add(db_obj) - async def update( + async def update_( self, db: AsyncSession, pk: int, obj_in: UpdateSchemaType | Dict[str, Any], user_id: int | None = None ) -> int: """ @@ -64,7 +64,7 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): model = await db.execute(update(self.model).where(self.model.id == pk).values(**update_data)) return model.rowcount - async def delete(self, db: AsyncSession, pk: int) -> int: + async def delete_(self, db: AsyncSession, pk: int) -> int: """ 通过主键 id 删除一条数据 diff --git a/backend/app/crud/crud_dept.py b/backend/app/crud/crud_dept.py index bd5c9245..8b90df08 100644 --- a/backend/app/crud/crud_dept.py +++ b/backend/app/crud/crud_dept.py @@ -6,8 +6,8 @@ from backend.app.schemas.dept import CreateDept, UpdateDept class CRUDDept(CRUDBase[Dept, CreateDept, UpdateDept]): - async def get_dept_by_id(self, db, dept_id): - return await self.get(db, dept_id) + async def get(self, db, dept_id: int): + return await self.get_(db, dept_id) DeptDao: CRUDDept = CRUDDept(Dept) diff --git a/backend/app/crud/crud_role.py b/backend/app/crud/crud_role.py index b1890152..9aecae58 100644 --- a/backend/app/crud/crud_role.py +++ b/backend/app/crud/crud_role.py @@ -6,8 +6,8 @@ from backend.app.schemas.role import CreateRole, UpdateRole class CRUDRole(CRUDBase[Role, CreateRole, UpdateRole]): - async def get_role_by_id(self, db, role_id): - return await self.get(db, role_id) + async def get(self, db, role_id: int): + return await self.get_(db, role_id) RoleDao: CRUDRole = CRUDRole(Role) diff --git a/backend/app/crud/crud_user.py b/backend/app/crud/crud_user.py index b1d2344d..ee381c89 100644 --- a/backend/app/crud/crud_user.py +++ b/backend/app/crud/crud_user.py @@ -14,18 +14,18 @@ from backend.app.schemas.user import CreateUser, UpdateUser, Avatar class CRUDUser(CRUDBase[User, CreateUser, UpdateUser]): - async def get_user_by_id(self, db: AsyncSession, user_id: int) -> User | None: - return await self.get(db, user_id) + async def get(self, db: AsyncSession, user_id: int) -> User | None: + return await self.get_(db, user_id) - async def get_user_by_username(self, db: AsyncSession, username: str) -> User | None: + async def get_by_username(self, db: AsyncSession, username: str) -> User | None: user = await db.execute(select(self.model).where(self.model.username == username)) return user.scalars().first() - async def update_user_login_time(self, db: AsyncSession, username: str) -> int: + async def update_login_time(self, db: AsyncSession, username: str) -> int: user = await db.execute(update(self.model).where(self.model.username == username).values(last_login=func.now())) return user.rowcount - async def create_user(self, db: AsyncSession, create: CreateUser) -> NoReturn: + async def create(self, db: AsyncSession, create: CreateUser) -> NoReturn: create.password = jwt.get_hash_password(create.password) new_user = self.model(**create.dict(exclude={'roles'})) role_list = [] @@ -52,8 +52,8 @@ class CRUDUser(CRUDBase[User, CreateUser, UpdateUser]): user = await db.execute(update(self.model).where(self.model.id == current_user.id).values(avatar=avatar)) return user.rowcount - async def delete_user(self, db: AsyncSession, user_id: int) -> int: - return await self.delete(db, user_id) + async def delete(self, db: AsyncSession, user_id: int) -> int: + return await super().delete_(db, user_id) async def check_email(self, db: AsyncSession, email: str) -> User | None: mail = await db.execute(select(self.model).where(self.model.email == email)) @@ -65,45 +65,43 @@ class CRUDUser(CRUDBase[User, CreateUser, UpdateUser]): ) return user.rowcount - def get_users(self) -> Select: + def get_all(self) -> Select: return ( select(self.model) .options(selectinload(self.model.roles).selectinload(Role.menus)) .order_by(desc(self.model.time_joined)) ) - async def get_user_is_super(self, db: AsyncSession, user_id: int) -> bool: - user = await self.get_user_by_id(db, user_id) + async def get_super(self, db: AsyncSession, user_id: int) -> bool: + user = await self.get(db, user_id) return user.is_superuser - async def get_user_is_active(self, db: AsyncSession, user_id: int) -> bool: - user = await self.get_user_by_id(db, user_id) + async def get_active(self, db: AsyncSession, user_id: int) -> bool: + user = await self.get(db, user_id) return user.is_active - async def super_set(self, db: AsyncSession, user_id: int) -> int: - super_status = await self.get_user_is_super(db, user_id) + async def set_super(self, db: AsyncSession, user_id: int) -> int: + super_status = await self.get_super(db, user_id) user = await db.execute( update(self.model).where(self.model.id == user_id).values(is_superuser=False if super_status else True) ) return user.rowcount - async def active_set(self, db: AsyncSession, user_id: int) -> int: - active_status = await self.get_user_is_active(db, user_id) + async def set_active(self, db: AsyncSession, user_id: int) -> int: + active_status = await self.get_active(db, user_id) user = await db.execute( update(self.model).where(self.model.id == user_id).values(is_active=False if active_status else True) ) return user.rowcount - async def get_user_role_ids(self, db: AsyncSession, user_id: int) -> list[int]: + async def get_role_ids(self, db: AsyncSession, user_id: int) -> list[int]: user = await db.execute( select(self.model).where(self.model.id == user_id).options(selectinload(self.model.roles)) ) roles_id = [role.id for role in user.scalars().first().roles] return roles_id - async def get_user_with_relation( - self, db: AsyncSession, *, user_id: int = None, username: str = None - ) -> User | None: + async def get_with_relation(self, db: AsyncSession, *, user_id: int = None, username: str = None) -> User | None: where = [] if user_id: where.append(self.model.id == user_id) diff --git a/backend/app/services/user_service.py b/backend/app/services/user_service.py index fa3bb2b6..0de075dd 100644 --- a/backend/app/services/user_service.py +++ b/backend/app/services/user_service.py @@ -21,7 +21,7 @@ class UserService: @staticmethod async def swagger_login(form_data: OAuth2PasswordRequestForm): async with async_db_session() as db: - current_user = await UserDao.get_user_by_username(db, form_data.username) + current_user = await UserDao.get_by_username(db, form_data.username) if not current_user: raise errors.NotFoundError(msg='用户不存在') elif not jwt.password_verify(form_data.password, current_user.password): @@ -29,11 +29,11 @@ class UserService: elif not current_user.is_active: raise errors.AuthorizationError(msg='用户已锁定, 登陆失败') # 更新登陆时间 - await UserDao.update_user_login_time(db, form_data.username) + await UserDao.update_login_time(db, form_data.username) # 查询用户角色 - user_role_ids = await UserDao.get_user_role_ids(db, current_user.id) + user_role_ids = await UserDao.get_role_ids(db, current_user.id) # 获取最新用户信息 - user = await UserDao.get_user_by_id(db, current_user.id) + user = await UserDao.get(db, current_user.id) # 创建token access_token, _ = await jwt.create_access_token(str(user.id), role_ids=user_role_ids) return access_token, user @@ -41,16 +41,16 @@ class UserService: @staticmethod async def login(obj: Auth): async with async_db_session() as db: - current_user = await UserDao.get_user_by_username(db, obj.username) + current_user = await UserDao.get_by_username(db, obj.username) if not current_user: raise errors.NotFoundError(msg='用户不存在') elif not jwt.password_verify(obj.password, current_user.password): raise errors.AuthorizationError(msg='密码错误') elif not current_user.is_active: raise errors.AuthorizationError(msg='用户已锁定, 登陆失败') - await UserDao.update_user_login_time(db, obj.username) - user_role_ids = await UserDao.get_user_role_ids(db, current_user.id) - user = await UserDao.get_user_by_id(db, current_user.id) + await UserDao.update_login_time(db, obj.username) + user_role_ids = await UserDao.get_role_ids(db, current_user.id) + user = await UserDao.get(db, current_user.id) access_token, access_token_expire_time = await jwt.create_access_token(str(user.id), role_ids=user_role_ids) refresh_token, refresh_token_expire_time = await jwt.create_refresh_token( str(user.id), access_token_expire_time, role_ids=user_role_ids @@ -60,12 +60,12 @@ class UserService: @staticmethod async def refresh_token(user_id: int, custom_time: RefreshTokenTime): async with async_db_session() as db: - current_user = await UserDao.get_user_by_id(db, user_id) + current_user = await UserDao.get(db, user_id) if not current_user: raise errors.NotFoundError(msg='用户不存在') elif not current_user.is_active: raise errors.AuthorizationError(msg='用户已锁定, 获取失败') - user_role_ids = await UserDao.get_user_role_ids(db, current_user.id) + user_role_ids = await UserDao.get_role_ids(db, current_user.id) refresh_token, refresh_token_expire_time = await jwt.create_refresh_token( str(current_user.id), custom_expire_time=custom_time, role_ids=user_role_ids ) @@ -80,7 +80,7 @@ class UserService: @staticmethod async def register(obj: CreateUser): async with async_db_session.begin() as db: - username = await UserDao.get_user_by_username(db, obj.username) + username = await UserDao.get_by_username(db, obj.username) if username: raise errors.ForbiddenError(msg='该用户名已注册') email = await UserDao.check_email(db, obj.email) @@ -90,14 +90,14 @@ class UserService: validate_email(obj.email, check_deliverability=False).email except EmailNotValidError: raise errors.ForbiddenError(msg='邮箱格式错误') - dept = await DeptDao.get_dept_by_id(db, obj.dept_id) + dept = await DeptDao.get(db, obj.dept_id) if not dept: raise errors.NotFoundError(msg='部门不存在') for role_id in obj.roles: - role = await RoleDao.get_role_by_id(db, role_id) + role = await RoleDao.get(db, role_id) if not role: raise errors.NotFoundError(msg='角色不存在') - await UserDao.create_user(db, obj) + await UserDao.create(db, obj) @staticmethod async def pwd_reset(obj: ResetPassword): @@ -111,7 +111,7 @@ class UserService: @staticmethod async def get_userinfo(username: str): async with async_db_session() as db: - user = await UserDao.get_user_with_relation(db, username=username) + user = await UserDao.get_with_relation(db, username=username) if not user: raise errors.NotFoundError(msg='用户不存在') return user @@ -122,11 +122,11 @@ class UserService: if not current_user.is_superuser: if not username == current_user.username: raise errors.AuthorizationError - input_user = await UserDao.get_user_with_relation(db, username=username) + input_user = await UserDao.get_with_relation(db, username=username) if not input_user: raise errors.NotFoundError(msg='用户不存在') if input_user.username != obj.username: - username = await UserDao.get_user_by_username(db, obj.username) + username = await UserDao.get_by_username(db, obj.username) if username: raise errors.ForbiddenError(msg='该用户名已存在') if input_user.email != obj.email: @@ -140,11 +140,11 @@ class UserService: if obj.phone is not None: if not re_verify.is_phone(obj.phone): raise errors.ForbiddenError(msg='手机号码输入有误') - dept = await DeptDao.get_dept_by_id(db, obj.dept_id) + dept = await DeptDao.get(db, obj.dept_id) if not dept: raise errors.NotFoundError(msg='部门不存在') for role_id in obj.roles: - role = await RoleDao.get_role_by_id(db, role_id) + role = await RoleDao.get(db, role_id) if not role: raise errors.NotFoundError(msg='角色不存在') count = await UserDao.update_userinfo(db, input_user, obj) @@ -156,7 +156,7 @@ class UserService: if not current_user.is_superuser: if not username == current_user.username: raise errors.AuthorizationError - input_user = await UserDao.get_user_by_username(db, username) + input_user = await UserDao.get_by_username(db, username) if not input_user: raise errors.NotFoundError(msg='用户不存在') count = await UserDao.update_avatar(db, input_user, avatar) @@ -164,13 +164,13 @@ class UserService: @staticmethod async def get_user_list(): - return UserDao.get_users() + return UserDao.get_all() @staticmethod async def update_permission(pk: int): async with async_db_session.begin() as db: - if await UserDao.get_user_by_id(db, pk): - count = await UserDao.super_set(db, pk) + if await UserDao.get(db, pk): + count = await UserDao.set_super(db, pk) return count else: raise errors.NotFoundError(msg='用户不存在') @@ -178,8 +178,8 @@ class UserService: @staticmethod async def update_active(pk: int): async with async_db_session.begin() as db: - if await UserDao.get_user_by_id(db, pk): - count = await UserDao.active_set(db, pk) + if await UserDao.get(db, pk): + count = await UserDao.set_active(db, pk) return count else: raise errors.NotFoundError(msg='用户不存在') @@ -190,8 +190,8 @@ class UserService: if not current_user.is_superuser: if not username == current_user.username: raise errors.AuthorizationError - input_user = await UserDao.get_user_by_username(db, username) + input_user = await UserDao.get_by_username(db, username) if not input_user: raise errors.NotFoundError(msg='用户不存在') - count = await UserDao.delete_user(db, input_user.id) + count = await UserDao.delete(db, input_user.id) return count