Processing an XHTML form using CGI script

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mandrah
    New Member
    • Nov 2006
    • 3

    #1

    Processing an XHTML form using CGI script

    I'm having problems casting input information from an XHTML form as a different type in a CGI script using Python.
    For just a simple example I'd use the XHTML code:
    [HTML]<?xml version = "1.0" encoding = "utf-8"?>
    <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <html>
    <head>
    <title>formTest </title>
    </head>
    <body>
    <form action="./cgi-bin/formTest.py" method="post">
    <p>
    Calculate:<br />
    <input type="text" name="num1" /> + <input type="text" name="num2" /><br />
    <input type="submit" value="Calculat e" />
    </p>
    </form>
    </body>
    </html>[/HTML]

    And the Python Code:

    Code:
    #!/usr/bin/env python
    
    import cgi
    import cgitb; cgitb.enable()
    
    def main():
    
            form = cgi.FieldStorage()
    
            num1 = form.getvalue("num1")
            num2 = form.getvalue("num2")
    
            sum = int(num1) + int(num2)
    
            print "content-type:  text/html\n"
    
            print "<?xml version = \"1.0\" encoding = \"utf-8\"?>"
            print "<!DOCTYPE html PUBLIC \"-//w3c//DTD XHTML 1.1//EN\""
            print "\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n"
            print "<html>"
            print "  <head>"
            print "    <title>Solution</title>"
            print "    <style type=\"txt/css\">"
            print "  <head>"
            print "  <body>"
    
            print "    <p>Solution: " + str(sum) + "</p>"
    
            print "  </body>"
            print "</html>"
    
    main()
    However when I try to cast num1 and num2 as integers, I get an error saying that only string or number arguments can be used:

    int() argument must be a string or a number

    And if I don't cast them I get an error saying:

    unsupported operand types for +: 'NoneType' and 'NoneType'

    Is there a way to cast the input variables from the XHTML form as something other that 'NoneType' so that I can use them in calculations?
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    'NoneType' is the type of None.
    Python converts many 'null' values to None (for example a SQL database item that is a null value gets returned in python as None). I appears to me (I don't read html) that there is no value in you form.

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      A common practice is
      Code:
      try:
          num1 = int(form.getvalue("num1"))
      except (TypeError, ValueError):
          num1 = 0    # or warn the user somehow that the field is empty

      Comment

      Working...