Simple CGI Script in Python: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "The Python documentation is a pretty good place to start: http://docs.python.org/library/cgi.html <source lang="python"> print "Content-Type: text/html" # HTML is following ...")
 
No edit summary
Line 5: Line 5:
print "Content-Type: text/html"    # HTML is following
print "Content-Type: text/html"    # HTML is following
print                              # blank line, end of headers
print                              # blank line, end of headers
</source>
== Show Headers ==
HTTP headers are simply environment variables. Use the os.environ dictionary to get at them.
<source lang="python">
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
print "Content-type: text/html"
print
# show all headers as an HTML definition list
print "<dl>"
for key in os.environ:
    print "<dt>" + key + "</dt>"
    print "<dd>" + os.environ[key] + "</dd>"
print "</dl>"
</source>
</source>

Revision as of 17:52, 12 January 2011

The Python documentation is a pretty good place to start: http://docs.python.org/library/cgi.html

print "Content-Type: text/html"     # HTML is following
print                               # blank line, end of headers

Show Headers

HTTP headers are simply environment variables. Use the os.environ dictionary to get at them.

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os

print "Content-type: text/html"
print

# show all headers as an HTML definition list

print "<dl>"
for key in os.environ:
    print "<dt>" + key + "</dt>"
    print "<dd>" + os.environ[key] + "</dd>"
print "</dl>"