Using Python Web GET Data

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

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

      

on the full page, I have the following:

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 full page, I get a key error in "id". Does anyone know how to fix this?

EDIT
when i ran cgi.test()

it gave me nothing

I think there is something wrong with the way I use the url because it is not being passed over.

its basically localhost / chris / complete? id = 1

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

Can the URL be formatted incorrectly?

0


source to share


3 answers


An error means that the form["id"]

key could not be found "id"

in cgi.FieldStorage()

.

To check what keys are in the called url use cgi.test () :

cgi.test ()

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



EDIT: basic test script (using python cgi module with linux line) - only 3 lines. Make sure you know how to run it on your system and then invoke it from the browser to check that the arguments are visible on the CGI side. You can also add tracing formatting with import cgitb; cgitb.enable()

.

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

      

+1


source


Have you tried printing out the value of the form to make sure you get what you think you are getting? You have a small problem with your code, though ... you have to make the ["id"] form. Value to get the value of the element from FieldStorage. Another alternative is to just do it yourself, for example:

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']}

      

+1


source


First of all, you must do a dictionary lookup via

possibly_none = my_dict.get( "key_name" )

      

As this assigns None to the variable if no key is specified in the dict. Then you can use

if key is not None:
    do_stuff

      

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

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

form.get( 'id' ).value

      

to retrieve the data you seem to be requesting.

0


source







All Articles