CGI module misbehaving?

Jim Meier fatjim at home.com
Mon Jun 7 05:05:34 EDT 1999


Hi folks! I'm making my first foray into web programming, so my question
_might_ be silly; however, I've checked it out and seems to be an actual
bug.

At the end of this message is a python program that is supposed to
handle displaying and adding players to a gadfly database. The database
part is working fine. The program is there so that the bug can be
demonstrated..

The problem comes at the end of the file (the start of the program) when
it attempts to use the CGI module to read some form values in. A
traceback is generated on the line:

if form.has_key["name"]:
    ...

the traceback is:
Traceback (innermost last):
File "c:\httpd\cgi-bin\ahdb\add-player.py",line 178, in ?
if form.has_key["name"]:
TypeError: expected integer index

(formatting faked, as it was copied of the browser window)

I've searched through the source for the CGI module, and it does not
seem to generate this exception anywhere!

Is this a problem that is know, or is there something wrong with my
setup here?

Platform info:
Windows 98 (sigh)
Python 1.5.2 from PythonWare's download section (
http://www.pythonware.com/downloads/py15-980706.exe )
omniHTTPd v2.02

-Jim

code exhibiting the bug: (yes, pretty ugly I know. I take suggestions..
:)


# add-player.py ::sun jun 6::Jim Meier
# display forms for adding or deleting players

from os import environ
import cgi
from gadfly import gadfly

# find environment variables:
if environ.has_key('AH_HOME'):
  ah_dir=environ['AH_HOME']
else:
  ah_dir="c:\\py15\\src\\ahdb"
ahdb_dir=ah_dir+"\\ahdb"

connection=gadfly("ahdb", ahdb_dir)
curs=connection.cursor()

def get_players():
  curs.execute("select * from players")
  return curs.fetchall()

def player_table_row(player,sel_col):
  name='<a href="/cgi-bin/show-player?%s">%s</a>' %
(player[0],player[1])
  email='<a href="mailto:%s>%s</a>' % (player[2],player[2])
  web='<a href="%s">%s</a>' % (player[3],player[3])

  print "<tr>"
  print "  <td>%s</td>" % sel_col
  print "  <td>%s</td>" % name
  print "  <td>%s</td>" % email
  print "  <td>%s</td>" % web
  print "</tr>"

def player_table():
  print '<table border=0 width="90%" cellspacing=3 bgcolor="000000">'

  print '<tr bgcolor="6495ed">'
  print "  <td>Select</td>"
  print "  <td>Name</td>"
  print "  <td>E-Mail</td>"
  print "  <td>Home/AH Page</td>"
  print "</tr>"

  for i in get_players():
    sel_col='<input type="checkbox" name="player_sel" value="%s">' %
str(i[0])
    player_table_row(i, sel_col)

  print "</table>"


def new_player_form():
  print '<form method="POST" action="/cgi-bin/ahdb/add-player.py">'
  print '<table border=0 width="70%" cellspacing=3>'
  print '<tr><td>Name:</td> <td><input name="name"
type="text"></td></tr>'
  print '<tr><td>E-Mail:</td> <td> <input name="email"
type="text"></td></tr>'
  print '<tr><td>Home/AH Page:</td> <td> <input name="web"
type="text"></td></tr>'
  print '<tr><td></td><td><input type="submit" value="Add
Player.."></td></tr>'
  print '</table>'
  print '</form>'


def add_player():
  # make sure all required fields are filled..
  global mylog
  global name,email,web

  form_ok=1
  if name is None:
    form_ok, reason = None, "The Name field is required. Please go back
and fill it in."
  if name is None:
    form_ok, reason = None, "The E-Mail field is required. Please go
back and fill it in."
  if not form_ok:
    mylog.write("form doesn't have all we need, returning '%s'\n" %
reason)
    mylog.flush()
    return reason

  # get a unique id for him/her
  mylog.write("getting log id number..\n")
  mylog.flush()
  import whrandom
  id=whrandom.randint(0,sys.maxint)
  while 1: # no way in hell this'll fill up..
    mylog.write("have %i, check to see if it's used..\n" % id)
    mylog.write("executing the select statement..\n")
    curs.execute("select id from players where id=%s" % str(id))
    mylog.write("done execing select..\n")
    if len(curs.fetchall())==0:
      mylog.write("fetchall returned [] so we're breaking the loop..\n")

      break
    try:
      id=id+1
    except OverflowError:
      id=whrandom.randint(0,sys.maxint)

  # add 'em up!
  if web is None:
    web=""
  res=curs.execute("""insert into players (id,name,email,web)
                  values (%s,'%s','%s','%s')"""
                  % str(id), name, email, web)
  if res!=1:
    connection.abort()
    return "Couldn't update the database!"

  connection.commit()


def main():
  global mylog
  global name,email,web

  form=cgi.FieldStorage()
  print repr(form)
  name,email,web=None,None,None
  if form.has_key["name"]:
    name=form['name'].value
  if form.has_key['email']:
    email=form['email'].value
  if form.has_key['web']:
    web=form['web'].value


  mylog=open("c:\windows\profiles\jim\desktop\log.txt","w")
  mylog.write("add-player.py run..\n")
  mylog.write("cgi arguments:\n")
  mylog.write("name=%s\nemail=%s\nweb=%s\n"%(name,email,web))
  mylog.write("\n")
  mylog.write("enviroment:\n")
  for i in environ.keys():
    mylog.write("%s: '%s'\n" % (i, environ[i]))
  mylog.write("\nthat's all, total.\n")


  if len(form.keys()) != 0:
    # should add player, and redirect back to list unless an error
occurs.
    mylog.write("about to call add_player()..\n")
    mylog.flush()
    res=add_player()
    mylog.write("add_player() returned %s\n" % `res`)
    mylog.flush()
    if res!=None:
      mylog.write("res was %s so we're sending an error page..\n" %
`None`)
      print 'content-type: text/html'
      print
      print '<html><head><title>Whoops!</title></head>'
      print "<body><H1>Something's Amiss!</h1>"
      print """Either you screwed up or I did. Something happened while
               processing your form request that caused the operation to
fail.
               They tell me that the reason it failed was:"""
      print '<br>'
      print '<h3><p fgcolor="ff0000">%s</p></h3>' % res
      print '<hr>'
      print '<p align="left"> <a href="/cgi-bin/ahdb/add-player.py">'
      print 'Go Back..</a></p>'
      print '</body></html>'
      mylog.flush()
      mylog.close()
      return

  mylog.write("didn't call add_player()..\n")
  print "content-type: text/html"
  print
  print "<html><body>"
  player_table()
  new_player_form()
  print "</body></html>"

  #..and have a nice day.

  mylog.flush()
  mylog.close()



form=cgi.FieldStorage()
print repr(form)
name,email,web=None,None,None
if form.has_key["name"]:
  name=form['name'].value
if form.has_key['email']:
  email=form['email'].value
if form.has_key['web']:
  web=form['web'].value

main()






More information about the Python-list mailing list