Skip to content

Commit dc2b83b

Browse files
committed
chore: replace pickle with json for data serialization in tool_code.py
1 parent d94871b commit dc2b83b

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

apps/common/utils/tool_code.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# coding=utf-8
22
import ast
33
import os
4-
import pickle
4+
import json
55
import subprocess
66
import sys
77
from textwrap import dedent
@@ -40,15 +40,15 @@ def _createdir(self):
4040
def exec_code(self, code_str, keywords):
4141
self.validate_banned_keywords(code_str)
4242
_id = str(uuid.uuid7())
43-
success = '{"code":200,"msg":"成功","data":exec_result}'
43+
success = '{"code":200,"msg":"成功","data":json.dumps(exec_result, default=str)}'
4444
err = '{"code":500,"msg":str(e),"data":None}'
4545
result_path = f'{self.sandbox_path}/result/{_id}.result'
4646
python_paths = CONFIG.get_sandbox_python_package_paths().split(',')
4747
_exec_code = f"""
4848
try:
4949
import os
5050
import sys
51-
import pickle
51+
import json
5252
path_to_exclude = ['/opt/py3/lib/python3.11/site-packages', '/opt/maxkb-app/apps']
5353
sys.path = [p for p in sys.path if p not in path_to_exclude]
5454
sys.path += {python_paths}
@@ -64,20 +64,20 @@ def exec_code(self, code_str, keywords):
6464
for local in locals_v:
6565
globals_v[local] = locals_v[local]
6666
exec_result=f(**keywords)
67-
with open({result_path!a}, 'wb') as file:
68-
file.write(pickle.dumps({success}))
67+
with open({result_path!a}, 'w') as file:
68+
file.write(json.dumps({success}))
6969
except Exception as e:
70-
with open({result_path!a}, 'wb') as file:
71-
file.write(pickle.dumps({err}))
70+
with open({result_path!a}, 'w') as file:
71+
file.write(json.dumps({err}))
7272
"""
7373
if self.sandbox:
7474
subprocess_result = self._exec_sandbox(_exec_code, _id)
7575
else:
7676
subprocess_result = self._exec(_exec_code)
7777
if subprocess_result.returncode == 1:
7878
raise Exception(subprocess_result.stderr)
79-
with open(result_path, 'rb') as file:
80-
result = pickle.loads(file.read())
79+
with open(result_path, 'r') as file:
80+
result = json.loads(file.read())
8181
os.remove(result_path)
8282
if result.get('code') == 200:
8383
return result.get('data')

0 commit comments

Comments
 (0)