Skip to content

fix: application title error #2872

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
Apr 14, 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
4 changes: 4 additions & 0 deletions apps/application/serializers/application_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1071,6 +1071,7 @@ def edit(self, instance: Dict, with_valid=True):
for update_key in update_keys:
if update_key in instance and instance.get(update_key) is not None:
application.__setattr__(update_key, instance.get(update_key))
print(application.name)
application.save()

if 'dataset_id_list' in instance:
Expand All @@ -1089,6 +1090,7 @@ def edit(self, instance: Dict, with_valid=True):
chat_cache.clear_by_application_id(application_id)
application_access_token = QuerySet(ApplicationAccessToken).filter(application_id=application_id).first()
# 更新缓存数据
print(application.name)
get_application_access_token(application_access_token.access_token, False)
return self.one(with_valid=False)

Expand Down Expand Up @@ -1141,6 +1143,8 @@ def get_work_flow_model(instance):
instance['file_upload_enable'] = node_data['file_upload_enable']
if 'file_upload_setting' in node_data:
instance['file_upload_setting'] = node_data['file_upload_setting']
if 'name' in node_data:
instance['name'] = node_data['name']
break

def speech_to_text(self, file, with_valid=True):
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 code provided is a part of an object-oriented system with a method edit inside it. The function takes an instance dictionary instance and some optional parameters. Here’s a brief overview of the main parts:

  1. Updating Application Attributes: It iterates over keys in the update_keys, checks if they exist in the instance, and sets them using __setattr__. After setting the attributes, it prints the attribute name.

  2. Saving Changes: After processing all updates, it saves the updated application to the database.

  3. Handling Dataset ID List Update: If the dataset_id_list key exists in the instance, it clears previous cache entries based on this list. It also fetches an application access token and refreshes its cache data.

  4. Workflow Model Fetching Method: This method finds a specific workflow model where the file upload setting can be applied and returns the necessary fields.

  5. Speech-to-Text Conversion: This method converts audio files into text based on the passed file path (file). It also allows specifying whether validation should occur.

Optimization Suggestions and Potential Issues:

Optimization Suggestions

  1. Use Context Managers: Use context managers for database operations like connections or sessions to ensure resources are properly managed.

  2. Avoid Redundant Saves: Ensure that saving happens only once after all changes have been made instead of multiple times.

  3. Refactor Cache Clearing Logic: Consider optimizing how cache clearing works; batching might reduce overhead.

  4. Error Handling: Implement better error handling around database calls and other critical operations.

Possible Issues

  1. Database Integrity Checks: While caching helps, direct database manipulations without proper integrity checks could lead to inconsistencies and data loss.

  2. Concurrency Control: Without explicit locks or transaction management, concurrent modifications to the same records could cause race conditions.

  3. Code Readability: Complex logic within methods can make the code harder to read and maintain. Simplifying sections and adding comments could improve readability.

Here's a slightly optimized version of the class based on these points:

from typing import Dict
import logging

class YourClass:
    log = logging.getLogger(__name__)

    def __init__(self):
        # Initialize your logger here (e.g., logging.basicConfig())
        self.log.debug("Instance initialized")

    def edit(self, instance: Dict, with_valid=True):
        self.logger.info(f"Editing instance with update keys {update_keys}")
        
        for update_key in update_keys:
            if update_key in instance and instance.get(update_key) is not None:
                setattr(self.application, update_key, instance[update_key])
            
        self.save_changes()

        if 'dataset_id_list' in instance:
            self.delete_previous_records(instance['dataset_id_list'])
            self.refresh_application_access_token()

        return self.one(with_valid=False)

    def save_changes(self):
        try:
            with db_session.begin():
                self.application.save()
                self.log.info("Changes saved successfully")
        except Exception as e:
            self.log.error(f"Failed to save changes: {str(e)}")

    def delete_previous_records(self, dataset_ids):
        try:
            BatchDeleteModel(dataset_entry=DatasetEntry).where(DatasetEntry.dataset_id << dataset_ids).execute()
            self.log.info("Previous records deleted successfully")
        except Exception as e:
            self.log.error(f"Failed to delete records: {str(e)}")

    @staticmethod
    def get_work_flow_model(instance):
        wf_query_set = WorkflowEntries.where(Node.workflow == True)
        for entry in wf_query_set:
            if entry.file_type == 'audio':
                instance['file_upload_enable'] = entry.node_data.get('file_upload_enable')
                instance['file_upload_setting'] = entry.node_data.get('file_upload_setting')
                break

    def speech_to_text(self, file, with_valid=True):
        self.logger.warning("Not implemented")

This refactored approach uses contextual logging and handles exceptions during database operations to enhance reliability and maintainability.

Expand Down