Hello TGers,
I came across what I think is a cool decorator for Turbogears, that I would
like to share. If you have come across anything similar, please feel free to
share.
It is a decorator that passes the output of a controllers method through a
unix pipe!!!
{{{
import subprocess
def pipe(program, overwriteable=False):
'''
a Turbogears Decorator that takes a command line program and "pipes" the
controllers result through it.
uses the subprocess module.
The controller method must return a string OR if program is False must
return a tuple of output, program
example:
@expose(content_type="text/plain")
@util.pipe('bash')
def cmd(self, x):
"""SECURITY HOLE!!!"""
return x
'''
def entangle(func):
def _pipe(*args, **kw):
output= func(*args, **kw)
if overwriteable and isinstance(output, tuple):
output, theprogram = output
else:
theprogram = program
assert isinstance(output, basestring)
#start the process
p= subprocess.Popen(theprogram.split(),
stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
return p.communicate(output)[0]#execute and return
return _pipe
return entangle
}}}
The example in the doc string is very simple yet extremely powerful! (read:
dangerous[http://localhost:8080/cmd/rm+-rf+%2f]???)
I orginally made this to use graphviz to create some graphs(i could have
just used pydot or something)
Here is a real world example that might be useful. It returns an svg that
displays which users are in which departments(or groups, depending on the
schema):
{{{
@expose(content_type="image/svg+xml")
@pipe('twopi -Tsvg')
def users(self):
s = "digraph G {\n"
#edges
for ud in model.UserDept.select():
s += '"%s"->"%s";' %(ud.user, ud.dept.deptName)
s += "\n"
#uesrs
for u in model.User.select():
s += '"%s";' %u
s+= "\n"
#deptartments(or groups)
for d in model.Dept.select():
s += '"%s"[shape=box];' %d.deptName
s += "\n"
s+="}\n\n"
return s
}}}
You are free to use any of the code, for any reason. I would ask that you
please reference this thread, in some manner.
-Dave
--
David Pattison
530.220.5043
http://davidspattison.com
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---