Skip to content

Commit dc04d46

Browse files
committed
refactor: replace diskcache with pickle for result handling and organize sandbox directories
1 parent 4da75ac commit dc04d46

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

apps/common/utils/tool_code.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
# coding=utf-8
22

33
import os
4+
import pickle
45
import subprocess
56
import sys
67
from textwrap import dedent
78

89
import uuid_utils.compat as uuid
9-
from diskcache import Cache
1010

1111
from maxkb.const import BASE_DIR, CONFIG
1212
from maxkb.const import PROJECT_DIR
@@ -31,14 +31,16 @@ def _createdir(self):
3131
old_mask = os.umask(0o077)
3232
try:
3333
os.makedirs(self.sandbox_path, 0o700, exist_ok=True)
34+
os.makedirs(os.path.join(self.sandbox_path, 'execute'), 0o700, exist_ok=True)
35+
os.makedirs(os.path.join(self.sandbox_path, 'result'), 0o700, exist_ok=True)
3436
finally:
3537
os.umask(old_mask)
3638

3739
def exec_code(self, code_str, keywords):
3840
_id = str(uuid.uuid7())
3941
success = '{"code":200,"msg":"成功","data":exec_result}'
4042
err = '{"code":500,"msg":str(e),"data":None}'
41-
path = r'' + self.sandbox_path + ''
43+
result_path = f'{self.sandbox_path}/result/{_id}.result'
4244
python_paths = CONFIG.get_sandbox_python_package_paths().split(',')
4345
_exec_code = f"""
4446
try:
@@ -59,29 +61,28 @@ def exec_code(self, code_str, keywords):
5961
for local in locals_v:
6062
globals_v[local] = locals_v[local]
6163
exec_result=f(**keywords)
62-
from diskcache import Cache
63-
cache = Cache({path!a})
64-
cache.set({_id!a},{success})
64+
import pickle
65+
with open({result_path!a}, 'wb') as file:
66+
file.write(pickle.dumps({success}))
6567
except Exception as e:
66-
from diskcache import Cache
67-
cache = Cache({path!a})
68-
cache.set({_id!a},{err})
68+
with open({result_path!a}, 'wb') as file:
69+
file.write(pickle.dumps({err}))
6970
"""
7071
if self.sandbox:
7172
subprocess_result = self._exec_sandbox(_exec_code, _id)
7273
else:
7374
subprocess_result = self._exec(_exec_code)
7475
if subprocess_result.returncode == 1:
7576
raise Exception(subprocess_result.stderr)
76-
cache = Cache(self.sandbox_path)
77-
result = cache.get(_id)
78-
cache.delete(_id)
77+
with open(result_path, 'rb') as file:
78+
result = pickle.loads(file.read())
79+
os.remove(result_path)
7980
if result.get('code') == 200:
8081
return result.get('data')
8182
raise Exception(result.get('msg'))
8283

8384
def _exec_sandbox(self, _code, _id):
84-
exec_python_file = f'{self.sandbox_path}/{_id}.py'
85+
exec_python_file = f'{self.sandbox_path}/execute/{_id}.py'
8586
with open(exec_python_file, 'w') as file:
8687
file.write(_code)
8788
os.system(f"chown {self.user}:root {exec_python_file}")

0 commit comments

Comments
 (0)