我想安全地执行一些用户定义的代码。为此,我想使用 RestrictedPython 来限制用户可以访问哪些模块和变量。用户提交的代码有一些准则:
这是我当前的版本:
from RestrictedPython import compile_restricted
from RestrictedPython import safe_builtins
import pandas as pd
import math
import random
import datetime
d = None
x = None
def MakeDFDict():
data1 = {"A": [1, 2, 3, 4, 5], "B": [2, 4, 6, 8, 10]}
data2 = {"C": [3, 6, 9, 12, 15], "D": [4, 8, 12, 16, 20]}
return {"Dataframe 1": pd.DataFrame(data1),
"Dataframe 2": pd.DataFrame(data2)}
def run_code_safely(code):
global d
d = MakeDFDict()
global x
x = None
globals_dict = {"d": d}
allowed_modules = {
"__builtins__": safe_builtins,
"math": math,
"random": random,
"datetime": datetime,
"pandas": pd
}
restricted_globals = {
"__builtins__": safe_builtins,
"__import__": lambda name, globals=None, locals=None, fromlist=(), level=0: __import__(name),
"getattr": lambda obj, attr: getattr(obj, attr)
}
restricted_globals.update(allowed_modules)
bytecode = RestrictedPython.compile_restricted(code, '<inline code>', 'exec')
try:
exec(bytecode, restricted_globals, globals_dict)
except Exception as e:
return f"Error occurred while running the code:\n{e}"
x = globals_dict['x']
return x
code = """
x = []
for name, df in d.items():
x.append(name, df)
"""
run_code_safely(code)
这给出了以下错误:
Error occurred while running the code: name '_iter_unpack_sequence_' is not defined
我在这里错过了什么?有没有办法让 exec 产生更具解释性的错误消息?