[mod_python] Tutorials, FieldStorage and sys.py. A depressing saga.

Yandle, Hans Hans.Yandle at cingular.com
Thu May 22 17:55:14 EST 2003


Well, I decided to make a working sample out of your code so here is my
working version. Use at will. By no means is this perfect but it does work
for me. Example URL:
http://localhost/test/sample/ProcessForm/?name=Hans&color=swallow

=== sample.py ===
from mod_python import apache
import string

### File Parameter Options ###
Template = "/usr/local/python/template.html" # filename of template file

def EvalTemplate(Content):
    (Result, ErrorMsg) = (None, None)
    try:
        TemplateFile = file(Template, "r") # open in read only mode
        TemplateData = TemplateFile.read() # read in the contents of the
file
        TemplateFile.close() # close the file
    except IOError, e:
        ErrorMsg = "Error! Unable to read contents of template file %s.
<br>%s" % (Template, e)
    except:
        ErrorMsg = "Error! Unknown error has occured."
    if not ErrorMsg:
        if string.find(TemplateData, "<!--*** INSERT CONTENT HERE ***-->")
is not -1:
            Result = string.replace(TemplateData, "<!--*** INSERT CONTENT
HERE ***-->", Content)
        else:
            ErrorMsg = "Invalid template file format. Missing insert comment
tag. Please fix %s." % Template
    return (Result, ErrorMsg)

def SendHTML(Output=None, ErrorMsg=None):
    if not ErrorMsg:
        s, ErrorMsg = EvalTemplate(Output)
    if ErrorMsg:
        s = """<html><head><title>Mod_Python Sample Using a Template: Error
Message</title></head>
               <body><p>An error has occured. Please correct the
problem.</p>
               <pre>%s</pre></body></html>""" % ErrorMsg
    return s

def ProcessForm(req, name=None, email=None, color=None, comment=None):
    ErrorMsg = None
    Output = "Hello, "
            
    if name:
        if email:
            Output = Output + "<a href=mailto:%s>%s</a>.<p>" % (email, name)
        else:
            Output = Output + "%s.<p>" % name
    else:
        ErrorMsg="You need to at least supply a name. Please go back."
        
    if color=="swallow":
        Output = Output + "You must be a Monte Python fan.<p>"
    elif color != None:
        Output = Output + "Your favorite color was %s<p>" % color
    else:
        Output = Output + "You cheated! You didn't specify a color!<p>"
        
    if comment:
        Output = Output + "In addition, you said: <br>%s<p>" % comment
        
    req.content_type = "text/html"
    req.send_http_header()
    
    return SendHTML(Output, ErrorMsg)
=== end ===
=== template.html ===
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
  <head>
    <META NAME="keywords" CONTENT="blah blah -- your ad here">
    <title>Python is Fun!</title>
  </head>
  <body>
                <!--*** INSERT CONTENT HERE ***-->
  </body>
</html>
=== end ===

Have fun,

Hans

-----Original Message-----
From: Gregory (Grisha) Trubetskoy [mailto:grisha at modpython.org]
Sent: Thursday, May 22, 2003 3:11 PM
To: Terry MacDonald
Cc: mod_python at modpython.org
Subject: Re: [mod_python] Tutorials, FieldStorage and sys.py. A
depressing saga.



Terry -

Thanks for your compliments.

You didn't specify what's in your apache config, so it's hard to tell
what's going on there. My recommendation would be to reserve an hour or so
and read the tutorial carefully.

One of the things that caught my eye was the ".value" attribute you're
using - the mod_python version of FieldStorage does not require it. But
more likely than not you just need to use the publisher handler, in which
case you wouldn't need to concern yourself with FieldStorage at all, and
your ProcessForm function would look something like:

def ProcessForm(req, name="", email="", color="", comment=""):

	if not name:

		return "Name is required"


	... etc ...


	return SubResult[0]


Note that print statements are useless in mod_python, also your URL is
lower case, but function names are mixed-case - since Python is
case-sensitive, that would cause a problem.

HTH.

Grisha


On 22 May 2003, Terry MacDonald wrote:

> Hi again,
>
> Thankyou very much for your replies, You seem a nice bunch in here.
> I look forward to conversing with you over time (hopefully not all bug
related!)
>
> Anyways your advice solved one issue but unfortunately moved me on to the
next.
> I am reaching the end of my patience as I have tried various work arounds
to my
> ills and I just go up more garden paths to more problems (this should not
be that
> difficult I know!).
>
> Forgive me but I have decided to post the code to see if you can tell what
is wrong
> cos I just can't get it to work as it is supposed to. The code is
primarily example
> code but has been rejigged a little while trying to get it to work.
>
> Problems occuring now is that the subn function is giving a mulitple
repeat error.
> When I comment out the offending code I just get Object not found in the
browser.
> Also I have to put full pathnames in for the html files otherwise they
cannot be
> found (I know this can't be right - but i'm trying anything to get this to
work)
>
> Ultimately the example should print a form, fetch the contents and display
them
> back to you in another page (I think!) not exactly rocket science.
>
> Below is the .py file and the two basic html files. Enjoy !
>
> Cheers
>
> Terry
>
>
============================================================================
====
> #!/usr/bin/python
>
> from mod_python import apache
> from mod_python import util
> import re
>
> # specify the filename of the template file
> TemplateFile = "/var/www/html/python/template.html"
>
> # Display  takes one parameter - a string to Display
> def Display(Content):
>     TemplateHandle = open(TemplateFile, "r")  # open in read only mode
>     # read the entire file as a string
>     TemplateInput = TemplateHandle.read()
>     TemplateHandle.close()                    # close the file
>
>     # this defines an exception string in case our
>     # template file is messed up
>     BadTemplateException = "There was a problem with the HTML template."
>
>     SubResult = re.subn( "<!-- *** INSERT CONTENT HERE *** -->", Content,
TemplateInput )
>     if SubResult[1] == 0:
>         raise BadTemplateException
>
>     print "Content-Type: text/html\n\n"
>     print SubResult[0]
>
>
> def ProcessForm(req):
>
>     form = util.FieldStorage(req)
>
>     # extract the information from the form in easily digestible format
>     try:
>         name = form["name"].value
>     except:
>         # name is required, so output an error if
>         # not given and exit script
>         Display("You need to at least supply a name. Please go back.")
>         raise SystemExit
>     try:
>         email = form["email"].value
>     except:
>         email = None
>     try:
>         color = form["color"].value
>     except:
>         color = None
>     try:
>         comment = form["comment"].value
>     except:
>         comment = None
>
>     Output = ""  # our output buffer, empty at first
>
>     Output = Output + "Hello, "
>
>     if email != None:
>         Output = Output + "<A HREF=mailto:" + email + ">" + name +
"</A>.<P>"
>     else:
>         Output = Output + name + ".<P>"
>
>     if color == "swallow":
>         Output = Output + "You must be a Monty Python fan.<P>"
>     elif color != None:
>         Output = Output + "Your favorite color was " + color + "<P>"
>     else:
>         Output = Output + "You cheated!  You didn't specify a color!<P>"
>
>     if comment != None:
>         Output = Output + "In addition, you said:<BR>" + comment + "<P>"
>
>     Display(Output)
>
> ###
> ### Begin actual script
> ###
>
> #### "key" is a hidden form element with an
> ### action command such as "process"
> #try:
> #    key = form["key"].value
> #    key = form["key"].value
> ##except:
> #    key = None
>
> #if key == "process":
> #    ProcessForm(form)
> #else:
> #    DisplayForm()
>
> # Open and display the form
> FormFile = "/var/www/html/python/form2.html"
> FormHandle = open(FormFile, "r")
> FormInput = FormHandle.read()
> FormHandle.close()
> Display(FormInput)
>
>
============================================================================
===========
>
> Form2.html.........
>
> <FORM METHOD="POST" ACTION="sample.py/processform">
>       <INPUT TYPE=HIDDEN NAME="key" VALUE="process">
>       Your name:<BR>
>       <INPUT TYPE=TEXT NAME="name" size=60>
>       <BR>
>       Email: (optional)<BR>
>       <INPUT TYPE=TEXT NAME="email" size=60>
>       <BR>
>       Favorite Color:<BR>
>       <INPUT TYPE=RADIO NAME="color" VALUE="blue" CHECKED>Blue
>       <INPUT TYPE=RADIO NAME="color" VALUE="yellow">No, Yellow...
>       <INPUT TYPE=RADIO NAME="color" VALUE="swallow">What do you mean, an
African or European swallow?
>       <P>
>       Comments:<BR>
>       <TEXTAREA NAME="comment" ROWS=8 COLS=60>
>       </TEXTAREA>
>       <P>
>         <INPUT TYPE="SUBMIT" VALUE="Okay">
> </FORM>
>
============================================================================
===========
> Template.html........
>
> <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
> <html>
>   <head>
>     <META NAME="keywords" CONTENT="blah blah -- your ad here">
>     <title>Python is Fun!</title>
>   </head>
>   <body>
>                 <!-- *** INSERT CONTENT HERE *** -->
>   </body>
> </html>
>
>
>
> _______________________________________________
> Mod_python mailing list
> Mod_python at modpython.org
> http://mailman.modpython.org/mailman/listinfo/mod_python
>

_______________________________________________
Mod_python mailing list
Mod_python at modpython.org
http://mailman.modpython.org/mailman/listinfo/mod_python
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mailman.modpython.org/pipermail/mod_python/attachments/20030522/50bf5078/attachment-0003.htm


More information about the Mod_python mailing list