getlist question

Victor Subervi victorsubervi at gmail.com
Thu Dec 24 16:50:06 EST 2009


On Thu, Dec 24, 2009 at 3:28 PM, MRAB <python at mrabarnett.plus.com> wrote:

> Victor Subervi wrote:
>
>> Hi;
>> I have the following code:
>>
>>      try:
>>        trueVal = form.getlist(storeColNames[i])
>>        colNames.append(storeColNames[i])
>>        if len(trueVal) > 1:
>>          trueVal = string.join(trueVal, ',')
>>
>
> Unless you're using a very old version of Python, you should be using
> the string method:
>
>          trueVal = ','.join(trueVal)
>
>
>           values.append(trueVal)
>>        elif len(trueVal) == 1:
>>          print storeColNames[i], trueVal, '<br />'
>>          trueVal = '%s' % trueVal[0]
>>          values.append(trueVal)
>>        if len(trueVal) > 0:
>>          sql = '%s="%s"' % (storeColNames[i], trueVal)
>>          sqlUpdate.append(sql)
>>      except:
>>        raise
>>
>> This works fine except when storeColNames[i] returns no data. Now, if I
>> were dealing with getfirst instead of getlist, I could easily put in a
>> nonsense default data value such as '%$#' and check for that. But how can I
>> do that or something similar (and preferably more elegant) with getlist,
>> which takes only the one name parameter?
>>
>>  You just need to check whether len(trueVal) == 0. Simple.


The problem is that it doesn't see the value at all

        trueVal = form.getlist(storeColNames[i])
        test = ','.join(trueVal)
        if len(test) == 0:
          trueVal == ''

It simply doesn't register storeColNames[i] if there is nothing provided
from the referring page. Here's a test printout:

SKU ['prodSKU1']
Category ['prodCat1']
Name ['name1']
Title ['title1']
Description ['descr']
Price ['123.45']
SortFactor ['500']
Availability ['1']
OutOfStock ['0']
ShipFlatFee ['10']
ShipPercentPrice ['5']
ShipPercentWeight ['2']
TempPrice ['1']
LastDatePrice ['2000-01-01']
Weight ['2.5']
Metal ['14k gold']
PercentMetal ['25']
insert into products (SKU, Category, Name, Title, Description, Price,
SortFactor, Availability, OutOfStock, ShipFlatFee, ShipPercentPrice,
ShipPercentWeight, Associations, TempPrice, LastDatePrice, Weight, Metal,
PercentMetal) values("prodSKU1", "prodCat1", "name1", "title1", "descr",
"123.45", "500", "1", "0", "10", "5", "2", "1", "2000-01-01", "2.5", "14k
gold", "25"); Insert/update successful!
*This page is going to refresh to the principle page of the shopping cart in
5 seconds.*
*
*
You can see from the above part with breaks that "Availability" isn't
logged. But it is in the insert statement...without a value, which throws an
error. The complete code follows:

TIA,
beno

#! /usr/bin/python

import cgitb; cgitb.enable()
import MySQLdb
import cgi
import string
import sys,os
sys.path.append(os.getcwd())
from login import login
from particulars import addStore

def enterProducts4():
  form = cgi.FieldStorage()
  store = form.getfirst('store')
  print '''Content-Type: text/html\r\n
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>'''
#  print '<META HTTP-EQUIV="refresh"
content="5;URL=enterProducts.py?store=%s">' % store
  print '</head>\n<body>'
  user, passwd, db, host = login()
  db = MySQLdb.connect(host, user, passwd, db)
  cursor= db.cursor()
  both = ''
  count = 0
  cursor.execute('describe %s;' % store)
  temp = cursor.fetchall()
  tmp = [itm[0] for itm in cursor]
  storeColNames = []
  for descrip in tmp:
    storeColNames.append(descrip)
  colNames = []
  colNamesOther = []
  sqlUpdate = []
  sqlUpdatePics = []
  i = 0
  values = []
  valuesPics = []
  pics = []
  colNamesPics = []
  y = 0
  whatDo = form.getfirst('whatDo')
  sql = 'select last_insert_id() from %s;' % store
  cursor.execute(sql)
  try:
    id = cursor.fetchone()[0]
  except:
    id = 0 # This is obviously the first insert; since insert, will be
incremented below
  if whatDo == 'insert':
    id += 1
  i = 0
  while i < len(storeColNames):
    if (len(storeColNames[i]) > 3) and (storeColNames[i][:3] == 'pic'):
      y += 1
      pic = form.getfirst(storeColNames[i][:4], '')
      if len(pic) > 0:
        pics.append(pic)
      else:
        try:
          sql = 'select %s from %s where ID=%s;' % (storeColNames[i][:4],
store, id)
          cursor.execute(sql)
          try:
            pic = cursor.fetchone()[0].tostring()
            pics.append(pic)
          except:
            pass
        except: # This means it's an insert, not an update
          pass
      colNamesPics.append(storeColNames[i])
      sqlUpdatePics.append(storeColNames[i] + '="' + trueVal + '"')
    else:
      try:
        trueVal = form.getlist(storeColNames[i])
        test = ','.join(trueVal)
        if len(test) == 0:
          trueVal == ''
        colNames.append(storeColNames[i])
        if len(trueVal) > 1:
          trueVal = string.join(trueVal, ',')
          values.append(trueVal)
        elif len(trueVal) == 1:
          print storeColNames[i], trueVal, '<br />'
          trueVal = '%s' % trueVal[0]
          values.append(trueVal)
        if len(trueVal) > 0:
          sql = '%s="%s"' % (storeColNames[i], trueVal)
          sqlUpdate.append(sql)
      except:
        raise
    i += 1
  colNames = string.join(colNames[1:], ', ') # We don't want to include the
ID field
  values = string.join(values, '", "')
  sqlUpdate = string.join(sqlUpdate, ', ')
  try:
    if whatDo == 'update':
      sql = 'update %s set %s where ID="%s";' % (store, sqlUpdate,
form.getfirst('id'))
      cursor.execute(sql)
      i = 0
      for pic in pics:
        sql = 'update %s set %s=%s where ID=%s;' % (store, colNamesPics[i],
'%s', id)
        cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),), )
        db.commit()
        i += 1
    elif whatDo == 'insert':
      cursor.execute('show tables like "%PersonalData";')
      personalDataTables = [itm[0] for itm in cursor]
      sql = 'create table if not exists relationships%s (%sID tinyint(5) not
