Skip to content
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

fix: Defect of embedding application parameters as empty and reporting errors #2278

Merged
merged 1 commit into from
Feb 14, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@

class ApplicationNodeSerializer(serializers.Serializer):
application_id = serializers.CharField(required=True, error_messages=ErrMessage.char(_("Application ID")))
question_reference_address = serializers.ListField(required=True, error_messages=ErrMessage.list(_("User Questions")))
question_reference_address = serializers.ListField(required=True,
error_messages=ErrMessage.list(_("User Questions")))
api_input_field_list = serializers.ListField(required=False, error_messages=ErrMessage.list(_("API Input Fields")))
user_input_field_list = serializers.ListField(required=False, error_messages=ErrMessage.uuid(_("User Input Fields")))
user_input_field_list = serializers.ListField(required=False,
error_messages=ErrMessage.uuid(_("User Input Fields")))
image_list = serializers.ListField(required=False, error_messages=ErrMessage.list(_("picture")))
document_list = serializers.ListField(required=False, error_messages=ErrMessage.list(_("document")))
audio_list = serializers.ListField(required=False, error_messages=ErrMessage.list(_("Audio")))
child_node = serializers.DictField(required=False, allow_null=True, error_messages=ErrMessage.dict(_("Child Nodes")))
child_node = serializers.DictField(required=False, allow_null=True,
error_messages=ErrMessage.dict(_("Child Nodes")))
node_data = serializers.DictField(required=False, allow_null=True, error_messages=ErrMessage.dict(_("Form Data")))


Expand All @@ -33,11 +36,16 @@ def _run(self):
self.node_params_serializer.data.get('question_reference_address')[1:])
kwargs = {}
for api_input_field in self.node_params_serializer.data.get('api_input_field_list', []):
kwargs[api_input_field['variable']] = self.workflow_manage.get_reference_field(api_input_field['value'][0],
api_input_field['value'][1:])
value = api_input_field.get('value', [''])[0] if api_input_field.get('value') else ''
kwargs[api_input_field['variable']] = self.workflow_manage.get_reference_field(value,
api_input_field['value'][
1:]) if value != '' else ''

for user_input_field in self.node_params_serializer.data.get('user_input_field_list', []):
kwargs[user_input_field['field']] = self.workflow_manage.get_reference_field(user_input_field['value'][0],
user_input_field['value'][1:])
value = user_input_field.get('value', [''])[0] if user_input_field.get('value') else ''
kwargs[user_input_field['field']] = self.workflow_manage.get_reference_field(value,
user_input_field['value'][
1:]) if value != '' else ''
# 判断是否包含这个属性
app_document_list = self.node_params_serializer.data.get('document_list', [])
if app_document_list and len(app_document_list) > 0:
Expand All @@ -46,15 +54,17 @@ def _run(self):
app_document_list[1:])
for document in app_document_list:
if 'file_id' not in document:
raise ValueError(_("Parameter value error: The uploaded document lacks file_id, and the document upload fails"))
raise ValueError(
_("Parameter value error: The uploaded document lacks file_id, and the document upload fails"))
app_image_list = self.node_params_serializer.data.get('image_list', [])
if app_image_list and len(app_image_list) > 0:
app_image_list = self.workflow_manage.get_reference_field(
app_image_list[0],
app_image_list[1:])
for image in app_image_list:
if 'file_id' not in image:
raise ValueError(_("Parameter value error: The uploaded image lacks file_id, and the image upload fails"))
raise ValueError(
_("Parameter value error: The uploaded image lacks file_id, and the image upload fails"))

