Skip to content

feat: application save #3151

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

Merged
merged 1 commit into from
May 27, 2025
Merged
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
66 changes: 66 additions & 0 deletions apps/common/field/common.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# coding=utf-8
"""
@project: maxkb
@Author:虎
@file: common.py
@date:2024/1/11 18:44
@desc:
"""
from rest_framework import serializers
from django.utils.translation import gettext_lazy as _


class ObjectField(serializers.Field):
def __init__(self, model_type_list, **kwargs):
self.model_type_list = model_type_list
super().__init__(**kwargs)

def to_internal_value(self, data):
for model_type in self.model_type_list:
if isinstance(data, model_type):
return data
self.fail(_('Message type error'), value=data)

def to_representation(self, value):
return value


class InstanceField(serializers.Field):
def __init__(self, model_type, **kwargs):
self.model_type = model_type
super().__init__(**kwargs)

def to_internal_value(self, data):
if not isinstance(data, self.model_type):
self.fail(_('Message type error'), value=data)
return data

def to_representation(self, value):
return value


class FunctionField(serializers.Field):

def to_internal_value(self, data):
if not callable(data):
self.fail(_('not a function'), value=data)
return data

def to_representation(self, value):
return value


class UploadedImageField(serializers.ImageField):
def __init__(self, **kwargs):
super().__init__(**kwargs)

def to_representation(self, value):
return value


class UploadedFileField(serializers.FileField):
def __init__(self, **kwargs):
super().__init__(**kwargs)

def to_representation(self, value):
return value
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Based on the provided Python code (which appears to be part of Django REST Framework), here are some comments and areas for improvement:

Code Comments and Issues

  1. File Encoding: The file starts with @@, which suggests it might be coming from a diff tool like Git or GitHub Actions. Ensure that this is intentional and does not affect the original code.

  2. Docstrings: All classes have doc strings but lack clear descriptions of what each method does. This can make the code harder to understand without additional documentation.

  3. Field Classes:

    • ObjectField: Should be used where you need a flexible object type that could represent several models. It allows passing lists of allowed model types, which can potentially lead to confusion.
    • InstanceField: Ensures that only instances of a specified model can be passed via serialization/deserialization. Useful for ensuring that data meets expected schema requirements.
    • FunctionField: Validates if the input is a callable function. Useful for validating endpoints that accept functions at runtime, though usage cases are limited.
    • UploadedImageField and UploadedFileField: These should work similarly to their standard counterparts but specify image for UploadedImageField. They default to uploading files, so explicitly mentioning these fields helps clarity.
  4. Consistent Naming Convention: While naming conventions such as self.model_type_list are consistent, model_type in certain contexts could benefit from being more descriptive (e.g., allowed_model_types).

Optimizations

  • Error Messages: Enhancing error messages can improve user feedback when an invalid type is encountered.

    class ObjectField(serializers.Field):
        def __init__(self, model_type_list, **kwargs):
            self.model_type_list = model_type_list
            super().__init__(**kwargs)
    
        def to_internal_value(self, data):
            for model_type in self.model_type_list:
                if isinstance(data, model_type):
                    return data
             message = _("Invalid item in list. Expected one of the following types:")
             valid_types = ", ".join(
                 [f"{t.__name__}" for t in self.model_type_list]
             )
             raise serializers.ValidationError(message.format(valid_types))
    
         def to_representation(self, value):
             return value
  • Code Duplication: If multiple field types share similar functionality (like calling .fail() within .to_internal_value()) consider extracting this logic into a base class if possible.

  • Documentation: Adding more detailed documentation alongside inline comments can help maintainability and understanding, especially for developers who may encounter this codebase later.

  • Type Checking Beyond Conformity: Consider adding checks for attribute existence or other behaviors specific to your domain model if necessary beyond just checking the presence of a single id.

By addressing these points, the code will become more robust, easier to maintain, and better documented, enhancing its reliability and usability across different development teams.

Loading