Skip to content

Commit 7eeec79

Browse files
committed
perf: Function library execution
1 parent decd339 commit 7eeec79

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

apps/common/util/function_code.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,12 @@
77
@desc:
88
"""
99
import os
10+
import pickle
1011
import subprocess
1112
import sys
1213
import uuid
1314
from textwrap import dedent
1415

15-
from diskcache import Cache
16-
1716
from smartdoc.const import BASE_DIR
1817
from smartdoc.const import PROJECT_DIR
1918

@@ -37,14 +36,16 @@ def _createdir(self):
3736
old_mask = os.umask(0o077)
3837
try:
3938
os.makedirs(self.sandbox_path, 0o700, exist_ok=True)
39+
os.makedirs(os.path.join(self.sandbox_path, 'execute'), 0o700, exist_ok=True)
40+
os.makedirs(os.path.join(self.sandbox_path, 'result'), 0o700, exist_ok=True)
4041
finally:
4142
os.umask(old_mask)
4243

4344
def exec_code(self, code_str, keywords):
4445
_id = str(uuid.uuid1())
4546
success = '{"code":200,"msg":"成功","data":exec_result}'
4647
err = '{"code":500,"msg":str(e),"data":None}'
47-
path = r'' + self.sandbox_path + ''
48+
result_path = f'{self.sandbox_path}/result/{_id}.result'
4849
_exec_code = f"""
4950
try:
5051
import os
@@ -60,32 +61,31 @@ def exec_code(self, code_str, keywords):
6061
for local in locals_v:
6162
globals_v[local] = locals_v[local]
6263
exec_result=f(**keywords)
63-
from diskcache import Cache
64-
cache = Cache({path!a})
65-
cache.set({_id!a},{success})
64+
import pickle
65+
with open({result_path!a}, 'wb') as file:
66+
file.write(pickle.dumps({success}))
6667
except Exception as e:
67-
from diskcache import Cache
68-
cache = Cache({path!a})
69-
cache.set({_id!a},{err})
68+
with open({result_path!a}, 'wb') as file:
69+
file.write(pickle.dumps({err}))
7070
"""
7171
if self.sandbox:
7272
subprocess_result = self._exec_sandbox(_exec_code, _id)
7373
else:
7474
subprocess_result = self._exec(_exec_code)
7575
if subprocess_result.returncode == 1:
7676
raise Exception(subprocess_result.stderr)
77-
cache = Cache(self.sandbox_path)
78-
result = cache.get(_id)
79-
cache.delete(_id)
77+
with open(result_path, 'rb') as file:
78+
result = pickle.loads(file.read())
79+
os.remove(result_path)
8080
if result.get('code') == 200:
8181
return result.get('data')
8282
raise Exception(result.get('msg'))
8383

8484
def _exec_sandbox(self, _code, _id):
85-
exec_python_file = f'{self.sandbox_path}/{_id}.py'
85+
exec_python_file = f'{self.sandbox_path}/execute/{_id}.py'
8686
with open(exec_python_file, 'w') as file:
8787
file.write(_code)
88-
os.system(f"chown {self.user}:{self.user} {exec_python_file}")
88+
os.system(f"chown {self.user}:root {exec_python_file}")
8989
kwargs = {'cwd': BASE_DIR}
9090
subprocess_result = subprocess.run(
9191
['su', '-s', python_directory, '-c', "exec(open('" + exec_python_file + "').read())", self.user],

0 commit comments

Comments
 (0)