Skip to content

Instantly share code, notes, and snippets.

@dylan-evans
Created March 15, 2011 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylan-evans/870832 to your computer and use it in GitHub Desktop.
Save dylan-evans/870832 to your computer and use it in GitHub Desktop.
Execute legacy CGI in modern web app
#!/usr/bin/python
# Execute a cgi script
# Created in order to allow legacy cgi to be used in modern web apps
# Main cgiexec module
from subprocess import Popen, PIPE
import re
# CGI must be dead, i can't get hold of a standard
# For now i am referenceing Apache mod_cgi
# http://httpd.apache.org/docs/current/mod/mod_cgi.html
# Got it: http://graphcomp.com/info/specs/cgi11.html
defaults = {
'GATEWAY_INTERFACE': 'CGI/1.1',
# 'PATH_INFO': '',
# 'PATH_TRANSLATED': '',
'QUERY_STRING': '',
'REMOTE_ADDR': '127.0.0.1',
'SERVER_NAME': 'localhost',
'SERVER_PORT': '80',
'SERVER_PROTOCOL': 'HTTP/1.1',
'SERVER_SOFTWARE': 'CGIExec'
}
class CGIExec(object):
"""Execute a file as a CGI script
Setup a CGI environment
"""
def __init__(self, path, env={}, eol='\r\n'):
self.path = path
self.env = dict(defaults).update(env)
self.eol = eol # Output newline, defaults to standard
def run(self, *args):
"""Run the command with the given arguments"""
if args:
args = list(args).insert(0, self.path)
else:
args = [self.path]
p = Popen(args, stdout=PIPE, shell=True, env=self.env)
data = p.communicate()[0]
# Maybe just return this? So the object remains mostly stateless
return self.parse_response(data)
#return page
def parse_response(self, output):
"""Seperate headers from body content"""
lines = re.split(r'\r\n|\n', output)
headers = {}
for idx, opt in enumerate(lines):
if len(opt.strip()) == 0: break # End of headers
res = opt.split(':')
headers[res[0]] = res[1]
page = self.eol.join(lines[idx+1:])
return (page, headers)
if __name__ == '__main__':
c = CGIExec('./test.sh',{})
print c.run()[0]
#!/bin/sh
# Sample CGI script for testing
echo "Content-Type: text/plain"
echo
echo "Hello, World!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment