This commit is contained in:
王思川 2022-06-30 14:00:49 +08:00
parent 61c281b16d
commit a67054f2e4
3 changed files with 79 additions and 32 deletions

View File

@ -1,32 +0,0 @@
from DBHelper.MongoHelperInstance import DB_TEST
class TextCodeExecutor(object):
code = ""
params = ""
if __name__ == '__main__':
code_text = DB_TEST.find_single_column(
"模型数据",
"计算函数",
{"函数ID": "I1JxzQef"},
"方法"
)
code_text
eval(code_text)
code_text_01 = """
def eval_operating_margin(arg0, arg1, arg2, arg3):
try:
value = ((arg0 - arg1 - arg2) / arg3) * 100
value = round(value, 2)
operating_margin = value
return operating_margin
except TypeError:
return None
except ZeroDivisionError:
return None
"""

0
Modules/Test/__init__.py Normal file
View File

79
Modules/Test/test.py Normal file
View File

@ -0,0 +1,79 @@
from DBHelper.MongoHelperInstance import DB_TEST
from Utils.ErrorUtil import JustThrowError
class PythonCodeExecutor(object):
def __init__(self, func_name, func_text, params):
self.func_name = ExecutorUtils.check_func_name(func_name)
self.func_text = ExecutorUtils.check_code(func_text)
self.params = ExecutorUtils.check_params(params)
self.result = self.impl()
def impl(self):
try:
exec(self.func_text)
return eval("{func_name}({params})".format(func_name=self.func_name, params=self.params))
except Exception:
raise JustThrowError("代码执行失败")
class ExecutorUtils(object):
@staticmethod
def check_func_name(func_name):
if type(func_name) != str:
raise JustThrowError("方法名称不符合文本格式")
return func_name
@staticmethod
def check_code(code_text):
if type(code_text) != str:
raise JustThrowError("代码不符合文本格式")
# 禁止使用import、eval、exec
ban_words = ["import", "eval", "exec"]
for ban_word in ban_words:
if ban_word in code_text:
raise JustThrowError("代码中带有非法字符")
return code_text
@staticmethod
def check_params(input_params):
if type(input_params) != dict:
raise JustThrowError("传入参数不符合字典格式")
return_params = ""
for item in input_params.items():
return_params = return_params + ("{}={}, ".format(item[0], item[1]))
return_params = return_params[:-2]
return return_params
if __name__ == '__main__':
code_t = DB_TEST.find_single_column(
"模型数据",
"计算函数",
{"函数ID": "I1JxzQef"},
"方法"
)
inp = {
"arg0": 1,
"arg1": 2,
"arg2": 3,
"arg3": 4
}
e = PythonCodeExecutor("cal_operating_margin", code_t, inp)
print(e.result)