views:

871

answers:

3

I'm trying to pass information to a python page via the url. I have the following link text:

"<a href='complete?id=%s'>" % (str(r[0]))

on the complete page, I have this:

import cgi
def complete():
    form = cgi.FieldStorage()
    db = MySQLdb.connect(user="", passwd="", db="todo")
    c = db.cursor()
    c.execute("delete from tasks where id =" + str(form["id"]))
    return "<html><center>Task completed! Click <a href='/chris'>here</a> to go back!</center></html>"

The problem is that when i go to the complete page, i get a key error on "id". Does anyone know how to fix this?

EDIT when i run cgi.test() it gives me nothing

I think something is wrong with the way i'm using the url because its not getting passed through.

its basically localhost/chris/complete?id=1

/chris/ is a folder and complete is a function within index.py

Am i formatting the url the wrong way?

+1  A: 

The error means that form["id"] failed to find the key "id" in cgi.FieldStorage().

To test what keys are in the called URL, use cgi.test():

cgi.test()

Robust test CGI script, usable as main program. Writes minimal HTTP headers and formats all information provided to the script in HTML form.

EDIT: a basic test script (using the python cgi module with Linux path) is only 3 lines. Make sure you know how to run it on your system, then call it from a browser to check arguments are seen on the CGI side. You may also want to add traceback formatting with import cgitb; cgitb.enable().

#!/usr/bin/python
import cgi
cgi.test()
gimel
A: 

First off, you should make dictionary lookups via

possibly_none = my_dict.get( "key_name" )

Because this assigns None to the variable, if the key is not in the dict. You can then use the

if key is not None:
    do_stuff

idiom (yes, I'm a fan of null checks and defensive programming in general...). The python documentation suggests something along these lines as well.

Without digging into the code too much, I think you should reference

form.get( 'id' ).value

in order to extract the data you seem to be asking for.

Steen
The doc shows a cgi.FieldStorage() example: if not (form.has_key("name") and form.has_key("addr")): ...
gimel
form.get( 'id' ).value doesn't work either. I get an attribute error. I think something is wrong with the way i'm using the url because its not getting passed through
The.Anti.9
to see what is being passed, use cgi.test()
gimel
+1  A: 

Have you tried printing out the value of form to make sure you're getting what you think you're getting? You do have a little problem with your code though... you should be doing form["id"].value to get the value of the item from FieldStorage. Another alternative is to just do it yourself, like so:

import os
import cgi

query_string = os.environ.get("QUERY_STRING", "")
form = cgi.parse_qs(query_string)

This should result in something like this:

{'id': ['123']}
mcrute