simplify crud method naming (#75)

* simplify crud method naming

* update get_user_list to get_select
This commit is contained in:
Wu Clan
2023-05-26 16:13:32 +08:00
committed by GitHub
parent 4868cb142b
commit 9b5a19a58b
9 changed files with 72 additions and 73 deletions
-2
View File
@@ -1,2 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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
+16 -13
View File
@@ -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)
+4 -4
View File
@@ -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 删除一条数据
+2 -2
View File
@@ -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)
+2 -2
View File
@@ -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)
+18 -20
View File
@@ -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)
+27 -27
View File
@@ -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