Help a newbie revise my program

S

Sean Berry

My program is used by an applet to look up items in a mysql database.
It is a "smart program". By that I mean it returns different results based
on
the arguments from the URL. Like,
www.domain.com/cgi-bin/getModels?shaped=5&sized=7

It works well enough. However, I would like to find out better ways to do
some of the things I am doing,
such as getting the variable values from the URL.

Here is my code:

#!/usr/local/bin/python

import MySQLdb, os
db=MySQLdb.connect(db="aquatics")
c=db.cursor()
d = ()
di = {}
x = []
li2 = []

def getVars():
if len(os.environ["QUERY_STRING"]) > 0:
val_list = os.environ["QUERY_STRING"].split("&")
for item in val_list:
templi = item.split("=")
li2.append(templi)
return li2
else:
return []

x = getVars()
if len(x) > 0:
di = dict(x)
sql = """SELECT code from models"""

if 'sized' and 'shaped' in di:
sql = sql + """ where size like '%s%%' and shape=%s order by code"""
%(di['sized'], di['shaped'])
elif di.has_key('shaped'):
sql = sql + """ where shape=%s order by code""" %di['shaped']
elif di.has_key('size'):
sizevalue = di['sized']
sql = sql + """ where size like '%s%%' order by code""" %di['sized']

c.execute("%s" %sql)
d=c.fetchall()
for type in d:
print "<option>" + type[0] "+</option>\n"
 
P

Paul McGuire

Sean Berry said:
My program is used by an applet to look up items in a mysql database.
It is a "smart program". By that I mean it returns different results based
on
the arguments from the URL. Like,
www.domain.com/cgi-bin/getModels?shaped=5&sized=7

It works well enough. However, I would like to find out better ways to do
some of the things I am doing,
such as getting the variable values from the URL.

I think you'll find some helpful stuff in the cgi module, especially
parse_qs(queryString), which in your example will return a dictionary as
follows:
import cgi
print cgi.parse_qs("shaped=5&sized=7") {'sized': ['7'], 'shaped': ['5']}

I can't explain why the dictionary values are lists, though - I would have
expected scalar strings.

-- Paul
 
M

Marc 'BlackJack' Rintsch

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top