"""
WebEnvironment: A trivial wrapper for the cgi module
Usage:
from WebEnvironment import WebEnvironment
server = WebEnvironment() #Initialize environment
server["get_or_post_var"] #Dictionary lookup for GET or POST vars
server.REQUEST_METHOD #Attribute lookup for environment vars
server.write(string) #Output (send headers if not already sent)
server.file("head.html") #Like server.write() for file contents
server.redirect(url string) #Call before headers sent
server.header(key, value) #Set a header ("Content-Type":"text/html" by default)
server.sendHeaders() #Force headers to be sent
"""
__author__ = "Patrick Lioi <patrick_at_lioi_dot_net>"
__date__ = "$Date: 2003/09/01 10:49:03 $"
__version__ = "$Revision: 1.0 $"
import cgi
import os
class WebEnvironment:
_VARS = {}
_headers = {"Content-Type":"text/html"}
_ENV = {}
def __init__(self):
fieldStorage = cgi.FieldStorage()
for key in fieldStorage.keys():
self._VARS[key] = fieldStorage[key].value
self.headers_sent = 0
def sendHeaders(self):
if self.headers_sent == 0:
self.headers_sent = 1
print "\n".join(
["%s: %s"%(key, value)
for (key, value) in self._headers.items()])
print
def __getitem__(self, key):
if not self._VARS.has_key(key):
self._VARS[key]=""
return self._VARS[key]
def __setitem__(self, key, value):
self._VARS[key] = value
def __getattr__(self, name):
if name in self._ENV:
return self._ENV[name]
else:
self._ENV[name] = os.environ.get(name, '')
return self._ENV[name]
def header(self, key, value):
self._headers[key]=value
return self.headers_sent
def redirect(self, location):
self.header("Location", location)
self.sendHeaders()
def write(self, text):
if not self.headers_sent:
self.sendHeaders()
print text
def file(self, filename):
self.write(file(filename).read())