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
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from typing import Dict

from django.db.models import QuerySet
from django.utils.translation import gettext as _

from application.flow.i_step_node import NodeResult
from application.flow.step_node.function_lib_node.i_function_lib_node import IFunctionLibNode
Expand Down Expand Up @@ -39,7 +40,7 @@ def get_field_value(debug_field_list, name, is_required):
if len(result) > 0:
return result[-1]['value']
if is_required:
raise AppApiException(500, f"{name}字段未设置值")
raise AppApiException(500, _('Field: {name} No value set').format(name=name))
return None


Expand All @@ -55,9 +56,12 @@ def valid_reference_value(_type, value, name):
elif _type == 'string':
instance_type = str
else:
raise Exception(500, f'字段:{name}类型:{_type} 不支持的类型')
raise Exception(_('Field: {name} Type: {_type} Value: {value} Unsupported types').format(name=name,
_type=_type))
if not isinstance(value, instance_type):
raise Exception(f'字段:{name}类型:{_type}值:{value}类型错误')
raise Exception(
_('Field: {name} Type: {_type} Value: {value} Type error').format(name=name, _type=_type,
value=value))


def convert_value(name: str, value, _type, is_required, source, node):
Expand All @@ -84,15 +88,26 @@ def convert_value(name: str, value, _type, is_required, source, node):
v = json.loads(value)
if isinstance(v, dict):
return v
raise Exception("类型错误")
raise Exception(_('type error'))
if _type == 'array':
v = json.loads(value)
if isinstance(v, list):
return v
raise Exception("类型错误")
raise Exception(_('type error'))
return value
except Exception as e:
raise Exception(f'字段:{name}类型:{_type}值:{value}类型错误')
raise Exception(
_('Field: {name} Type: {_type} Value: {value} Type error').format(name=name, _type=_type,
value=value))


def valid_function(function_lib, user_id):
if function_lib is None:
raise Exception(_('Function does not exist'))
if function_lib.permission_type == 'PRIVATE' and str(function_lib.user_id) != str(user_id):
raise Exception(_('No permission to use this function {name}').format(name=function_lib.name))
if not function_lib.is_active:
raise Exception(_('Function {name} is unavailable').format(name=function_lib.name))


class BaseFunctionLibNodeNode(IFunctionLibNode):
Expand All @@ -102,8 +117,7 @@ def save_context(self, details, workflow_manage):

