Both ASP and mod_python allow you to deploy web applications written in Python. This recipe allows you to push that decision down to your deployers, rather than your programmers. By abstracting the webserver, the same Python application can be deployed on either platform without rewriting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | ###############
# paramset.py #
###############
class ParamSet:
"""A mutable set of parameters.
data: a dictionary of the form: {Name: Value}.
_Value_ will be a string, unless multiple parameters
of the same _Name_ are created, in which case _Value_
will become a list of strings.
"""
data = {}
def __init__(self):
self.data = {}
def add_param(self, name, value):
name, value = str(name), str(value)
if self.data.has_key(name):
if type(self.data[name]) != type([]):
# Current value is not a list.
# Create a list for the value instead.
self.data[name] = [self.data[name]]
self.data[name].append(value)
else:
self.data[name] = value
def flush(self):
self.data = {}
#############
# uihtml.py #
#############
import re
from classloader import get_func
import paramset
class UserInterfaceHTML:
"""A base class for HTML interfaces."""
requestParams = paramset.ParamSet()
user = ''
OK = 200
HTTP_NOT_ACCEPTABLE = 406
dispatchre = re.compile('([^/]*)\.htm$')
dispatches = {'default': 'myapp.interface.default.view',
'directory': 'myapp.interface.directory.view',
'directoryedit': 'myapp.interface.directory.edit'}
hostname = ''
port = 80
protocol = 'http'
path = '/'
script = ''
def dispatch(self):
"""Process a URI and invoke the appropriate handler."""
page = self.dispatchre.search(self.script)
try:
nextHandler = get_func(self.dispatches[page.group(1)])
except KeyError:
nextHandler = get_func(self.dispatches['default'])
return nextHandler(self)
def write_header(self, documentTitle):
"""Write a standard HTML header."""
self.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n')
self.write(' "http://www.w3.org/TR/xhtml1/DTD/strict.dtd">\n')
self.write('<html xmlns="http://www.w3.org/TR/xhtml1/strict"')
self.write(' xml:lang="en" lang="en">\n\n')
self.write("<head>\n")
self.write(" <title>%s</title>\n" % documentTitle)
self.write("</head>\n")
def uri_port(self):
if self.port == 80: return ''
return ':%s' % self.port
def location(self, includeScriptName=False):
if includeScriptName:
return '%s://%s%s%s/%s' % (self.protocol, self.hostname,
self.uri_port(), self.path,
self.script)
return '%s://%s%s%s/' % (self.protocol, self.hostname,
self.uri_port(), self.path)
################################
# myapp.interface.directory.py #
################################
from objectkit import objectservers
def view(UI):
"""Write the requested Directory object page out to the client."""
# Locate the requested Directory object.
reqID = UI.requestParams.value('ID', '0')
reqDir = objectservers.recall('Directory', reqID)
# Write assembled page out to the client.
UI.write_header('Directory %s' % reqID)
UI.write("<body>You are looking at Directory record %s, %s" % \
(reqID, reqDir.name()))
UI.write("</body></html>")
return UI.OK
def edit(UI):
"""Edit the requested Directory object page."""
# Locate the requested Directory object.
reqID = UI.requestParams.value('ID', '0')
reqDir = objectservers.recall('Directory', reqID)
reqDir.name = UI.requestParams.value('name', '')
# Write page out to the client.
UI.write_header('Directory %s' % reqID)
UI.write("<body>You just edited Directory record %s, %s" % \
(reqID, reqDir.name()))
UI.write("</body></html>")
return UI.OK
########### ASP ###########
############
# uiasp.py #
############
from uihtml import *
from cgi import parse_qs
class UserInterfaceASP(UserInterfaceHTML):
"""Provide an HTML interface built with Microsoft's ASP framework."""
response = None
def __init__(self, anApp, aRequest, aResponse):
"""Create an interface using the ASP top-level objects from a Request."""
# Set response hook.
self.response = aResponse
# Set uri data from Request object.
if aRequest.ServerVariables("HTTPS") == "ON":
self.protocol = 'https'
self.port = str(aRequest.ServerVariables("SERVER_PORT"))
self.hostname = str(aRequest.ServerVariables("SERVER_NAME"))
tName = str(aRequest.ServerVariables("SCRIPT_NAME"))
atoms = tName.split("/")
self.script = atoms.pop()
self.path = "/".join(atoms)
# Store logged-on username
self.user = str(aRequest.ServerVariables("LOGON_USER"))
# Retrieve the submitted CGI parameters.
if str(aRequest.ServerVariables("REQUEST_METHOD")) == 'POST':
self.set_params(aRequest.Form())
else:
self.set_params(aRequest.QueryString())
def set_params(self, queryString):
"""Parse CGI params into a paramset."""
self.requestParams.flush()
inParams = parse_qs(str(queryString), True, False)
for eachName, eachValue in inParams.items():
for eachSubValue in eachValue:
self.requestParams.add_param(eachName, eachSubValue)
def write(self, textToOutput):
self.response.Write(textToOutput)
#################################
# D:\htdocs\myapp\directory.htm #
#################################
<%@Language=Python%>
<%
from myapp.interface import uiasp
uiasp.UserInterfaceASP(Application, Request, Response).dispatch()
%>
######## mod_python #######
##################
# uimodpython.py #
##################
from uihtml import *
from mod_python import apache, util
class UserInterfaceModPython(UserInterfaceHTML):
"""Provide an HTML interface using mod_python."""
response = None
def __init__(self, aRequest):
self.OK = apache.OK
self.HTTP_NOT_ACCEPTABLE = apache.HTTP_NOT_ACCEPTABLE
# Set response hook to equal the Request object.
self.response = aRequest
self.load_params(aRequest)
# Set uri data from Request object.
if aRequest.protocol.count('HTTPS') > 0: self.protocol = 'https'
rawIP, self.port = aRequest.connection.local_addr
self.hostname = aRequest.hostname
atoms = aRequest.uri.split("/")
self.script = atoms.pop()
self.path = "/".join(atoms)
self.user = aRequest.user
# Retrieve the submitted parameters from Apache/mod_python.
# ONLY CALL ONCE per request.
newData = util.FieldStorage(aRequest, 1).list
self.requestParams.flush()
if newData is not None:
for eachParam in newData:
self.requestParams.add_param(str(eachParam.name),
str(eachParam.value))
def write(self, textToOutput):
self.response.write(textToOutput)
###############################
# D:\htdocs\myapp\dispatch.py #
###############################
from myapp.interface import uimodpython
def handler(req):
return uimodpython.UserInterfaceModPython(req).dispatch()
#####################
# myapp-apache.conf #
#####################
<Directory D:\htdocs\myapp>
AddHandler python-program .htm
PythonHandler dispatch
</Directory>
|
The basic structure in this design revolves around the UserInterfaceHTML class and its two subclasses, one for ASP and one for mod_python. We then have small glue scripts to connect that UI object to our particular platform. Regardless of which web server we use, the UI object should do several things for us:
Process and store CGI parameters submitted in an HTTP GET or POST. I've inluded a simple ParamSet class for storing these. It doesn't store complex things like file uploads, but you can add that yourself if you like. With mod_python, the CGI parameters are made available in the util.FieldStorage() object. In ASP, they are accessed via Request.Form() and Request.QueryString().
Store the request environment, including such items as user name, the URI which was requested, etc. Mod_python provides these through its request object. In ASP, we generally read environment variables. I include a function, location(), which uses this information to provide you the current URI; use it to form href's in the HTML of your new page which point to the current directory or page.
Provide a means to write data back to the client browser. ASP has a Response object separate from its Request object; mod_python uses the same Request object for both reading and writing.
In our case, we use the UI object to help us execute the appropriate code based on the URI, using the dispatch() function. I have to admit this fits the mod_python approach more closely than it does ASP. When Apache is configured to handle web page requests using mod_python, it's easiest to route all requests to a single Python function. See myapp-apache.conf and dispatch.py, above. Under this model, if a client requests /directory.htm, Apache will call the handler() function in dispatch.py. From there, we create a UI object and call UI.dispatch().
ASP doesn't work like this: it expects each requestable URI to have an actual file of ASP code. So, if our client requests /directory.htm, we need to have an actual file named "directory.htm" in the appropriate folder. Therefore, if your application consists of 100 pages, you're going to have 100 duplicates of this code sitting around. Sorry. However, each file is exactly the same; there's nothing stopping you from writing a Python script to generate the files for you; you can even put that script on a webpage. It's possible to use rewriting to work around this, but not without mangling the URL as the client sees it. As far as I can tell, IIS doesn't have an administratively-accessible option for "internal" redirection (IIS 6.0 does, via ExecuteURL, but this is only available within ISAPI applications).
In addition, if you are not already set up to use Python as your ASP interpreter, you need to configure IIS to do so. See http://support.microsoft.com/?kbid=276494
Finally, I made the choice to keep the ".htm" extension in ASP to make this more portable; frankly, I dislike the idea of users having to (or being allowed to) know how the web page they are viewing was generated. Therefore, you need to set up IIS to handle .htm files with the ASP interpreter, by adding a Script Mapping for it.
The dispatch() function simply examines the full URI (such as "http://www.amor.org/mcontrol/directory.htm") and extracts the final "filename": in this example, "directory". It then looks up and calls the appropriate package.module.function to handle the request. It does this using get_func(), which I describe elsewhere*.
Analysis:
When functionality becomes a commodity, portability often takes its place as the deciding factor in deployment decisions. Python itself often fits this maxim. In the web application space, this has been a truism for some time now. This recipe gives you the basic structure to deploy the same Python application using either IIS and ASP (Windows) or Apache and mod_python (Windows, Unix). I first developed this technique when I developed a mod_python app, and then found out Apache 2 on Windows didn't yet do HTTPS (although one can solve that with an Apache 1.x SSL proxy).
With any design, many of the benefits perceived by one deployer will be seen as detriments by another. However, this particular design has a few good things going for it:
It completely abstracts the UI so your code can simply not care which webserver it's using.
It's modular, which means that you could easily write a UI subclass for other webservers: Netscape, Xitami, Roxen, or your own.
The interface code itself is quite small. Since the UI module(s) will be loaded once and reused by the Python intepreter, having small page scripts increases performance.
Partly due to the fact that it is Python, its completely rewritable. You could, for example, dynamically build the dispatches dictionary from a configuration file, which would be read and parsed upon the first page request.
In order to keep the recipe simple enough to discuss, I left out any session-handling code. I also made directory.py rather simple; there's only enough code there to demonstrate UI.requestParams and UI.write(). That module references some functions (like objectserver.recall()) for which I understandably didn't bother to include code; I hope you can infer their operation.
- See "Import package modules at runtime": http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223972
where did you define the load_params method ? i did not find it in the code .
thanks.