Interesting Problem

Victor Subervi victorsubervi at gmail.com
Wed Jan 20 10:19:01 EST 2010


Hi;
I think I finally have an interesting problem for y'all. I need to import a
script from a lower dir, forcing me to change dirs:

cwd = os.getcwd()
os.chdir('%s/..' % cwd)
sys.path.append(os.getcwd())
from templateFrame import top, bottom
os.chdir(cwd)

Because I've found I must do my form evaluations *before* changing dir as
above, I am forced to call these values as globals:

form = cgi.FieldStorage()
store = form.getfirst('store')
cat = form.getfirst('cat')
id = form.getfirst('id')
pkg = form.getfirst('pkg')
patientID = form.getfirst('patientID')

Now, apparently because of python's problem with globals, when I call "id"
as follows:

cursor.execute('select ProductID from productsPackages where PackageID=%s' %
id)

I get the following error:

/var/www/html/angrynates.com/cart/Store_frame2.py
  135   cursor.close()
  136   bottom()
  137
  138 Store_frame2()
  139
Store_frame2 = <function Store_frame2>
 /var/www/html/angrynates.com/cart/Store_frame2.py in Store_frame2()
  119     printAProduct()
  120   else:
  121     cursor.execute('select ProductID from productsPackages where
PackageID=%s' % id)
  122     for id in [itm[0] for itm in cursor]:
  123       printAProduct(id)
global cursor = <MySQLdb.cursors.Cursor object>, cursor.execute = <bound
method Cursor.execute of <MySQLdb.cursors.Cursor object>>, global id = '1'

UnboundLocalError: local variable 'id' referenced before assignment
      args = ("local variable 'id' referenced before assignment",)

Full code below. Please advise.
TIA,
beno

#! /usr/bin/python

import string
import cgitb; cgitb.enable()
import cgi
import MySQLdb
import sys,os
from sets import Set
import fpformat
cwd = os.getcwd()
sys.path.append(cwd)
from login import login
from particulars import truncate

form = cgi.FieldStorage()
store = form.getfirst('store')
cat = form.getfirst('cat')
id = form.getfirst('id')
pkg = form.getfirst('pkg')
patientID = form.getfirst('patientID')

try:
  browser = form.getfirst('browser', 'all')
except:
  browser = headers()

os.chdir('%s/..' % cwd)
sys.path.append(os.getcwd())
from templateFrame import top, bottom
os.chdir(cwd)

ourFile = string.split(__file__, "/")
p = ourFile[len(ourFile) - 1]
p = p[: - 9]
site = ourFile[4][:-10]
if site != '':
  site = site[:-1]

user, passwd, db, host = login()
db = MySQLdb.connect(host, user, passwd, db)
cursor= db.cursor()

cursor.execute('describe %s;' % store)
descr = cursor.fetchall()
cols = []
for elt in descr:
  cols.append(elt[0])

def printAProduct(id=id):
  lastID = ''
  cursor.execute('select * from %s where ID="%s"' % (store, id))
  vals = cursor.fetchone()
  prodDict = dict(zip(cols, vals))
  for col, item in prodDict.iteritems():
    if col == 'ID':
      print '<input type="hidden" name="prodid" value="%s" />' % item
    try: # Stores such as products (but not prescriptions) will pass through
      from particulars import ourOptions
      if col in ourOptions():
        print '<input type="hidden" name="%s" value="%s" />' % (col, item)
    except:
      pass
    if col[:3] != 'pic':
      notSet = 1
      if isinstance(item, (str, int, long, float, long, complex, unicode,
list, buffer, xrange, tuple)):
        print '<b>%s: </b>%s<br />\n' % (col, item)
      else:
        try:
          html = "<b>%s</b>: <select name='%s'>" % (col, col)
          notSet = 0
          for itm in item:
            try:
              color, number = itm.split('_')
              html += "<option value='%s'>%s</option>" % (itm, color)
            except:
              html += "<option value='%s'>%s</option>" % (itm, itm)
          html += "</select><br />"
          print html
        except:
          pass
#      if notSet == 1:
#        if len(col) > 49:
#          colX = col[:50] + '...'
#       else:
#         colX = col
#       print '<b>%s: </b>%s<br />\n' % (colX, item)
    elif col == 'pic1':
      try:
        if (item != None):
#      if (item != None) and (len(item > 0)):
          print '<a href="getpic.py?store=%s&pic=%s&id=%s" class="highslide"
href="getpic.py?store=%s&pic=%s&id=%s" onclick="return hs.expand(this)"><img
src="getpic.py?store=%s&pic=%s&id=%s" width="100" height="80" alt=""
align="left" border="0" title="Click to enlarge" style="border: 0px"></a><br
clear="all" />\n' % (store, col[3:], id, store, col[3:], id, store, col[3:],
id)
      except TypeError:
        raise
      except:
        raise
#      i += 1
#      try:
#        content = item[x].tostring()
#         pic = "tmp" + str(i) + ".jpg"
#        try:
#          os.remove(pic)
#        except:
#          pass
#        img = open(pic, "w")
#        img.write(content)
#        print '<img src="%s"><br /><br />' % pic
#        img.close()
#      except:
#        pass

def Store_frame2():
  top(browser, p)
  i = 0
  print '<tr>\n'
  print '<form method="post" action="cart.py">'
  print "<input type='hidden' name='store' value='%s' />" % store
  print "<input type='hidden' name='whatDo' value='insert' />"
  if pkg == 'no':
    printAProduct()
  else:
    cursor.execute('select ProductID from productsPackages where
PackageID=%s' % id)
    for id in [itm[0] for itm in cursor]:
      printAProduct(id)
  if store == 'prescriptions':
    print "<input type='hidden' name='quantity' value='1' />"
    print "<input type='submit' value=' Refill ' />"
  elif truncate()[store] != '':
    pass
  else:
    print "<b>Quantity</b>: <input type='text' name='quantity' width='3'
maxlength='3' /><br />"
    print "<input type='submit' value=' Add To Cart ' />"
  print '</form>'
  print '</td></tr></table>\n'
  print '</table>\n'
  cursor.close()
  bottom()

Store_frame2()


-- 
The Logos has come to bear
http://logos.13gems.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100120/3687def1/attachment.html>


More information about the Python-list mailing list