Saturday, February 13, 2010

Twisted Web in 60 seconds: CGI

Greetings, and welcome back to "Twisted Web in 60 Seconds". In the previous entry, back at the beginning of December, I promised to cover Twisted Web's proxying capabilities. For various reasons I've decided to dump that topic and cover something else instead. So, prepare to learn about Twisted Web's CGI capabilities!

twisted.web.twcgi.CGIScript and twisted.web.twcgi.FilteredScript are the two most interesting classes in this area. They are both Resource subclasses, so many of the features of resources that I've covered so far apply to them. For example, you can use them as the resource in an .rpy script:

from twisted.web.twcgi import CGIScript
resource = CGIScript("/path/to/") might look like this:


echo "Content-Type: text/plain"

That is, just a regular CGI - nothing special about Twisted Web going on there.

If you need to specify an interpreter for some reason (for example, the CGI itself isn't set executable, or doesn't specify its own interpreter with #! on the first line), you can use FilteredScript instead of CGIScript:

from twisted.web.twcgi import FilteredScript

resource = FilteredScript("/path/to/")
resource.filter = "/bin/sh"

Set up this way, /bin/sh will always be run and passed an argument of /path/to/