Using RestrictedPython
Evan Simpson
evan at 4-am.com
Mon Oct 6 10:54:05 EDT 2003
Rasjid Wilcox wrote:
> Below is my test program. Am I doing this the right way?
Well, you've got the basics of compiling and executing the compiled
code. What you need to understand about RestrictedPython, though, is
that while it provides the raw material for restricted execution, you
need to supply a policy implementation. You hook up your implementation
by providing a set of specially named objects in the global dict that
you use for execution of code. Specifically:
1. "_print_" is a callable object that returns a handler for print
statements. This handler must have a 'write()' method that accepts a
single string argument, and must return a string when called. The
PrintCollector module has an implementation.
2. "_write_" is a guard function taking a single argument. If the
object passed to it may be written to, it should be returned, otherwise
the guard function should raise an exception.
3. "_getattr_" and "_getitem_" are guard functions, each of which takes
two arguments. The first is the base object to be accessed, while the
second is the attribute name or item index that will be read. The guard
function should return the attribute or subitem, or raise an exception.
4. "__import__" is the normal Python import hook, and should be used to
control access to Python packages and modules.
5. "__builtins__" is the normal Python builtins dictionary, which should
be weeded down to a set that cannot be used to get around your
restrictions. A usable "safe" set is in the Guards module.
To help illustrate how this works under the covers, here's an example
function along with (sort of) how it looks after restricted compilation:
def f(x):
x.foo = x.foo + x[0]
print x
return printed
def f(x):
# Make local variables from globals.
_print = _print_()
_write = _write_
_getattr = _getattr_
_getitem = _getitem_
#
_write(x).foo = _getattr(x, 'foo') + _getitem(x, 0)
print >>_print, x
return _print()
Cheers,
Evan @ 4-am
More information about the Python-list
mailing list