ITADN

How to access array and dicts

#300Closedperotom 创建于 2025-03-31
question
P
perotomcommented
I am trying to allow users to run the following code: ``` python from RestrictedPython import compile_restricted, safe_builtins class dotdict(dict): """dot.notation access to dictionary attributes""" __getattr__ = dict.get test = [{'id': 1}, {'id': 2}] variables = { 'test': map(lambda x: dotdict(x), test) } safe_globals = { '__builtins__': safe_builtins, # built-in policy allowing basic Python functions '_getitem_': lambda x, y: x[y] } safe_locals = {**variables} user_code = ''' result = test[0].id ''' # Compile the user-provided code into a restricted code object restricted_code = compile_restricted(user_code, '<usercode>', 'exec') # Execute the restricted code within the restricted context exec(restricted_code, safe_globals, safe_locals) print('Result', safe_locals['result']) ``` but I get the error `name '_getitem_' is not defined`. I tried to implement my own `_getitem_` but it doesn't seem to get picked up. Overall I want to allow array index access and dict name access.
关闭于 2025-04-07 2 条评论