Wednesday, January 22, 2014

Python CGI

/var/www/cgi-bin

EXAMPLE 1:

#!/usr/bin/python
print "Content-type: text/html"
print

print ""
print "Our first CGI python Form"
print ""
print "
"
print "Name:
"
print "Title:
"
print "E-Mail:
"
print ""
print "
"
print "
"
print "
"

#!/usr/bin/python
print "Content-type: text/html"

import cgi

print "Content-type: text/html"
print

form = cgi.FieldStorage()

name = form["name"].value
title = form["title"].value
email = form["email"].value

print "Name:\t", name
print "Title:\t", title
print "E-Mail:\t", email


EXAMPLE 2:
#!/usr/bin/python

print "Content-type: text/html"
print

print ""
print "Our first CGI python Form"
print ""

# Different between get and post
print "
"
print "Name:
"
print ""
print "
"
print "
"
print "
"

#!/usr/bin/python
import cgi
form = cgi.FieldStorage() # instantiate only once!
name = form.getfirst('name', 'empty')

# Avoid script injection escaping the user input
name = cgi.escape(name)

print "Content-Type: text/html"

print """\
Content-Type: text/html\n

The submitted name was "%s"

""" % name


EXMPLE 3:

# Webpython.code.net
import cgitb; cgitb.enable()

# The subprocess module is new in 2.4
import os, urllib, subprocess as sub

# Retrieve the command from the query string
# and unencode the escaped %xx chars
str_command = urllib.unquote(os.environ['QUERY_STRING'])

p = sub.Popen(['/bin/bash', '-c', str_command],
    stdout=sub.PIPE, stderr=sub.STDOUT)
output = urllib.unquote(p.stdout.read())

print """\
Content-Type: text/html\n

$ %s
%s
""" % (str_command, output)


http://www.elvenware.com/charlie/development/web/Python/PythonScripts.html