[Zope] dictionary definition and strings

Dieter Maurer dieter@handshake.de
Thu, 4 Apr 2002 20:28:29 +0200


p.t. writes:
 > as a newbie to Zope and this list, I have a simple question I can't manage 
 > to get an answer.
 > If, in a python script, I have a string ="{'aKey':'aValue'}" and I want to 
 > generate a dictionary from such a string, what should I do?
 > BTW, the function dict() does not work (at least in Zope 2.4.3)
 > TIA for any suggestion,
If you have write access to the file system (where Zope extensions live),
I would recomment to make an External Method "safe_eval" and
use it for the conversion.

"safe_eval" could have the following definition

	    def safe_eval(s,dict=None):
	      '''evaluate *s* in *dict*.'''
	      if dict is None: dict= {}
	      dict['__builtins__']= None
	      return eval(s,dict)


The "dict['__builtins__']= None" makes your "eval" half-way safe.
It is still possible to let your server crash by creating
excessively large objects: e.g. '1000000000 * "123"'.

The package "RestrictedPython" probably allows you to define
safer versions of "eval" but I did not yet look enough into it
that I could give you a precise recipe.


An alternative, but a bit indirect, would be to create a
DTML object consisting of

     <dtml-return expr="your string">

and then call it. The result will be your string evaluated.


Dieter