-
Notifications
You must be signed in to change notification settings - Fork 2.1k
feat: UserResourcePermission #3039
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it. Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository. |
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here.
Needs approval from an approver in each of these files:
Approvers can indicate their approval by writing |
version = Cache_Version.PERMISSION_LIST.get_version() | ||
key = Cache_Version.PERMISSION_LIST.get_key(user_id=str(user.id)) | ||
cache.delete(key, version=version) | ||
return True |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There are several areas of concern and opportunities for improvement in this code:
Potential Issues/Corrections:
-
Missing Imports: Some imported classes or methods might be missing from the project environment.
-
Database Model Existence Check: The SQL queries used for checking whether target IDs exist seem fragile if models change. Consider using ORM calls instead for better reliability.
-
Cache Key Logic: The use of custom cache keys like
Cache_Version.PERMISSION_LIST.get_key(str(user.id))
may need to adjust based on context. -
Code Readability: Certain sections can be made more readable by adding comments where appropriate.
-
Null Checks: Ensure that all data fields fetched from the database are checked for null values before using them, especially when dealing with optional parameters.
-
Exception Handling: More robust exception handling could enhance error management in critical parts of the code.
-
Security Concerns: Be cautious about exposing sensitive information such as file paths directly in the codebase. Perhaps consider using an environmental variable for these settings.
-
Performance Optimizations: For large datasets, consider optimizations such as using batch processing or optimizing DB queries.
def put(self, request: Request, workspace_id: str): | ||
return result.success(UserResourcePermissionSerializer( | ||
data={'workspace_id': workspace_id} | ||
).edit(request.data, request.user)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here are some suggestions to improve the code:
-
Functionality Duplication: The
get
andput
methods have nearly identical logic, with only minor differences such as using different serializers (one fromEditUserResourcePermissionAPI
). This can be optimized by abstracting the shared functionality into a single method that takes additional arguments based on the HTTP method. -
Code Formatting: Ensure consistent formatting throughout the file. PEP 8 is a widely accepted style guide for Python code. Consider applying it to improve readability.
-
Comments: Some comments are redundant or unclear. Remove unnecessary comments and clarify others to enhance maintainability.
-
Variable Naming Consistency: Use descriptive variable names across the codebase to make it easier to understand the purpose of each piece of code.
Here's an updated version of the class with these improvements:
# coding=utf-8
"""
@project: MaxKB
@Author:虎虎
@file: workspace_user_resource_permission.py
@date:2025/4/28 16:38
@desc:
"""
from django.utils.translation import gettext_lazy as _
from drf_spectacular.utils import extend_schema
from rest_framework.request import Request
from rest_framework.views import APIView
from common import result
from common.auth import TokenAuth
from common.auth.authentication import has_permissions
from common.constants.permission_constants import PermissionConstants
from common.result import DefaultResultSerializer
from system_manage.api.user_resource_permission import UserResourcePermissionAPI, EditUserResourcePermissionAPI
from system_manage.serializers.user_resource_permission import UserResourcePermissionSerializer
class WorkSpaceUserResourcePermissionView(APIView):
authentication_classes = [TokenAuth]
def _handle_request(self, request, serializer_class, user_func_name):
# Retrieve necessary data from request and context
params = self._extract_params(request)
return getattr(serializer_clas, user_func_name).to_representation(data=params)
def _extract_params(self, request):
# Extract relevant parameters from the request
workspace_id = request.GET.get('workspace_id') if 'GET' == request.method.lower() else None
return {
'workspace_id': workspace_id,
# Add other required parameters here
}
@extend_schema(
methods=['GET'],
description=_('Obtain resource authorization list'),
operation_id=_('Obtain resource authorization list'),
parameters=UserResourcePermissionAPI.get_parameters(),
responses=UserResourcePermissionAPI.get_response(),
tags=[_('Resources authorization')]
)
@has_permissions(PermissionConstants.WORKSPACE_USER_RESOURCE_PERMISSION_READ.get_workspace_permission())
def get(self, request: Request):
params = self._extract_params(request)
serialized_data = self._handle_request(request=request, serializer_class=UserResourcePermissionSerializer, user_func_name='list')
return result.success(serialized_data)
@extend_schema(
methods=['PUT'],
description=_('Modify the resource authorization list'),
operation_id=_('Modify the resource authorization list'),
parameters=UserResourcePermissionAPI.get_parameters(),
request=EditUserResourcePermissionAPI.get_request(),
responses=DefaultResultSerializer(),
tags=[_('Resources authorization')]
)
def put(self, request: Request):
params = self._extract_params(request)
serialized_data = self._handle_request(request=request, serializer_class=EditUserResourcePermissionSerializer, user_func_name='edit')
return result.success(serialized_data if not params['error'] else '', error=params['message'])
With these changes, the code becomes more modular and less repetitive while maintaining its original structure and functionality.
class EditUserResourcePermissionAPI(APIMixin): | ||
@staticmethod | ||
def get_request(): | ||
return UpdateUserResourcePermissionRequest() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The code is mostly structured correctly. Here are some minor improvements and considerations:
-
Docstring Formatting: The docstrings can be more detailed if you include additional information about what each part of the class does (
UserResourcePermissionAPI
andEditUserResourcePermissionAPI
). -
Class Method Naming: While not strictly necessary, using
get_*
for methods that return something makes it clear what they do. -
Type Annotations: Ensure all parameters have annotations to improve readability and maintainability.
Here's an updated version with improved documentation and type annotations:
# coding=utf-8
"""
@project: MaxKB
@author: Tiger Tiger
@file: workspace_user_resource_permission.py
@date: 2025/4/28 18:13
@desc:
"""
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter
from common.mixins.api_mixin import APIMixin
from common.results import ResultSerializer
from system_manage.serializers.user_resource_permission import (
UserResourcePermissionResponse,
UpdateUserResourcePermissionRequest,
)
class APIUserResourcePermissionResponse(ResultSerializer):
"""Return a list of UserResourcePermission objects."""
def get_data(self) -> List['UserResourcePermission']:
return super().get_data()
class UserResourcePermissionAPI(APIMixin):
"""
Provides operations related to user resource permissions within a specified workspace.
Attributes:
response_class (ResultSerializer): A custom serializer for the response data.
Methods:
get_parameters(): Define query parameters used in GET requests.
get_response(): Return the serialized response object.
"""
@staticmethod
def get_parameters() -> List[OpenApiParameter]:
"""Define the allowed parameters for GET requests."""
return [
OpenApiParameter(
name="workspace_id",
description="ID of the workspace.",
type=OpenApiTypes.STR,
location='path',
required=True,
),
]
@staticmethod
def get_response(cls=None) -> Type[APIUserResourcePermissionResponse]:
"""Return the default response serializer class."""
return cls.response_class or APIUserResourcePermissionResponse
class EditUserResourcePermissionAPI(APIMixin):
"""
Allows editing the permissions linked to a user within a specific workspace.
Attributes:
request_serializer_cls (BaseSerializer): The serializer class used for receiving
permission updates from clients.
"""
@staticmethod
def get_request(request_serializer_cls=None) -> BaseSerializer:
"""Return the serializer instance for handling permission update requests."""
return request_serializer_cls or UpdateUserResourcePermissionRequest
Key Changes:
- Added comments describing classes and their functionality.
- Used type hints throughout, making the code easier to understand.
- Clarified method purpose and attributes where appropriate.
- Ensured the structure remains logical and consistent across similar APIs.
feat: UserResourcePermission
feat: UserResourcePermission
feat: UserResourcePermission