app_audio_list = self.node_params_serializer.data.get('audio_list', [])
if app_audio_list and len(app_audio_list) > 0:
Expand All @@ -63,7 +73,8 @@ def _run(self):
app_audio_list[1:])
for audio in app_audio_list:
if 'file_id' not in audio:
raise ValueError(_("Parameter value error: The uploaded audio lacks file_id, and the audio upload fails."))
raise ValueError(
_("Parameter value error: The uploaded audio lacks file_id, and the audio upload fails."))
return self.execute(**self.node_params_serializer.data, **self.flow_params_serializer.data,
app_document_list=app_document_list, app_image_list=app_image_list,
app_audio_list=app_audio_list,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Your code appears to be well-written and follows Python best practices for Django Rest Framework serializers. Here's a concise analysis of the code:

  1. Serializer Fields:

    • The fields application_id, question_reference_address, api_input_field_list, user_input_field_list, image_list, document_list, and audio_list are correctly defined and have appropriate error messages.
  2. Serializers and SerializersMixin Methods:

    • The _run() method is implemented appropriately within the context of a serializers.ModelSerializer. It extracts data from serialized objects, processes it, and calls execute.
  3. Validation Logic:

    • The validation logic checks for missing file_id fields in uploaded documents, images, and audios and raises appropriate exceptions if they are missing.
  4. Execution:

    • The execution function (execute) takes parameters from both node_params_serializer and flow_params_serializer, along with processed lists (documents, images, audios).

Optimization Suggestions

  1. Data Handling:

    • Instead of hardcoding default values like [0] and [1.], consider using dynamic access where needed (if api_input_field['value']:). This makes the code more readable and allows for potentially cleaner handling of different input scenarios.
  2. Exception Messages:

    • Ensure consistent formatting of exception messages throughout the application. You might want to use f-string interpolation or other methods to avoid repetition in strings that only change in length.
  3. Code Clarity:

    • Break down complex conditional statements into smaller functions if they become too lengthy. For example, separate the logic related to processing each type of media (doc, image, audio) into distinct methods for readability.

Overall, the current implementation is robust and should meet most requirements. If you need more specific improvements or further optimizations, please let me know!

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,20 +220,25 @@ def execute(self, application_id, message, chat_id, chat_record_id, stream, re_c
def get_details(self, index: int, **kwargs):
global_fields = []
for api_input_field in self.node_params_serializer.data.get('api_input_field_list', []):
value = api_input_field.get('value', [''])[0] if api_input_field.get('value') else ''
global_fields.append({
'label': api_input_field['variable'],
'key': api_input_field['variable'],
'value': self.workflow_manage.get_reference_field(
api_input_field['value'][0],
api_input_field['value'][1:])
value,
api_input_field['value'][1:]
) if value != '' else ''
})

for user_input_field in self.node_params_serializer.data.get('user_input_field_list', []):
value = user_input_field.get('value', [''])[0] if user_input_field.get('value') else ''
global_fields.append({
'label': user_input_field['label'],
'key': user_input_field['field'],
'value': self.workflow_manage.get_reference_field(
user_input_field['value'][0],
user_input_field['value'][1:])
value,
user_input_field['value'][1:]
) if value != '' else ''
})
return {
'name': self.node.properties.get('stepName'),
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 Python function has some issues that need to be addressed:

  1. The code contains multiple places where a single dictionary access is made with indexing (e.g., api_input_field['value'][0]). This can lead to errors if the list is empty, especially since '[]' cannot be split into parts.

  2. Using '''''' for multi-line strings introduces unnecessary escaping (\n).

  3. There's duplication across the two loops (for user_input_field) which could be simplified by iterating over one of them.

Here are specific improvements and optimizations:

Improvements/Optimizations

  1. Handle cases where values might not be present properly inside lists or dictionaries before splitting.
  2. Simplify the loop iterations; they are similar except for different types of fields being checked.
  3. Remove redundant checks for string content after handling default values.

Suggested Code Snippet:

def execute(self, application_id, message, chat_id, chat_record_id, stream, re_context=True):
    global_fields = []

    api_fields_list = self.node_params_serializer.data.get('api_input_field_list', [])
    user_fields_list = self.node_params_serialzier.data.get('user_input_field_list', [])

    fields_list_of_lists = [api_fields_list, user_fields_list]

    for api_user_fields in fields_list_of_lists:
        for field in api_user_fields:
            # Avoid using get on NoneType causing TypeError
            variable = field.get('variable', '').lower()
            # Check if value exists and it's not an empty string before processing
            reference_value = (
                self.workflow_manage.get_reference_field(
                    field.get('value', ['', ''])[0].strip(),
                    field.get('type', '')
                    
                    )
                
                if field.get('value', '') != '' else ''
            )

            global_fields.append({
                'label': variable,
                'key': variable,
                'value': reference_value or ''
            })

    return {
        'name': self.node.properties.get('stepName')
    }

Explanation

  • Avoiding Typos: Directly accessing nested keys without checking them first ensures robustness against missing data.
  • Stripping Values: Use .strip() to clean up input values and remove leading/trailing spaces.
  • Conditional Checks: Ensure conditionals handle all potential scenarios correctly, including when fields lack required information or contain invalid values.
  • Simplified Loops: Combining loops simplifies the logic while enhancing readability and maintainability.

This approach should resolve most detected issues and improve performance in case there are many items within the fields_list_of_lists.

Expand Down