At this point you may be wondering if mod_python is all that useful after all. You may find yourself asking: "If there can only be one handler per directory, how am I to structure my application?"
Enter the publisher
handler provided as one of the standard
mod_python handlers. To get the publisher handler working,
you will need the following lines in your config:
AddHandler python-program .py PythonHandler mod_python.publisher
The following example will demonstrate a simple feedback form. The form will ask for the name, e-mail address and a comment and the will construct an e-mail to the webmaster using the information submitted by the user.
Here is the html for the form:
<html> Please provide feedback below: <p> <form action="form/email" method="POST"> Name: <input type="text" name="name"><br> Email: <input type="text" name="email"><br> Comment: <textarea name="comment" rows=4 cols=20></textarea><br> <input type="submit"> </form> </html>
Note the action
element of the <form>
tag points to
form/email
. We are going to create a file called form.py,
like this:
import smtplib def email(req, name, email, comment): # see if the user provided all the parameters if not (name and email and comment): return "A required parameter is missing, \ please go back and correct the error" # create the message text msg = """\ From: %s Subject: feedback To: webmaster I have the following comment: %s Thank You, %s """ % (email, comment, name) # send it out conn = smtplib.SMTP("localhost") conn.sendmail(email, ["webmaster"], msg) conn.quit() # provide feedback to the user s = """\ <html> Dear %s,<br> Thank You for your kind comments, we will get back to you shortly. </html>""" % name return s
When the user clicks the Submit button, the publisher handler will
load the email function in the form module,
passing it the form fields as keyword arguments. Note that it will
also pass the Request object as req
. Note also that
you do not have to have req
as one of the arguments if you do
not need it. The publisher handler is smart enough to pass your function
only those arguments that it will accept.
Also notice how it sends data back to the customer - via the return value of the function.
And last, but not the least, note how all the power of mod_python
is still available to this function, since it has access to the
Request object. You can do all the same things you can do
with a "native" mod_python handler, e.g. set custom headers via
req.headers_out
, return errors by raising
apache.SERVER_ERROR exceptions, write or read directly
to and from the client via req.write and req.read,
etc.
Read Section 6.1 Publisher Handler for more information on the publisher handler.