null primary key, ' % (store[0].upper() + store[1:], store[0].upper() +
store[1:])
      sql2 = 'insert into relationships%s values ("%s", ' %
(store[0].upper() + store[1:], id)
      for dataTable in personalDataTables:
        sql += '%sID tinyint(5) unsigned not null, ' % (dataTable[0].upper()
+ dataTable[1:-12])
        sql2 += '"%s", ' % form.getfirst(dataTable[:-12])
      sql = '%s);' % sql[:-2]
#      cursor.execute(sql)
      sql2 = '%s);' % sql2[:-2]
#      cursor.execute(sql2)
      sql = 'insert into %s (%s) values("%s");' % (store, colNames, values)
      print sql
#      cursor.execute(sql)
      i = 0
      for pic in pics:
        sql = 'update %s set %s=%s where ID="%s";' % (store,
colNamesPics[i], '%s', id)
        cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),))
        i += 1
  except MySQLdb.IntegrityError:
    print 'I\'m sorry, but the SKU you entered is already in use in another
entry. Please click the \'back\' button and choose another number.'
  except MySQLdb.OperationalError:
#    print 'I\'m sorry, but you have added an illegal character to a number
(or in "SKU", "price", "weight", "% Metal", "flat shipping fee", "shipping
fee based on % of price" or "shipping fee based on weight"). Please click
the \'back\' button and enter a correct number.'
    raise
  except:
    print 'I\'m sorry, but there has been an error. Please click the
\'back\' button and try and figure out what went wrong.'
  print 'Insert/update successful!<br />'
  print '<i>This page is going to refresh to the principle page of the
shopping cart in 5 seconds.</i>'
  print '<body>\n</html>'
  db.commit()
  cursor.close()

enterProducts4()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091224/e35cc147/attachment-0001.html>


More information about the Python-list mailing list