def execute(self, function_lib_id, input_field_list, **kwargs) -> NodeResult:
function_lib = QuerySet(FunctionLib).filter(id=function_lib_id).first()
if not function_lib.is_active:
raise Exception(f'函数:{function_lib.name} 不可用')
valid_function(function_lib, self.flow_params_serializer.data.get('user_id'))
params = {field.get('name'): convert_value(field.get('name'), field.get('value'), field.get('type'),
field.get('is_required'),
field.get('source'), self)
Copy link
Copy Markdown
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 has several issues and areas for improvement:

Issues:

  1. Duplicate get_field_value Method: There seems to be a duplicate get_field_value method that could cause confusion. It's better to remove one of them.

  2. String Translation Missing Parameter:

    • In valid_function, there is an exception message where a parameter _type is missing in the translation string: 'Field: {name} Type: {_type} Unsupported Types'.
  3. Improper Exception Handling: Some exceptions are raised without providing context messages which can make debug harder.

  4. Inconsistent Code Structure:

    • The code structure can be cleaner by grouping related methods together and ensuring consistent formatting.

Optimization Suggestions:

  1. Use More Consistent Variable Names: Use descriptive variable names to enhance readability, such as field_name, reference_value, input_fields, etc.

  2. Remove Unnecessary Imports:

    • If _ (gettext) isn't needed throughout the function, consider removing it to reduce clutter.
  3. Simplify JSON Parsing Error Handling: Extract common handling logic for parsing errors into a separate function or method.

Here's an improved version of the code with these considerations:

from typing import Dict

from django.db.models import QuerySet
import json

from application.flow.i_step_node import NodeResult
from application.flow.step_node.function_lib_node.i_function_lib_node import IFunctionLibNode


def get_field_value(field_list, name, is_required):
    """Get the value from a list of fields."""
    results = [entry['value'] for entry in field_list if entry['name'] == name]
    return results[-1] if len(results) > 0 else (
        f"{name}字段未设置值" if is_required else None
    )


def convert_value(value, _type, is_required=None):
    try:
        if _type == 'object':
            v = json.loads(value)
            if isinstance(v, dict):
                return v
            raise ValueError("类型错误")
        if _type == 'array':
            v = json.loads(value)
            if isinstance(v, list):
                return v
            raise ValueError("类型错误")
        # Add other types if necessary
        return value
    except (json.JSONDecodeError, TypeError):
        if is_required:
            raise ValueError(f'字段:{value} 类型错误')
        return None


class BaseFunctionLibNode(IFunctionLibNode):
    def __init__(self, flow_params_serializer):
        self.flow_params_serializer = flow_params_serializer

    def save_context(self, details, workflow_manage):
        pass

    def execute(self, function_lib_id, input_field_list, **kwargs) -> NodeResult:
        function_lib = QuerySet(FunctionLib).filter(id=function_lib_id).first()
        valid_function(function_lib, self.flow_params_serializer.data.get('user_id'))

        params = {}
        for field in input_field_list:
            field_name = field['name']
            reference_value = get_field_value(input_field_list, field_name, field['is_required'])

            field_result = convert_value(
                reference_value,
                field['type'],
                field['is_required'],
                field['source'],
                self
            )
            
            # Assuming you want to store the resulting values in the dictionary
            params[field_name] = field_result

        return NodeResult(params)


def valid_function(function_lib, user_id):
    if function_lib is None:
        raise ValueError(_("Function does not exist"))
    if function_lib.permission_type == "PRIVATE" and str(function_lib.user_id) != str(user_id):
        raise ValueError(_("No permission to use this function %s").format(function_lib.name))
    if not function_lib.is_active:
        raise ValueError(_("Function %s is unavailable").format(function_lib.name))

This version cleans up the code, improves naming consistency, and provides more meaningful error messages.

Expand Down
17 changes: 16 additions & 1 deletion apps/locales/en_US/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -7472,4 +7472,19 @@ msgid "Add internal function"
msgstr ""

msgid "Batch generate related documents"
msgstr "Batch generate related problems"
msgstr "Batch generate related problems"

msgid "No permission to use this function {name}"
msgstr ""

msgid "Function {name} is unavailable"
msgstr ""

msgid "Field: {name} Type: {_type} Value: {value} Type error"
msgstr ""

msgid "Field: {name} Type: {_type} Value: {value} Unsupported types"
msgstr ""

msgid "Field: {name} No value set"
msgstr ""
15 changes: 15 additions & 0 deletions apps/locales/zh_CN/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -7636,3 +7636,18 @@ msgstr "添加内置函数"

msgid "Batch generate related documents"
msgstr "批量生成问题"

msgid "No permission to use this function {name}"
msgstr "无权使用此模型 {name}"

msgid "Function {name} is unavailable"
msgstr "函数{name} 不可用"

msgid "Field: {name} Type: {_type} Value: {value} Type error"
msgstr "字段: {name} 类型: {_type} 值: {value} 类型错误"

msgid "Field: {name} Type: {_type} Value: {value} Unsupported types"
msgstr "字段: {name} 类型: {_type} 值: {value} 不支持的类型"

msgid "Field: {name} No value set"
msgstr "字段: {name} 未设置值"
17 changes: 16 additions & 1 deletion apps/locales/zh_Hant/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -7645,4 +7645,19 @@ msgid "Add internal function"
msgstr "添加內寘函數"

msgid "Batch generate related documents"
msgstr "批量生成问题"
msgstr "批量生成问题"

msgid "No permission to use this function {name}"
msgstr "無權使用此模型{name}"

msgid "Function {name} is unavailable"
msgstr "函數{name} 不可用"

msgid "Field: {name} Type: {_type} Value: {value} Type error"
msgstr "欄位: {name} 類型: {_type} 值: {value} 類型錯誤"

msgid "Field: {name} Type: {_type} Value: {value} Unsupported types"
msgstr "欄位: {name} 類型: {_type} 值: {value} 不支持的類型"

msgid "Field: {name} No value set"
msgstr "欄位: {name} 未設定值"