执行 Python 代码节点 参数: node: 节点实体 inputs: 输入数据(来自前驱节点) context: 执行上下文 返回: 代码执行后 result 变量的值
(self, node: Node, inputs: dict[str, Any], context: dict[str, Any])
| 69 | } |
| 70 | |
| 71 | async def execute(self, node: Node, inputs: dict[str, Any], context: dict[str, Any]) -> Any: |
| 72 | """执行 Python 代码节点 |
| 73 | |
| 74 | 参数: |
| 75 | node: 节点实体 |
| 76 | inputs: 输入数据(来自前驱节点) |
| 77 | context: 执行上下文 |
| 78 | |
| 79 | 返回: |
| 80 | 代码执行后 result 变量的值 |
| 81 | """ |
| 82 | code = node.config.get("code", "") |
| 83 | |
| 84 | if not code: |
| 85 | raise DomainError("Python 节点缺少代码") |
| 86 | |
| 87 | # 检查禁止的模块和操作 |
| 88 | code_lower = code.lower() |
| 89 | for forbidden in self.FORBIDDEN_KEYWORDS: |
| 90 | if forbidden.lower() in code_lower: |
| 91 | raise DomainError(f"Python 代码包含被禁止的操作: {forbidden}") |
| 92 | |
| 93 | # 准备执行环境 |
| 94 | exec_context = { |
| 95 | "__builtins__": self.SAFE_BUILTINS, |
| 96 | } |
| 97 | |
| 98 | # 将输入映射为 input1, input2, ... |
| 99 | for i, (_key, value) in enumerate(inputs.items(), 1): |
| 100 | exec_context[f"input{i}"] = value |
| 101 | |
| 102 | # 添加上下文变量 |
| 103 | exec_context["context"] = context |
| 104 | |
| 105 | try: |
| 106 | # 执行代码 |
| 107 | exec(code, exec_context) |
| 108 | |
| 109 | # 返回结果(假设代码中有 result 变量赋值) |
| 110 | return exec_context.get("result") |
| 111 | |
| 112 | except SyntaxError as e: |
| 113 | raise DomainError(f"Python 代码执行失败: 语法错误 - {str(e)}") from e |
| 114 | except Exception as e: |
| 115 | raise DomainError(f"Python 代码执行失败: {str(e)}") from e |