Python – Using Python Web GET data

form-datapython

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?

Best Solution

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()