Mailing List Archive

CGI module misbehaving?
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()
CGI module misbehaving? [ In reply to ]
Hi!

On Mon, 7 Jun 1999, Jim Meier wrote:
> if form.has_key["name"]:

if form.has_key("name"):

has_key is a function!

Oleg.
----
Oleg Broytmann National Research Surgery Centre http://sun.med.ru/~phd/
Programmers don't die, they just GOSUB without RETURN.
CGI module misbehaving? [ In reply to ]
Oleg Broytmann wrote:

> On Mon, 7 Jun 1999, Jim Meier wrote:
> > if form.has_key["name"]:
>
> if form.has_key("name"):
>
> has_key is a function!

(I was asked to post this to the group so it would show up in a deja search..)

On Mon, Jun 07, 1999 at 03:26:44AM -0600, Jim Meier wrote:
>
> Whoops! That'll teach me to try working this late. Thanks a lot - Now my only
> problem will be recovering from the embarrassment!
>
> -Jim
>
CGI module misbehaving? [ In reply to ]
In article <Pine.LNX.4.04.9906071320360.5443-
100000@emerald.netskate.ru>,
phd@sun.med.ru wrote:
> Hi!
>
> On Mon, 7 Jun 1999, Jim Meier wrote:
> > if form.has_key["name"]:
>
> if form.has_key("name"):
>
> has_key is a function!

This is one of my most common typos for some reason.

Also I'd note that for cgi use you really should use a gadfly
server for safety. It is conceivable that two cgi clients could
access the database at once otherwise and the updates from
one of them would probably get lost. It will also probably run
faster if the database gets big.

-- Aaron Watters http://www.chordate.com

===

May your hemorroids heal without surgery.
-- blessing from "Bored of the Rings"


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.