mirror of
https://github.com/fastapi-practices/fastapi-best-architecture.git
synced 2026-09-21 21:15:13 +00:00
Update non-linked sidebar support (#633)
* Update non-linked sidebar support * fix typing
This commit is contained in:
@@ -15,8 +15,8 @@ router = APIRouter()
|
||||
|
||||
|
||||
@router.get('/sidebar', summary='获取用户菜单侧边栏', description='适配 vben5', dependencies=[DependsJwtAuth])
|
||||
async def get_user_sidebar(request: Request) -> ResponseSchemaModel[list[dict[str, Any]]]:
|
||||
menu = await menu_service.get_user_menu_tree(request=request)
|
||||
async def get_user_sidebar(request: Request) -> ResponseSchemaModel[list[dict[str, Any] | None]]:
|
||||
menu = await menu_service.get_sidebar(request=request)
|
||||
return response_base.success(data=menu)
|
||||
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ async def get_user_all_roles(
|
||||
@router.get('/{pk}/menus', summary='获取角色所有菜单', dependencies=[DependsJwtAuth])
|
||||
async def get_role_all_menus(
|
||||
pk: Annotated[int, Path(description='角色 ID')],
|
||||
) -> ResponseSchemaModel[list[dict[str, Any]]]:
|
||||
) -> ResponseSchemaModel[list[dict[str, Any] | None]]:
|
||||
menu = await role_service.get_menu_tree(pk=pk)
|
||||
return response_base.success(data=menu)
|
||||
|
||||
|
||||
@@ -45,12 +45,12 @@ class CRUDMenu(CRUDPlus[Menu]):
|
||||
"""
|
||||
filters = {}
|
||||
if title is not None:
|
||||
filters.update(title=f'%{title}%')
|
||||
filters.update(title_like=f'%{title}%')
|
||||
if status is not None:
|
||||
filters.update(status=status)
|
||||
return await self.select_models_order(db, 'sort', **filters)
|
||||
|
||||
async def get_role_menus(self, db: AsyncSession, superuser: bool, menu_ids: list[int]) -> Sequence[Menu]:
|
||||
async def get_sidebar(self, db: AsyncSession, superuser: bool, menu_ids: list[int | None]) -> Sequence[Menu]:
|
||||
"""
|
||||
获取角色菜单列表
|
||||
|
||||
|
||||
@@ -41,27 +41,29 @@ class MenuService:
|
||||
:return:
|
||||
"""
|
||||
async with async_db_session() as db:
|
||||
menu_select = await menu_dao.get_all(db, title=title, status=status)
|
||||
menu_tree = get_tree_data(menu_select)
|
||||
menu_data = await menu_dao.get_all(db, title=title, status=status)
|
||||
menu_tree = get_tree_data(menu_data)
|
||||
return menu_tree
|
||||
|
||||
@staticmethod
|
||||
async def get_user_menu_tree(*, request: Request) -> list[dict[str, Any]]:
|
||||
async def get_sidebar(*, request: Request) -> list[dict[str, Any] | None]:
|
||||
"""
|
||||
获取用户的菜单树形结构
|
||||
获取用户的菜单侧边栏
|
||||
|
||||
:param request: FastAPI 请求对象
|
||||
:return:
|
||||
"""
|
||||
async with async_db_session() as db:
|
||||
roles = request.user.roles
|
||||
menu_ids = []
|
||||
menu_tree = []
|
||||
if roles:
|
||||
all_menus = []
|
||||
for role in roles:
|
||||
menu_ids.extend([menu.id for menu in role.menus])
|
||||
menu_select = await menu_dao.get_role_menus(db, request.user.is_superuser, menu_ids)
|
||||
menu_tree = get_vben5_tree_data(menu_select)
|
||||
all_menus.extend(role.menus)
|
||||
all_ids = [menu.id for menu in all_menus]
|
||||
valid_menu_ids = [menu.id for menu in all_menus if menu.parent_id is None or menu.parent_id in all_ids]
|
||||
menu_data = await menu_dao.get_sidebar(db, request.user.is_superuser, valid_menu_ids)
|
||||
menu_tree = get_vben5_tree_data(menu_data)
|
||||
return menu_tree
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -69,7 +69,7 @@ class RoleService:
|
||||
return await role_dao.get_list(name=name, status=status)
|
||||
|
||||
@staticmethod
|
||||
async def get_menu_tree(*, pk: int) -> list[dict[str, Any]]:
|
||||
async def get_menu_tree(*, pk: int) -> list[dict[str, Any] | None]:
|
||||
"""
|
||||
获取角色的菜单树形结构
|
||||
|
||||
@@ -80,9 +80,7 @@ class RoleService:
|
||||
role = await role_dao.get_with_relation(db, pk)
|
||||
if not role:
|
||||
raise errors.NotFoundError(msg='角色不存在')
|
||||
menu_ids = [menu.id for menu in role.menus]
|
||||
menu_select = await menu_dao.get_role_menus(db, False, menu_ids)
|
||||
menu_tree = get_tree_data(menu_select)
|
||||
menu_tree = get_tree_data(role.menus) if role.menus else []
|
||||
return menu_tree
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Socket.IO Task Notifications</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
}
|
||||
#notifications {
|
||||
margin-top: 20px;
|
||||
padding: 10px;
|
||||
border: 1px solid #ccc;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.notification {
|
||||
padding: 10px;
|
||||
margin-bottom: 10px;
|
||||
background-color: #f9f9f9;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.notification.new {
|
||||
background-color: #d3f9d8;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h1>Task Notifications</h1>
|
||||
<p>Waiting for task notifications...</p>
|
||||
|
||||
<div id="notifications"></div>
|
||||
|
||||
<!-- Load Socket.IO client -->
|
||||
<script src="https://cdn.socket.io/4.5.1/socket.io.min.js"></script>
|
||||
<script>
|
||||
// Establish a connection to the server
|
||||
const socket = io('http://127.0.0.1:8000', {
|
||||
autoConnect: true,
|
||||
path: '/ws/socket.io',
|
||||
reconnection: true,
|
||||
reconnectionAttempts: 3,
|
||||
reconnectionDelay: 1000,
|
||||
transports: ['websocket'],
|
||||
auth: {
|
||||
session_uuid: 'da985430-43b3-4860-a20a-97cc8e8e0b76',
|
||||
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uX3V1aWQiOiJkYTk4NTQzMC00M2IzLTQ4NjAtYTIwYS05N2NjOGU4ZTBiNzYiLCJleHAiOjE3Mzc2MzQwODUsInN1YiI6IjEifQ.QeXNtXhHG4cm5GRzOtv2wqZXi6HdqACmW_UjC4JLPsk'
|
||||
}
|
||||
});
|
||||
|
||||
// Handle 'task_notification' event
|
||||
socket.on('task_notification', (data) => {
|
||||
// Get the notifications container
|
||||
const notificationsContainer = document.getElementById('notifications');
|
||||
|
||||
// Create a new div for the notification
|
||||
const notificationDiv = document.createElement('div');
|
||||
notificationDiv.classList.add('notification', 'new');
|
||||
notificationDiv.innerHTML = `
|
||||
<strong>Task Notification:</strong>
|
||||
<p>${data.msg}</p>
|
||||
<small>Received at: ${new Date().toLocaleTimeString()}</small>
|
||||
`;
|
||||
|
||||
// Append the new notification to the container
|
||||
notificationsContainer.appendChild(notificationDiv);
|
||||
|
||||
// Scroll to the bottom to show the latest notification
|
||||
notificationsContainer.scrollTop = notificationsContainer.scrollHeight;
|
||||
});
|
||||
|
||||
// Handle connection errors
|
||||
socket.on('connect_error', (error) => {
|
||||
console.error('Connection error:', error);
|
||||
alert('Unable to connect to the server. Please check your connection.');
|
||||
});
|
||||
|
||||
socket.on('connect', () => {
|
||||
console.log('Connected to server');
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('Disconnected from server');
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user