Skip to content

Instantly share code, notes, and snippets.

@westmark
Created February 21, 2012 13:51
Show Gist options
  • Save westmark/1876671 to your computer and use it in GitHub Desktop.
Save westmark/1876671 to your computer and use it in GitHub Desktop.
Testing RestrictedPython
from RestrictedPython import compile_restricted
from RestrictedPython.PrintCollector import PrintCollector
from RestrictedPython.Guards import safe_builtins, full_write_guard
def getitem(obj, index):
if obj is not None and type(obj) in (list, tuple, dict):
return obj[index]
raise Exception()
_print_ = PrintCollector
_write_ = full_write_guard
_getattr_ = getattr
_getitem_ = getitem
restricted_globals = dict(__builtins__=safe_builtins)
restricted_globals['_print_'] = _print_
restricted_globals['_write_'] = _write_
restricted_globals['_getattr_'] = _getattr_
restricted_globals['_getitem_'] = _getitem_
class Tester(object):
def __init__(self):
self._a = 1
@property
def a(self):
return self._a
def set_a(self, nr):
self._a = nr
def do_it(self, nr):
print nr
restricted_globals['Tester'] = Tester
restricted_globals['tester'] = Tester()
src = '''
v = (1,2,3)
def snurr():
tester.set_a(2)
tester.do_it(tester.a)
snurr()
'''
code = compile_restricted(src, '<string>', 'exec')
exec(code) in restricted_globals
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment