Skip to content

Conversation

@shaohuzhang1
Copy link
Contributor

fix: Query by permission in system resource management --bug=1060785 --user=张展玮 【资源授权】-通过权限查询资源无效 https://www.tapd.cn/62980211/s/1761243

--bug=1060785 --user=张展玮 【资源授权】-通过权限查询资源无效 https://www.tapd.cn/62980211/s/1761243
@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Aug 26, 2025

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.

Details

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-sigs/prow repository.

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Aug 26, 2025

[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.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@zhanweizhang7 zhanweizhang7 merged commit c082dae into v2 Aug 26, 2025
3 of 5 checks passed
@zhanweizhang7 zhanweizhang7 deleted the pr@v2@fix_query_permission_in_system_resource_management branch August 26, 2025 05:59
'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.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants