Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/system_manage/api/user_resource_permission.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def get_parameters():
required=False
),
OpenApiParameter(
name="permission",
name="permission[]",
description="权限",
type=OpenApiTypes.STR,
location='query',
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code snippet has a small issue with the parameter definition:

def get_parameters():
    return [
        OpenApiParameter(
            name="permission[]",  # This is incorrect. Parameter names should not contain square brackets []
            description="权限",
            type=OpenApiTypes.STR,
            location='query'
        )
    ]

Issue:
The name attribute should use snake_case instead of camelCase and should be prefixed with an underscore to adhere to typical naming conventions for query parameters.

Optimization Suggestions:

  1. Use Proper Naming Convention: Ensure that all names, including query parameters, follow Python's conventional snake_case naming style to make them more readable and maintainable.
  2. Documentation Consistency: Make sure that the documentation (description) matches the actual usage of the parameter if it differs from its internal structure or behavior.

Corrected Code:

def get_parameters():
    return [
        OpenApiParameter(
            name="_permission",
            description="权限",
            type=OpenApiTypes.SLICE_OF_STRINGS,  # Adjust types based on intended functionality
            location='query'
        )
    ]

Note: Depending on your specific needs, you might want to use str | list[str] as the type.

Expand Down
6 changes: 3 additions & 3 deletions apps/system_manage/views/user_resource_permission.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def get(self, request: Request, workspace_id: str, user_id: str, resource: str):
return result.success(UserResourcePermissionSerializer(
data={'workspace_id': workspace_id, 'user_id': user_id, 'auth_target_type': resource}
).list({'name': request.query_params.get('name'),
'permission': request.query_params.getlist('permission')}, request.user))
'permission': request.query_params.getlist('permission[]')}, request.user))

@extend_schema(
methods=['PUT'],
Expand Down Expand Up @@ -99,7 +99,7 @@ def get(self, request: Request, workspace_id: str, user_id: str, resource: str,
return result.success(UserResourcePermissionSerializer(
data={'workspace_id': workspace_id, 'user_id': user_id, 'auth_target_type': resource}
).page({'name': request.query_params.get('name'),
'permission': request.query_params.getlist('permission')}, current_page, page_size, request.user))
'permission': request.query_params.getlist('permission[]')}, current_page, page_size, request.user))


class WorkspaceResourceUserPermissionView(APIView):
Expand Down Expand Up @@ -132,7 +132,7 @@ def get(self, request: Request, workspace_id: str, target: str, resource: str):
data={'workspace_id': workspace_id, "target": target, 'auth_target_type': resource,
}).list(
{'username': request.query_params.get("username"), 'nick_name': request.query_params.get("nick_name"),
'permission': request.query_params.getlist("permission")
'permission': request.query_params.getlist("permission[]")
}))

@extend_schema(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code snippet includes several potential issues and areas for optimization:

  1. Duplicate Code: There are multiple instances where the UserResourcePermissionSerializer is used with similar logic but with different query parameter names and handling (request.query_params.get() vs request.query_params.getlist()) on permission. This could be consolidated into a single method to reduce redundancy.

  2. Consistent Query Parameter Handling: The use of 'permission' for both single-value and list values is inconsistent. When using 'permission', it should typically expect a comma-separated string if you intend it as a list-like input (e.g., 'read,write,execute'). Ensure that this usage aligns across all calls to the serializer.

  3. Variable Names: The variable current_page was defined but not subsequently used within the function scope. Since it's only referenced outside the method, consider removing or ensuring its reuse.

  4. APIView Consistency: While API views like WorkspaceResourcePermissionsListView and WorkspaceResourceUserPermissionView extend from APIView, they have separate paths and handlers. Consider combining them under a common base class (e.g., BaseWorkplaceResourceView) to share common behavior and improve maintainability.

  5. Extend Schema Usage: In some cases, extending schema metadata might not add significant value unless detailed documentation or extra validation rules are required. If no additional schema information needs to be added, remove these decorators.

  6. Type Annotations: It would be beneficial to add type annotations to the parameters and return types in each function to enhance readability and catch errors at runtime.

Here’s an optimized version after addressing these points:

from drf_yasg.utils import swagger_auto_schema
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination

class UserResourcePermissionListApiHandler:
    @swagger_auto_schema(
        operations_summary='Get user-resource-permission list',
        responses={200: UserResourcePermissionSerializer(many=True)}
    )
    def get(self, request: Request, workspace_id: str, user_id: str, resource: str) -> Response:
        queryset = UserResourcePermission.objects.filter(workspace=workspace_id, user=user_id)
        permission_querystring_value = request.query_params.get('permission', '').split(',')
        filtered_queryset = queryset.filter(permission__in=permission_querystring_value)

        paginator = PageNumberPagination()
        paginated_response = paginator.paginate_queryset(filtered_queryset, request)
        
        return paginator.get_paginated_response(UserResourcePermissionSerializer(paginated_response).data)


# Example usage:
# class WorkspaceResourcePermissionsListView(BaseWorkplaceResourceViewMixin, BaseWorkplaceResourcesAccessControlView):
#     ...

In summary, focusing on clean code by reducing duplication, consistent parameter management, and optimizing variable usage can significantly enhance the robustness and ease of maintenance of codebases.

Expand Down
Loading