[Chicago] Passing an expression into Python then executing it

Brantley Harris deadwisdom at gmail.com
Mon Dec 3 23:20:16 CET 2012


Essentially you have instructions that are a pair (regex, result).  How
complex do you want ``result`` to be?  Kumar is right that you can be
infinitely complex by passing it in as a pure function.  This is likely
you're best bet.

However, if you need it to be a string, because of easy configuration or
some other reason, then you have to pass something meaningful into it.

You have a few options after that, one is to just have a {0, 1, 2, 3, ...,
n} and return the m.groups()[n].  But something tells me you want something
a bit more complex.


Another is completely unsafe, security-wise, but unquestionably easy and
powerful:

   def get_result(m, code):
       return eval(code, {}, {'m': m})

Then you can do:
   >>> regex, result = 'Connection closed by ([a-zA-Z0-9.-]+)',
'm.groups()[0]'
   >>> m = re.match(regex, 'Connection closed by TheCloser')
   >>> print get_result(m, result)
   TheCloser

This is, as I said, completely insecure.  If anyone is allowed to specify
the "result", they could do whatever they wanted to your system.


Another is to run it as a template.  Safe and secure, and allows rather
high complexities:

   from jinja2 import Template
   def get_result(m, code):
       return Template(code).render(m=m)

Then you can do:
   >>> regex, result = 'Connection closed by ([a-zA-Z0-9.-]+)', '{{
m.groups()[0] }}'
   >>> m = re.match(regex, 'Connection closed by TheCloser')
   >>> print get_result(m, result)
   TheCloser

Along with any of the other complexities available in the Jinja2 Template
Library.


On Mon, Dec 3, 2012 at 2:33 PM, D Mahoney <dan at streemit.net> wrote:

> For
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20121203/fc713fc4/attachment.html>


More information about the Chicago mailing list