Re: Don't Want Visitor To See Nuttin'

2011-03-11 Thread Victor Subervi
On Fri, Mar 11, 2011 at 3:54 AM, Ian Kelly ian.g.ke...@gmail.com wrote:

 On Wed, Mar 9, 2011 at 2:01 PM, Victor Subervi victorsube...@gmail.com
 wrote:
  titleMaya 2012: Transform At the Source/title

 Yow.  You're designing a Maya 2012 website to help some travel company
 bilk gullible people out of thousands of dollars?  I would be ashamed
 to have anything to do with this.


Um...just for the record, these guys have ben featured on the FRONT PAGES
OF:
The Wall Street Journal
The Los Angeles Times
The San Francisco Chronicle
and have appeared on:
Eye-To-Eye with Connie Chung
CNN's Travel Guide
and National Geographic's Travel Magazine called them the graddaddy of
metaphysical tours.
If you'll go to the About Us page you'll see their photo with the Dalai
Lama.

They're ligit :)
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Don't Want Visitor To See Nuttin'

2011-03-11 Thread Victor Subervi
On Fri, Mar 11, 2011 at 4:26 AM, Dennis Lee Bieber wlfr...@ix.netcom.comwrote:

 On Thu, 10 Mar 2011 18:00:10 -0800 (PST), alex23 wuwe...@gmail.com
 declaimed the following in gmane.comp.python.general:

  He's comp.lang.python's version of Sisyphus. Or maybe Sisyphus'
  boulder...I forget where I was going with this.

 The boulder -- given that we are the ones suffering... G


OK, fine, don't respond. The page works. I'm changing names and email
addresses. CU as someone else.
Bye,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Don't Want Visitor To See Nuttin'

2011-03-10 Thread Victor Subervi
On Wed, Mar 9, 2011 at 5:33 PM, Ian hobso...@gmail.com wrote:

 On 09/03/2011 21:01, Victor Subervi wrote:

 The problem is that it prints Content-Type: text/html to the screen

 If you can see what is intended to be a header, then it follows that you
 are not sending the header correctly.

 Sorry - can't tell you how to send a header. You don't say what framework
 you are using.


Framework? Python on CentOS, if that's what you're asking. From what I know
of python, one always begins a web page with something like this:

  print Content-Type: text/html
  print
  print '''
!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd;
html
head

and this has worked in the past, so I'm surprised it doesn't work here.
Don't understand what I've done wrong, nor why it prints the first line to
screen.
TIA,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Don't Want Visitor To See Nuttin'

2011-03-10 Thread Victor Subervi
On Thu, Mar 10, 2011 at 8:50 PM, Benjamin Kaplan
benjamin.kap...@case.eduwrote:

print Content-Type: text/html
print
print '''
  !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN
  http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd;
  html
  head
 
  and this has worked in the past, so I'm surprised it doesn't work here.
  Don't understand what I've done wrong, nor why it prints the first line
 to
  screen.
  TIA,
  Beno
 

 Typically, people developing web applications use a framework such as
 Django or TurboGears (or web.py or CherryPy or any of a dozen others)
 rather than just having the CGI scripts print stuff out. Rather than
 having your Python script just print out a page, you make a template
 and then have a templating engine fill in the blanks with the values
 you provide. They'll also protect you from things like Injection
 attacks and cross-site scripting (if you don't know what those are,
 you're probably vulnerable to them).

 ok. I'm looking into Django. I'm ok for injections and I think most of my
data is sanitized. Now, can someone please address my question? See above.
TIA,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How Translate This PHP

2011-03-09 Thread Victor Subervi
On Sun, Mar 6, 2011 at 12:00 PM, Noah Hall enali...@gmail.com wrote:

 On Sun, Mar 6, 2011 at 3:11 PM, Victor Subervi victorsube...@gmail.com
 wrote:
  Ah. I thought I had to return something!

 Well, based on what you asked, you would've, but based on the code,
 all it was doing is printing returnValue - value

 Of course, a better way of doing it would be to use formatting -

 For example,

 print 'returnValue=%d' % ok



Thanks.
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Absolutely Insane Problem with Gmail

2011-03-06 Thread Victor Subervi
On Sat, Mar 5, 2011 at 11:11 PM, Littlefield, Tyler ty...@tysdomain.comwrote:

 ourEmail = '
 myemaila...@gmail.com'

 ourEmail = '
 q...@xxx.com'

   You redefine this twice.


Right. The second definition, of course, overwrites the first. That is
deliberate. I simply comment out the second when I'm testing. The second is,
of course, bogus. But it works while the first doesn't!!! WHY???


 You also don't define a variable down lower.
 #  to_address = ourEmail,

   from_address = ourEmail,
   to_address = emailText,
 I could be wrong, but emailText isn't defined.


No, in fact, emailText *is* defined. And it, too, works, *unless* it's going
to a gmail address!! In fact, I just now tested it, commenting out the
second bogus email address, and using another gmail address but different
than the one defined as ourEmail, and everything works as expected.
Therefore, it appears that gmail, for whatever reason, filters out emails
send to the same address from which they are sent.
Thanks,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


How Translate This PHP

2011-03-06 Thread Victor Subervi
Hi;
How do I translate this PHP code?

if($ok){
echo returnValue=1;
}else{
echo returnValue=0;
}

In other words, when the email successfully sends, send back both the name
of the variable and its value.
TIA,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How Translate This PHP

2011-03-06 Thread Victor Subervi
On Sun, Mar 6, 2011 at 10:53 AM, Noah Hall enali...@gmail.com wrote:

 On Sun, Mar 6, 2011 at 2:45 PM, Victor Subervi victorsube...@gmail.com
 wrote:
  Hi;
  How do I translate this PHP code?
 
  if($ok){
  echo returnValue=1;
  }else{
  echo returnValue=0;
  }

 From the code provided -

 if ok:
print 'returnValue=1'
 else:
print 'returnValue=0'


Ah. I thought I had to return something! Thanks,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Absolutely Insane Problem with Gmail

2011-03-05 Thread Victor Subervi
Hi;
I have this code:

#!/usr/bin/python

import sys, os, string
import cgitb; cgitb.enable()
import cgi
cwd = os.getcwd()
dirs = string.split(cwd, '/')
dirs = dirs[1:-1]
backLevel = '/' + string.join(dirs, '/')
sys.path.append(cwd)
sys.path.append(backLevel)
import string
form = cgi.FieldStorage()
// all the fields here
subject = 'Order For Maya 2012'
msg = 'First Name: %s\nLast Name: %s\nEmail Address: %s\nAddress2: %s, City:
%s\nState: %s\nCountry: %s\nZip: %s\nPhone: %s\nFax: %s\nMessage: %s\n' %
(firstNameText, lastNameText, emailText, addrText, addr2Te
xt, cityText, stateText, countryText, zipText, faxText, messageText)
### LOOK AT THESE TWO LINES
ourEmail = 'myemaila...@gmail.com'
ourEmail = 'q...@xxx.com'

def my_mail():
  emailOne()
  emailTwo()

def emailOne():
  from simplemail import Email
  Email(
  from_address = ourEmail,
  to_address = emailText,
  subject = 'Thank you for your order!',
  message = msg
  ).send()

def emailTwo():
  from simplemail import Email
  Email(
  from simplemail import Email
  Email(
#  from_address = emailText,
#  to_address = ourEmail,
  from_address = ourEmail,
  to_address = emailText,
  subject = 'Order for Maya 2012',
  message = msg
  ).send()

print '''Content-type: text/html

!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
html
head
title/title
link rel=stylesheet type=text/css href=../../css/style.css
/head
body'''
my_mail()
print '''
/body
/html
'''

Now what's absolutely crazy about this is that if I use my online form and
enter my gmail address I get the email confirmations. However, if I get rid
of that garbage value for ourEmail and use the other one which is the
_very_same_gmail_address I get nothing!! No email. Ditto if I uncomment
those lines in emailTwo and delete the next two lines. What on earth could
be doing this???
TIA,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Communicating from Flash to Python

2011-03-04 Thread Victor Subervi
On Fri, Mar 4, 2011 at 2:57 AM, Godson Gera godso...@gmail.com wrote:

 You can use PyAMF http://pyamf.org


Thanks!
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Communicating from Flash to Python

2011-03-03 Thread Victor Subervi
Hi;
I have an AS3 script that is supposed to communicate with a python script
and I don't think it is. The python script is to email. How can I
trouble-shoot this?
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


OT: Need Interactivity With the Browser

2011-02-16 Thread Victor Subervi
Hi;
I would like to build a component where the user can go to a page, say he'd
like to upload so many (x) number of photos, click a button and without
leaving the page have three sets of upload widgets pop up. I think this is
done with Json; however, I can't find much info or tutorials on the same
that help me know if Json is my tool. (After spending a half hour studying
it online I'm still at a loss as to how it helps or what id does, just that
it's somewhat similar to XML) And I cannot find a discussion list on the
subject, either. Please advise.
TIA,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Another MySQLdb Q

2011-02-16 Thread Victor Subervi
Hi;
I have this code:
  db = MySQLdb.connect(host, user, passwd, db)
  cursor= db.cursor()
  cursor.execute(sql, id)
  db.commit()

It throws no errors and gives every indication that it executes the command.
I've printed out the command and the id and executed it successfully in
mysql...but not in python from the script. Everything else works in MySQLdb.
What could be the problem?
TIA,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem w/ MySQLdb

2011-02-15 Thread Victor Subervi
Hi;
I have a function that calls the following class:

#!/usr/bin/python

import sys,os
sys.path.append(os.getcwd())
import MySQLdb
from login import login
import re, string

def buildTableColorShortOptions():
  user, passwd, db, host = login()
  database = MySQLdb.connect(host, user, passwd, db)
  cursor = database.cursor()
  cursor.execute('''create table if not exists colorShortOptions (
Color varchar(40) not null,
Value bool not null default '0'
) engine=innodb''')
  cursor.execute(insert into colorShortOptions (Color) values ('indigo'))
  cursor.execute(insert into colorShortOptions (Color) values ('maroon'))
  cursor.execute(insert into colorShortOptions (Color) values ('violet'))
  cursor.execute(insert into colorShortOptions (Color) values ('tan'))
  cursor.execute(insert into colorShortOptions (Color) values ('lime'))
  cursor.execute(insert into colorShortOptions (Color) values ('blue'))
  cursor.execute(insert into colorShortOptions (Color) values ('fuchsia'))
  cursor.execute(insert into colorShortOptions (Color) values ('cobalt
blue'))
  cursor.execute(insert into colorShortOptions (Color) values ('black'))
  cursor.execute(insert into colorShortOptions (Color) values ('rose
pink'))
  cursor.execute(insert into colorShortOptions (Color) values ('air force
blue'))
  cursor.execute(insert into colorShortOptions (Color) values ('orange'))
  cursor.execute(insert into colorShortOptions (Color) values ('white'))
  cursor.execute(insert into colorShortOptions (Color) values ('red'))
  cursor.execute(insert into colorShortOptions (Color) values ('yellow
green'))
  cursor.execute(insert into colorShortOptions (Color) values ('navy
blue'))
  cursor.execute(insert into colorShortOptions (Color) values ('salmon'))
  cursor.execute(insert into colorShortOptions (Color) values ('yellow'))
  cursor.execute(insert into colorShortOptions (Color) values ('olive'))
  cursor.execute(insert into colorShortOptions (Color) values ('sky
blue'))
  cursor.execute(insert into colorShortOptions (Color) values ('silver'))
  cursor.execute(insert into colorShortOptions (Color) values ('gray'))
  cursor.execute(insert into colorShortOptions (Color) values ('green'))
  cursor.execute(insert into colorShortOptions (Color) values ('teal'))
  cursor.close()

It builds the table but fails from the first insertion. Trying to insert
using that code directly in MySQL does indeed work. Why?
TIA,
Beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem w/ MySQLdb

2011-02-15 Thread Victor Subervi
It's been too long since I've worked on this. Yep, I forgot to commit.
Thanks,
Beno

On Tue, Feb 15, 2011 at 5:21 PM, Jerry Hill malaclyp...@gmail.com wrote:

 On Tue, Feb 15, 2011 at 3:24 PM, Victor Subervi victorsube...@gmail.com
 wrote:
  It builds the table but fails from the first insertion. Trying to insert
  using that code directly in MySQL does indeed work. Why?

 In what way does it fail?  Does it give you a stack trace, and if so,
 what does it say?  Does it create the table, but not populate any
 data?  If that's the case, you probably need to call commit() after
 you do your inserts.

 I'm not familiar with the MySQLDB module in particular, but python
 database adapters typically do not autocommit, unless you explicitly
 ask for that behavior.

 --
 Jerry
 --
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing from Web Page

2010-11-21 Thread Victor Subervi
On Sun, Nov 21, 2010 at 5:35 AM, FELD Boris lothiral...@gmail.com wrote:

 I think the best way to do this is using css with specific media type.
 Take a look at : http://martybugs.net/articles/print.cgi


Oh, man, this is perfect! Thanks!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Printing from Web Page

2010-11-20 Thread Victor Subervi
Hi;
I need to be able to print something from a Web page: not the entire page
but what I specify. I am writing the page and the client is surfing to it.
How do I do this?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


MySQL Query Problem

2010-09-17 Thread Victor Subervi
Hi;
I have this code:

cursor.execute('insert into Passengers values (Null, %s, %s, %s, %s,
%s, %s, %s, %s, no, n/a)', (curr_flight, curr_customer, name, curr_sex,
curr_weight, price, curr_rt, curr_confirmation))

Now, when I print it out, add quotes where necessary and enter it in at a
mysql prompt, all goes well. But when I do it this way, it enters null
values for curr_customer and curr_weight! Same darn thing printed out works
at the prompt. What gives?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL Query Problem

2010-09-17 Thread Victor Subervi
Here's some more data:

print 'insert into Passengers values (Null, %s, %s, %s, %s, %s, %s,
%s, %s, no, n/a)' % (curr_flight, curr_customer, name, curr_sex,
curr_weight, price, curr_rt, curr_confirmation)
cursor.execute('insert into Passengers values (Null, %s, %s, %s, %s,
%s, %s, %s, %s, no, n/a)', (curr_flight, curr_customer, name, curr_sex,
curr_weight, price, curr_rt, curr_confirmation))
database.commit()
cursor.execute('select last_insert_id() from Passengers')
last_insert_id = cursor.fetchone()[0]
print 'update Passengers set name=%s, weight=%s where id=%s' %
(name, curr_weight, last_insert_id)
cursor.execute('update Passengers set name=%s, weight=%s where
id=%s', (name, curr_weight, last_insert_id))
database.commit()

This prints out:

insert into Passengers values (Null, 1, 1, Dr. Mengela, Male, 155, 100, 100,
654, no, n/a)
update Passengers set name=Dr. Mengela, weight=155 where id=15

Here's what's in the database:

mysql select * from Passengers;
+++-+--+--++---++--+--+---+
| id | flights_id | customer_id | name | sex  | weight | price | round_trip
| confirmation | late_fee | late_fee_paid |
+++-+--+--++---++--+--+---+
|  1 |  1 |   1 | ''   | NULL |   NULL |  0.00 |  0
| 12345| NULL | NULL  |
| 15 |  1 |   1 | ''   | Male |   NULL |  0.00 |100
| 654  | no   | n/a   |
+++-+--+--++---++--+--+---+
2 rows in set (0.00 sec)

mysql describe Passengers;
+---+---+--+-+-++
| Field | Type  | Null | Key | Default |
Extra  |
+---+---+--+-+-++
| id| int(11)   | NO   | PRI | NULL|
auto_increment |
| flights_id| int(11)   | NO   | MUL | NULL
||
| customer_id   | int(11)   | NO   | MUL | NULL
||
| name  | varchar(40)   | YES  | | NULL
||
| sex   | enum('Male','Female') | YES  | | NULL
||
| weight| int(11)   | YES  | | NULL
||
| price | float(6,2)| NO   | | NULL
||
| round_trip| tinyint(1)| NO   | | 1
||
| confirmation  | varchar(20)   | YES  | | NULL
||
| late_fee  | enum('no','yes')  | YES  | | no
||
| late_fee_paid | enum('n/a','paid','not paid') | YES  | | n/a
||
+---+---+--+-+-++
11 rows in set (0.00 sec)

and when I run the update:

mysql select * from Passengers;
+++-+-+--++---++--+--+---+
| id | flights_id | customer_id | name| sex  | weight | price |
round_trip | confirmation | late_fee | late_fee_paid |
+++-+-+--++---++--+--+---+
|  1 |  1 |   1 | ''  | NULL |   NULL |  0.00
|  0 | 12345| NULL | NULL  |
| 15 |  1 |   1 | Dr. Mengela | Male |155 |  0.00
|100 | 654  | no   | n/a   |
+++-+-+--++---++--+--+---+
2 rows in set (0.00 sec)

Please explain why it does that!
TIA,
beno

On Fri, Sep 17, 2010 at 8:51 AM, Victor Subervi victorsube...@gmail.comwrote:

 Hi;
 I have this code:

 cursor.execute('insert into Passengers values (Null, %s, %s, %s,
 %s, %s, %s, %s, %s, no, n/a)', (curr_flight, curr_customer, name,
 curr_sex, curr_weight, price, curr_rt, curr_confirmation))

 Now, when I print it out, add quotes where necessary and enter it in at a
 mysql prompt, all goes well. But when I do it this way, it enters null
 values for curr_customer and curr_weight! Same darn thing printed out works
 at the prompt. What gives?
 TIA,
 beno

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL Query Problem

2010-09-17 Thread Victor Subervi
I rebooted MySQL and it now works fine ;)

On Fri, Sep 17, 2010 at 9:26 AM, Victor Subervi victorsube...@gmail.comwrote:

 Here's some more data:

 print 'insert into Passengers values (Null, %s, %s, %s, %s, %s, %s,
 %s, %s, no, n/a)' % (curr_flight, curr_customer, name, curr_sex,
 curr_weight, price, curr_rt, curr_confirmation)

 cursor.execute('insert into Passengers values (Null, %s, %s, %s,
 %s, %s, %s, %s, %s, no, n/a)', (curr_flight, curr_customer, name,
 curr_sex, curr_weight, price, curr_rt, curr_confirmation))
 database.commit()
 cursor.execute('select last_insert_id() from Passengers')
 last_insert_id = cursor.fetchone()[0]
 print 'update Passengers set name=%s, weight=%s where id=%s' %
 (name, curr_weight, last_insert_id)
 cursor.execute('update Passengers set name=%s, weight=%s where
 id=%s', (name, curr_weight, last_insert_id))
 database.commit()

 This prints out:

 insert into Passengers values (Null, 1, 1, Dr. Mengela, Male, 155, 100,
 100, 654, no, n/a)
 update Passengers set name=Dr. Mengela, weight=155 where id=15

 Here's what's in the database:

 mysql select * from Passengers;

 +++-+--+--++---++--+--+---+
 | id | flights_id | customer_id | name | sex  | weight | price | round_trip
 | confirmation | late_fee | late_fee_paid |

 +++-+--+--++---++--+--+---+
 |  1 |  1 |   1 | ''   | NULL |   NULL |  0.00 |  0
 | 12345| NULL | NULL  |
 | 15 |  1 |   1 | ''   | Male |   NULL |  0.00 |100
 | 654  | no   | n/a   |

 +++-+--+--++---++--+--+---+
 2 rows in set (0.00 sec)

 mysql describe Passengers;

 +---+---+--+-+-++
 | Field | Type  | Null | Key | Default |
 Extra  |

 +---+---+--+-+-++
 | id| int(11)   | NO   | PRI | NULL|
 auto_increment |
 | flights_id| int(11)   | NO   | MUL | NULL
 ||
 | customer_id   | int(11)   | NO   | MUL | NULL
 ||
 | name  | varchar(40)   | YES  | | NULL
 ||
 | sex   | enum('Male','Female') | YES  | | NULL
 ||
 | weight| int(11)   | YES  | | NULL
 ||
 | price | float(6,2)| NO   | | NULL
 ||
 | round_trip| tinyint(1)| NO   | | 1
 ||
 | confirmation  | varchar(20)   | YES  | | NULL
 ||
 | late_fee  | enum('no','yes')  | YES  | | no
 ||
 | late_fee_paid | enum('n/a','paid','not paid') | YES  | | n/a
 ||

 +---+---+--+-+-++
 11 rows in set (0.00 sec)

 and when I run the update:

 mysql select * from Passengers;

 +++-+-+--++---++--+--+---+
 | id | flights_id | customer_id | name| sex  | weight | price |
 round_trip | confirmation | late_fee | late_fee_paid |

 +++-+-+--++---++--+--+---+
 |  1 |  1 |   1 | ''  | NULL |   NULL |  0.00
 |  0 | 12345| NULL | NULL  |
 | 15 |  1 |   1 | Dr. Mengela | Male |155 |  0.00
 |100 | 654  | no   | n/a   |

 +++-+-+--++---++--+--+---+
 2 rows in set (0.00 sec)

 Please explain why it does that!
 TIA,
 beno


 On Fri, Sep 17, 2010 at 8:51 AM, Victor Subervi 
 victorsube...@gmail.comwrote:

 Hi;
 I have this code:

 cursor.execute('insert into Passengers values (Null, %s, %s, %s,
 %s, %s, %s, %s, %s, no, n/a)', (curr_flight, curr_customer, name,
 curr_sex, curr_weight, price, curr_rt, curr_confirmation))

 Now, when I print it out, add quotes where necessary and enter it in at a
 mysql prompt, all goes well. But when I do it this way, it enters null
 values for curr_customer and curr_weight! Same darn thing printed out works
 at the prompt. What gives?
 TIA,
 beno



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL Problem

2010-09-03 Thread Victor Subervi
On Thu, Sep 2, 2010 at 3:02 PM, Ian hobso...@gmaiil.com wrote:

  On 02/09/2010 19:34, Victor Subervi wrote:

 for some reason running the command through python *omits* this one data!!
 The only difference is that a flag in spreadsheets (Temp) is set to 1. Why
 on earth doesn't it work in python??

 Some ideas to follow up.  (These are only guesses).

 1) One of the enum type fields contains an invalid value (perhaps a value
 removed from the column definition).


There are no enum type fields.


 2) The second id field (products.id?) appears to be very large. I wonder
 what would happen if it was larger than the auto-increment value?


It's not an ID field. It doesn't auto_increment.


 3) A field in the one of the rows in the missing data contains bytes that
 are invalid in the character encoding you are using in python.


I changed the only bytes I thought might affect it. Furthermore, I
successfully added the blasted data to that field so it would show up in the
spreadsheet through another form. More on that later.


 4) The python field type used for some column in the missing row, contains
 a value that cannot be held in the python variable assigned.


If that were so, none of the data would show up.

Please look at this comparison:

FIELDBAD DATA   GOOD DATA
ID609161
ClientLincoln_PropertiesLincoln_Properties
Multi00
Item203057240x48Green
Markup0.0099.32
Temp1Null
ID34337
Item203057240x48Green
DescriptionAmerico 20 Beige Floor PadGreen Can Liners
UOM5/cs1000/cs
Cost15.8817.56
ID33537
ProductsID34337
CategoryID4923
ID4923
CategoryMatsCan Liners
ParentRestaurant Paper/PlaBags

I have changed the value of Temp to Null and Markup to 11.11 to see if that
would somehow make a difference. It didn't. Then I used my TTW form for
adding data regularly to spreadsheets and it worked. The form I'm testing
enables the client to add data himself. The code is the same in both cases:

regular
cursor.execute('insert into spreadsheets values (Null, %s, 0, %s, 0, Null)',
(client, prod))

special
cursor.execute('insert into spreadsheets values (Null, %s, 0, %s, 0, Null)',
(client, product[1]))

I checked permissions and changed ownership to make the two scripts
identical. Again, the data gets entered into MySQL correctly...it just
doesn't show up with the rest of the data in the TTW form!! Why??
TIA,
beno


 Regards

 Ian



 --
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL Problem

2010-09-03 Thread Victor Subervi
This is an addendum to my last post. Please observe the following:

mysql select * from spreadsheets where Temp=1;
+-++---+-++--+
| ID  | Client | Multi | Item| Markup | Temp |
+-++---+-++--+
| 611 | Lincoln_Properties | 0 | 2030572 |   0.00 |1 |
| 621 | Lincoln_Properties | 0 | 2030572 |   0.00 |1 |
+-++---+-++--+
2 rows in set (0.00 sec)

mysql describe spreadsheets;
++--+--+-+-++
| Field  | Type | Null | Key | Default | Extra  |
++--+--+-+-++
| ID | int(11) unsigned | NO   | PRI | NULL| auto_increment |
| Client | varchar(40)  | YES  | | NULL||
| Multi  | tinyint(1)   | YES  | | NULL||
| Item   | varchar(40)  | YES  | | NULL||
| Markup | float(6,2)   | YES  | | NULL||
| Temp   | tinyint(1)   | YES  | | NULL||
++--+--+-+-++
6 rows in set (0.00 sec)

Yet from my script:

cursor.execute('select * from spreadsheets where Temp=1')
print cursor.fetchall()

print nothing but an empty set: () Why??
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL Problem

2010-09-03 Thread Victor Subervi
On Fri, Sep 3, 2010 at 9:25 AM, Richard Arts arts.rich...@gmail.com wrote:

 These are also mere suggestions.

 The statements you use in your print statement and the one you use to
 feed the cursor differ slightly. The latter is missing quotes around
 your search criterium.

 Isn't it possible to fetch results row by row and see if the missing
 row is in the set? That way you can get a better feeling about the
 nature of the error.


Well, I just tried, out of curiosity,  inserting 0 instead of 1 and guess
what? It shows up. So by simply changing that my problem is solved...but I
sure as heck would like to know why!


  cursor.execute('insert into spreadsheets values (Null, %s, 0, %s, 0,
 Null)', (client, prod))

 Out of curiosity, why would you want to insert null values in id
 fields? That's a disaster waiting to happen.


Hardly. This is the standard way of inserting into auto_increment fields.
That triggers the auto_increment! That makes it much easier to insert the
correct value of the field.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


MySQL Problem

2010-09-02 Thread Victor Subervi
Hi;
I have this code:

print 'select * from spreadsheets s join products p on p.Item=s.Item
join productsCategories pc on p.ID=pc.ProductsID join categories c on
pc.CategoryID=c.ID where s.Client=%s order by c.Category, c.Parent' %
(client,)
cursor.execute('select * from spreadsheets s join products p on
p.Item=s.Item join productsCategories pc on p.ID=pc.ProductsID join
categories c on pc.CategoryID=c.ID where s.Client=%s order by c.Category,
c.Parent', (client,))
tmp = cursor.fetchall()
print tmp

Now, when I run the print of the mysql command in the mysql interpreter, it
gives me the following data:

mysql select * from spreadsheets s join products p on p.Item=s.Item join
productsCategories pc on p.ID=pc.ProductsID join categories c on
pc.CategoryID=c.ID where s.Client='Lincoln_Properties' order by c.Category,
c.Parent;
+-++---+++--+-++--+-+---+-++++---+--+
| ID  | Client | Multi | Item   | Markup | Temp | ID  |
Item   | Description  | UOM
| Cost  | ID  | ProductsID | CategoryID | ID | Category  |
Parent   |
+-++---+++--+-++--+-+---+-++++---+--+
| 163 | Lincoln_Properties | 0 | 5349513|  53.22 | NULL |  39 |
5349513| 24833RNH 24#34; x 33 #34; 8 Mic Natural Can Liners | 1000/CS
| 25.63 |  39 | 39 | 23 | 23 | Can Liners|
Bags |
| 156 | Lincoln_Properties | 0 | 5349520|  30.00 | NULL |  31 |
5349520| Can Liners Coreless 45 gal Clear | 250/CS
| 28.69 |  31 | 31 | 23 | 23 | Can Liners|
Bags |
| 161 | Lincoln_Properties | 0 | 40x48Green |  99.32 | NULL |  37 |
40x48Green | Green Can Liners | 1000/cs
| 17.56 |  37 | 37 | 23 | 23 | Can Liners|
Bags |
| 160 | Lincoln_Properties | 0 | 24x33Green |  60.04 | NULL |  36 |
24x33Green | Green Can Liners | 1000/CS
| 20.27 |  36 | 36 | 23 | 23 | Can Liners|
Bags |
| 162 | Lincoln_Properties | 0 | 5349518|  26.02 | NULL |  38 |
5349518| 28048VNR01 40#34; x 48#34; HI-D| 250/CS
| 25.63 |  38 | 38 |  1 |  1 | Facility Supplies |
BASE |
| 152 | Lincoln_Properties | 0 | 4440120|  72.44 | NULL |  35 |
4440120| 91315 Pearlescent White Lotion Gallon Soap   | 4/CS
| 17.85 |  35 | 35 | 67 | 67 | Liquid Hand   |
Soap |
| 609 | Lincoln_Properties | 0 | 2030572|   0.00 |1 | 343 |
2030572| Americo 20#34; Beige Floor Pad  | 5/cs
| 15.88 | 335 |343 | 49 | 49 | Mats  |
Restaurant Paper/Pla |
| 159 | Lincoln_Properties | 0 | 2028071|  20.00 | NULL |  34 |
2028071| 25025088 77 Sanisac Liner| 500/CS
| 14.88 |  34 | 34 | 34 | 34 | Tampons   | Bathroom
Paper   |
| 158 | Lincoln_Properties | 0 | 2062866|  33.31 | NULL |  33 |
2062866| 7410 1/2 Fold Seat Cover | 3000/CS
| 35.81 |  33 | 33 | 35 | 35 | Toilet Seat Cover | Bathroom
Paper   |
| 155 | Lincoln_Properties | 0 | 5380447|  30.00 | NULL |  30 |
5380447| Scottfold Foldedd Towel 1-Ply White  | 4375/CS
| 35.00 |  30 | 30 | 33 | 33 | Toilet Tissue | Bathroom
Paper   |
| 154 | Lincoln_Properties | 0 | 5207270|   7.01 | NULL |  29 |
5207270| Standard Roll Bath Tissue 2-Ply White| 80/CS
| 43.50 |  29 | 29 | 33 | 33 | Toilet Tissue | Bathroom
Paper   |
| 164 | Lincoln_Properties | 0 | 5207269|  20.00 | NULL |  28 |
5207269| 17713-00 Kleenex Cottonelle 2-Ply Toilet Tissue  | 60/CS
| 35.50 |  28 | 28 | 33 | 33 | Toilet Tissue | Bathroom
Paper   |
| 157 | Lincoln_Properties | 0 | 5217344|  17.49 | NULL |  32 |
5217344| 1900-60 Kleenex Scottfold White Towel| 2400/CS
| 26.81 |  32 | 32 | 32 | 32 | Towels| Bathroom
Paper   |
+-++---+++--+-++--+-+---+-++++---+--+
13 rows in set (0.00 sec)

You will notice there is this data therein:

| 609 | Lincoln_Properties | 0 | 2030572|   

Re: Reversing a List

2010-09-02 Thread Victor Subervi
On Wed, Sep 1, 2010 at 9:26 AM, Shashwat Anand anand.shash...@gmail.comwrote:



 On Wed, Sep 1, 2010 at 6:45 PM, Matt Saxton m...@scotweb.co.uk wrote:

 On Wed, 1 Sep 2010 09:00:03 -0400
 Victor Subervi victorsube...@gmail.com wrote:

  Hi;
  I have this code:
 
cursor.execute('describe products;')
cols = [item[0] for item in cursor]
cols = cols.reverse()
cols.append('Delete')
cols = cols.reverse()
 
  Unfortunately, the list doesn't reverse. If I print cols after the first
  reverse(), it prints None. Please advise.

 The reverse() method modifies the list in place, but returns None, so just
 use
  cols.reverse()

 rather than
  cols = cols.reverse()


 Alternatively you can do \,

 cols = reversed(cols)


Thanks again, all
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Reversing a List

2010-09-01 Thread Victor Subervi
Hi;
I have this code:

  cursor.execute('describe products;')
  cols = [item[0] for item in cursor]
  cols = cols.reverse()
  cols.append('Delete')
  cols = cols.reverse()

Unfortunately, the list doesn't reverse. If I print cols after the first
reverse(), it prints None. Please advise. Also, is there a way to append to
the front of the list directly?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a List

2010-09-01 Thread Victor Subervi
On Wed, Sep 1, 2010 at 9:17 AM, Shashank Singh 
shashank.sunny.si...@gmail.com wrote:

 reverse reverses in-place

  l = [1, 2, 3]
  r = l.reverse()
  r is None
 True
  l
 [3, 2, 1]
 


Ah. Thanks!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


MySQL One More Again

2010-07-16 Thread Victor Subervi
Hi;
I have the following code:

cursor.execute('select MyTable from optionsDetails where Store=%s',
(store,))
options_tables = [item[0] for item in cursor]
for table in options_tables:
  cursor.execute('select * from %' % table)

You can already see what my question is. One of y'all said it's possible
under certain conditions to use the % without risking attack. Now is when I
need to know how to do that. Please advise.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL One More Again

2010-07-16 Thread Victor Subervi
On Fri, Jul 16, 2010 at 10:09 AM, MRAB pyt...@mrabarnett.plus.com wrote:

 Victor Subervi wrote:

 Hi;
 I have the following code:

cursor.execute('select MyTable from optionsDetails where Store=%s',
 (store,))
options_tables = [item[0] for item in cursor]
for table in options_tables:
  cursor.execute('select * from %' % table)

  Should be:

'select * from %s' % table

 Details! :-)


LOL. Whoops. Thanks.



  You can already see what my question is. One of y'all said it's possible
 under certain conditions to use the % without risking attack. Now is when I
 need to know how to do that. Please advise.

  It's safe when there's no way that the value you're putting in can come
 from the user.

 Here you're taking it from the 'optionsDetails' table. Can the user add,
 alter or delete that entry in any way?


No, and that's kind of what I figured. Thanks!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is This Open To SQL Injection?

2010-07-08 Thread Victor Subervi
On Wed, Jul 7, 2010 at 2:22 PM, Stephen Hansen me+list/pyt...@ixokai.iowrote:

 First, its always best to be explicit with insert statements. Meaning,
 don't rely on the underlining structure of a table, as in:

 INSERT INTO YourRandomTable VALUES (my, value, here);

 Instead, do:

 INSERT INTO YourRandomTable (field1, field2, field3) VALUES (my,
 value, here);

 By following this advice, I realized I didn't need to do that fancy
multiplying out the '%s' which was screwing me up anyway, and then I didn't
need to create an sql using a '%', and then I didn't need to open the door
to injection attack!

However, I now have another error. Here is my current command:

cursor.execute(insert into personalDataKeys (Store, User, useFirstName,
useLastName, usePhone, useCell, useFax, useAddress, useShippingAddress,
useDOB, useEmail, usePW) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
%s), ([store, user] + col_vals))

I get this error from MySQL which I am having a hard time understanding:

LATEST FOREIGN KEY ERROR

100708  6:15:01 Transaction:
TRANSACTION 0 9382, ACTIVE 0 sec, process no 5326, OS thread id 1169992000
inserting, thread declared inside InnoDB 500
mysql tables in use 1, locked 1
3 lock struct(s), heap size 368, undo log entries 1
MySQL thread id 1502, query id 23700 localhost beno update
insert into personalDataKeys (Store, User, useFirstName, useLastName,
usePhone, useCell, useFax, useAddress, useShippingAddress, useDOB, useEmail,
usePW) values ('specialty', 'patients', 1, 1, 1, 1, 1, 1, 0, 1, 1, 1)
Foreign key constraint fails for table `test/personalDataKeys`:
,
  CONSTRAINT `personalDataKeys_ibfk_1` FOREIGN KEY (`Store`) REFERENCES
`products` (`Store`)
Trying to add in child table, in index `Store` tuple:
DATA TUPLE: 2 fields;
 0: len 9; hex 7370656369616c7479; asc specialty;; 1: len 6; hex
03b7; asc   ;;

But in parent table `test/products`, in index `Store`,
the closest match we can find is record:
PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 696e66696d756d00; asc infimum ;;

What is this tuple?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is This Open To SQL Injection?

2010-07-08 Thread Victor Subervi
On Thu, Jul 8, 2010 at 10:45 AM, Stephen Hansen me+list/pyt...@ixokai.iowrote:

 On 7/8/10 6:20 AM, Victor Subervi wrote:
  However, I now have another error. Here is my current command:
 
  cursor.execute(insert into personalDataKeys (Store, User,
  useFirstName, useLastName, usePhone, useCell, useFax, useAddress,
  useShippingAddress, useDOB, useEmail, usePW) values (%s, %s, %s, %s, %s,
  %s, %s, %s, %s, %s, %s, %s), ([store, user] + col_vals))

 Quick point: why the parens around [store, user] + col_vars? They're
 redundant.

 
  I get this error from MySQL which I am having a hard time understanding:
 
  LATEST FOREIGN KEY ERROR
  
  100708  6:15:01 Transaction:
  TRANSACTION 0 9382, ACTIVE 0 sec, process no 5326, OS thread id
  1169992000 inserting, thread declared inside InnoDB 500
  mysql tables in use 1, locked 1
  3 lock struct(s), heap size 368, undo log entries 1
  MySQL thread id 1502, query id 23700 localhost beno update
  insert into personalDataKeys (Store, User, useFirstName, useLastName,
  usePhone, useCell, useFax, useAddress, useShippingAddress, useDOB,
  useEmail, usePW) values ('specialty', 'patients', 1, 1, 1, 1, 1, 1, 0,
  1, 1, 1)
  Foreign key constraint fails for table `test/personalDataKeys`:
  ,
CONSTRAINT `personalDataKeys_ibfk_1` FOREIGN KEY (`Store`) REFERENCES
  `products` (`Store`)

 A foreign key is a constraint, a restriction, which says that rows in
 TableA (personalDataKeys) depend on certain *matching* rows to already
 exist and always be valid in TableB (products); the exact match is a
 column they have in common (Store).

 The purpose of foreign keys is to keep data consistent. Here, it appears
 as if you have established a key such that the 'store' column in your
 personalDataKeys table must point to a certain row in the products table
 which has a 'store' column of the exact same value.

 This error message is indicating that when you do this INSERT, there is
 no corresponding row in the products table.


mysql describe products Store;
+---+-+--+-+-+---+
| Field | Type| Null | Key | Default | Extra |
+---+-+--+-+-+---+
| Store | varchar(40) | NO   | MUL | NULL|   |
+---+-+--+-+-+---+
1 row in set (0.00 sec)

mysql describe personalDataKeys Store;
+---+-+--+-+-+---+
| Field | Type| Null | Key | Default | Extra |
+---+-+--+-+-+---+
| Store | varchar(40) | NO   | MUL | NULL|   |
+---+-+--+-+-+---+
1 row in set (0.00 sec)

They both use innodb. They're both indexed. I was thinking after getting
your email that maybe I'd set the varchars to different lengths, but no.
However...

mysql select * from products;
Empty set (0.00 sec)

Is it that I can't insert into personalDataKeys until I've first done so in
products? After rethinking this, it occurred to me that I probably made a
mistake in copying my create table command from personalData to
personalDataKeys, both of which had the foreign key of Store referenced to
table products. That wasn't necessary, since personalDataKeys only needs to
be associated with personalData, so I dropped and recreated the table,
updating personalDataKeys foreign key to reference personalData; however,
once again:

mysql select * from personalData;
Empty set (0.00 sec)

Here's the deal:

mysql describe personalData;
+---+--+--+-+++
| Field | Type | Null | Key | Default|
Extra  |
+---+--+--+-+++
| ID| int(10) unsigned | NO   | PRI | NULL   |
auto_increment |
| Store | varchar(40)  | NO   | MUL | NULL
||
| User  | varchar(50)  | NO   | MUL | NULL
||
| FirstName | varchar(100) | NO   | | NULL
||
| LastName  | varchar(100) | NO   | | NULL
||
| Phone | varchar(13)  | YES  | | NULL
||
| Cell  | varchar(13)  | YES  | | NULL
||
| Fax   | varchar(13)  | YES  | | NULL
||
| AddressID | int(11)  | NO   | MUL | NULL
||
| ShippingAddressID | int(11)  | NO   | MUL | NULL
||
| DOB   | date | YES  | | 2000-01-01
||
| Email | varchar(100) | NO   | | NULL
||
| PW| varchar(12)  | NO   | | NULL
||
+---+--+--+-+++
13 rows in set (0.00 sec)

mysql describe personalDataKeys

Re: Is This Open To SQL Injection?

2010-07-08 Thread Victor Subervi
I've come to the realization that I don't need FKs at all here. Essentially,
what I need to do is consult personalDataKeys simply to determine what data
should be loaded into and retrieved from personalData. I was mistaken
because the data are not interdependent, it only appeared that way
superficially.

No, the data aren't loaded into one big table. There are about 10 fields
each in these tables.

Yes, I should rename it to storeUserDataKeys.

Thanks again, Stephen.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Is This Open To SQL Injection?

2010-07-07 Thread Victor Subervi
Hi;
I have this code:

sql = 'insert into personalDataKeys values (%s, %s, %s)' % (store, user,
', %s'.join('%s' * len(col_vals))
cursor.execute(sql, col_vals)

Is this open to injection attacks? If so, how correct?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More MySQL Stuff

2010-06-29 Thread Victor Subervi
On Mon, Jun 28, 2010 at 2:24 PM, Emile van Sebille em...@fenx.com wrote:

 On 6/28/2010 9:10 AM Victor Subervi said...

 Any other suggestions?



 http://www.databaseanswers.org/tutorial4_db_schema/index.htm


Thanks. Good tutorial.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


More MySQL Stuff

2010-06-28 Thread Victor Subervi
Hi;
So I'm launching into a major rewrite of my shopping cart because I've
finally woken up to the challenge of injection attacks. One of my major
problems is that many column names are determined when the shopping cart is
built. For example, how many photos are to be uploaded is determined that
way, thus there will be a column such as pic1 and another pic2 up as
many as the client desires. Now, I guess I could cap that at, say, 9, and
create as many columns, but then there's the issue of creating columns for
all the different mixins that I add. For example, when the shop is
created, if it's a jewelry store, I automatically add columns appropriate to
the same (ring size, etc.). Now, I guess I could just create a table with
all those columns added in irrespective of what kind of store it is, then
hide those that aren't used when I print to screen such things as product
descriptions or the form the client uses to upload his data, but that's
inelegant. Any other suggestions?
TIA.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More MySQL Stuff

2010-06-28 Thread Victor Subervi
On Mon, Jun 28, 2010 at 12:11 PM, Stephen Hansen
me+list/pyt...@ixokai.iowrote:

 On 6/28/10 9:10 AM, Victor Subervi wrote:

 Hi;
 So I'm launching into a major rewrite of my shopping cart because I've
 finally woken up to the challenge of injection attacks. One of my major
 problems is that many column names are determined when the shopping cart
 is built. For example, how many photos are to be uploaded is determined
 that way, thus there will be a column such as pic1 and another pic2
 up as many as the client desires. Now, I guess I could cap that at, say,
 9, and create as many columns,


 Ah, you are now entering the realm of Normalization.

 If you think a table requires a variable number of columns, you have
 designed the table incorrectly: no table needs a variable number of columns.

 Basically, the crux of the matter is: a table does not need, and indeed
 often should not, contain every bit of detail about a certain product.

 Let's say you have a basic product table: (The syntax on this may not be
 exactly MySQL-esque, so you'll have to look it up and/or adjust: I'm doing
 the SQL just as an example):

 CREATE TABLE Products (
product_sku  INTEGER PRIMARY KEY,
product_name VARCHAR(200) NOT NULL,

product_cost MONEY NOT NULL,
product_description TEXT,

...
 )

 Etcetera. Here, in this table, you include everything that is general,
 generic, universal to your products.

 A key important point: in no circumstance should the same piece of data
 ever be in two columns, or two tables at once (unless that piece of data is
 what's linking the two tables together-- a foreign key, but I won't go into
 that too much yet-- I don't even know if MySQL enforces relationships).

 Now, you want to handle pictures? Okay, great, we do:

 CREATE TABLE ProductPictures (
product_sku  INTEGER NOT NULL,
picture_num   INTEGER NOT NULL,

picture_desc TEXT,
picture_data IMAGE,

PRIMARY KEY (product_sku, picture_id)
 )

 Now, you suddenly can have one picture per product: or a hundred. It
 doesn't matter anymore. If you want to get a list of all pictures for a
 product, you do:

 SELECT picture_id, picture_desc, picture_data FROM ProductPictures WHERE
 product_sku = sku ORDER BY picture_id

 (Also, notice that product_sku is the same name in every table, and that
 each table sort of has its own prefix? This is good practice. Even though
 product_sku in ProductPictures is in the pictures table, the value of that
 field is really a reference to a sku defined int he Products table).

 Another point: you'll notice that in ProductPictures, the primary key is a
 composite of two fields. Picture_id's may be duplicated in this table, but
 the combination of (product_sku, picture_num) will always be unique.



  but then there's the issue of creating
 columns for all the different mixins that I add. For example, when the
 shop is created, if it's a jewelry store, I automatically add columns
 appropriate to the same (ring size, etc.). Now, I guess I could just
 create a table with all those columns added in irrespective of what kind
 of store it is, then hide those that aren't used when I print to screen
 such things as product descriptions or the form the client uses to
 upload his data, but that's inelegant. Any other suggestions?


 It depends on just how generic you want this application to be. There's two
 approaches I've used: a pseudo-inheritance' approach where I have a Product
 table which has the generic information, and then a SpecificKindOfProduct
 table which adds some columns: this I only use though in cases where I can
 basically pre-define the SpecificKinds, and I'm doing this for optimization
 purposes (ie, indexing and such).

 So I might have like:

 CREATE TABLE JewelryProduct (
product_sku INTEGER NOT NULL,
jewelry_ringsize INTEGER NOT NULL,

...
 )

 And such. But I only really do that if there's a finite set of 'types' of
 products the application is for (and in such cases, I *love* PostgreSQL's
 table inheritance stuff)

 The other approach is to make a generic 'extra details' table, which looks
 basically like:

 CREATE TABLE ProductDetails (
product_sku   INTEGER NOT NULL,

detail_keyVARCHAR (200) NOT NULL,
detail_value  TEXT,

PRIMARY KEY (product_sku, detail_key)
 )

 This is a very, very simple table, its basically a set of arbitrary
 key/value pairs for a given product-- its the SQL version of a dictionary
 for every product :) In fact, even when I do have SpecificKindOfProduct
 tables as I mention above, I usually have an 'extra stuff' table here-- for
 extra stuff, because certain things always come up that just need to be
 noted. But don't abuse such tables too much, because you can't index on them
 as well.

 The one thing I wouldn't do is make a table with a bajillion columns that
 are hidden/optional depending on what kind of store it is. Better a 'master'
 table with some related smaller tables that may only be used

Re: Another MySQL Problem

2010-06-26 Thread Victor Subervi
On Fri, Jun 25, 2010 at 2:15 AM, Dennis Lee Bieber wlfr...@ix.netcom.comwrote:

 On Thu, 24 Jun 2010 09:59:41 -0430, Victor Subervi
 victorsube...@gmail.com declaimed the following in
 gmane.comp.python.general:

I could have sworn the concept had been brought up some 8 months
 ago... Probably couched in relational database terminology rather than
 branded onto a 2x4 -- something like: if you are creating tables that
 are essentially identical with names based upon some user data; you
 should create one table in which you add a candidate key to hold what
 had been the table name. Then when you need to select records from
 one of the tables you add a ... where keyfield = 'tablename'


Well, Dennis, unlike people like you who have to carry their brains in an
18-wheeler, I don't have a photographic memory and occasionally have to be
told things more than once (or twice, or thrice...)
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-24 Thread Victor Subervi
On Thu, Jun 24, 2010 at 1:56 AM, John Nagle na...@animats.com wrote:

 On 6/23/2010 10:59 PM, Dennis Lee Bieber wrote:

 On Wed, 23 Jun 2010 11:58:24 -0430, Victor Subervi
 victorsube...@gmail.com  declaimed the following in
 gmane.comp.python.general:


  When I have this code:

 


And yes -- it IS an error... You are AGAIN trying to use parameters
 for SCHEMA entities, not data.


Yes.  Please post your CREATE statements, so we can see your
 database schema.  If you really have one table per client, you're
 doing it wrong.


cursor.execute('create table if not exists clients ('client varchar(100),
clientAppelation varchar(10), clientFirst varchar(20), clientLast
varchar(40), clientEmail varchar(60), pw varchar(10)')

TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-24 Thread Victor Subervi
On Thu, Jun 24, 2010 at 9:34 AM, Stephen Hansen me+list/pyt...@ixokai.iowrote:

 On Thu, Jun 24, 2010 at 4:47 AM, Victor Subervi 
 victorsube...@gmail.comwrote:

 On Thu, Jun 24, 2010 at 1:56 AM, John Nagle na...@animats.com wrote:

 Yes.  Please post your CREATE statements, so we can see your
 database schema.  If you really have one table per client, you're
 doing it wrong.


 cursor.execute('create table if not exists clients ('client varchar(100),
 clientAppelation varchar(10), clientFirst varchar(20), clientLast
 varchar(40), clientEmail varchar(60), pw varchar(10)')


 That's only a partial picture: your code later indicated that you have
 tables which are named for client. Like, Lincoln_Properties, or some such.
 That's the problem: you have data which belongs in a field (Lincoln) in the
 table name.

 Basically, instead of:

 Lincoln_Properties
 Memphis_Properties
 Angel_Properties

 And such.

 You should have a single Properties table, which is identical to the
 schema of the above: but with an additional field, client, which is either
 Lincoln or Memphis or whatnot. You may then need to tweak your primary
 keys a bit.

 Then instead of cur.execute('select * from %s', client) which errored out
 -- because you can't use parameterized queries for schema objects (tables,
 fields, etc) -- you would simply change it to cur.execute('select * from
 properties where client = %s', (client,)) -- and it'd work just the same.


Obvious in retrospect. Thanks for cluing me in :))
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Another MySQL Problem

2010-06-23 Thread Victor Subervi
Hi;
I have this line:

  cursor.execute('select clientEmail from clients where client=%s',
(string.replace(client, '_', ' ')))
  clientEmail = cursor.fetchone()[0]
  cursor.execute('select * from %s' % (client))

client = Lincoln_Properties
With the replacement, the interpreter complains that mydatabase.Lincoln
doesn't exist. Therefore, the first line of code isn't putting the %s
replacement in quotes, as I was told by you all it would. So I add quotes to
it and the interpreter complains on the second line of code that it's
unsubscriptable (because it's None). What gives?
TIA
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-23 Thread Victor Subervi
On Wed, Jun 23, 2010 at 10:25 AM, Stephen Hansen
me+list/pyt...@ixokai.iowrote:

 On 6/23/10 6:45 AM, Victor Subervi wrote:
  Hi;
  I have this line:
 
cursor.execute('select clientEmail from clients where client=%s',
  (string.replace(client, '_', ' ')))
clientEmail = cursor.fetchone()[0]
cursor.execute('select * from %s' % (client))
 
  client = Lincoln_Properties
  With the replacement, the interpreter complains that mydatabase.Lincoln
  doesn't exist. Therefore, the first line of code isn't putting the %s
  replacement in quotes, as I was told by you all it would. So I add
  quotes to it and the interpreter complains on the second line of code
  that it's unsubscriptable (because it's None). What gives?

 Its very early, so excuse me if I fall asleep in the middle of the
 response.

 First: Don't do 'string.replace(your_string, x, y)' -- that's back in
 the very, very old days before strings themselves had all the nice methods.

 Do, 'client.replace(_,  )' instead.

 Second, you're forgetting a cardinal rule. Always, always, always,
 include the actual tracebacks when reporting errors. Don't summarize them.

 Third, I *think* the problem is-- though I may be wrong here, because
 again, just woke up-- that you're not passing the options as a tuple.

 Consider: (hello) is not a tuple with one item. This is a slight
 'wart' with Python syntax. Parens do not make tuples: *commas* do.
 Therefore, every tuple *must* have a comma. To make a one-item tuple,
 you must do (hello, )


Well making the changes you suggest throws this error:

A problem occurred in a Python script. Here is the sequence of function
calls leading up to the error, in the order they occurred.
 /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py
   67 /body
   68 /html'''
   69
   70 mailSpreadsheet()
   71
mailSpreadsheet = function mailSpreadsheet
 /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py in
mailSpreadsheet()
   34   subject = 'Order From Client'
   35   cursor.execute('select clientEmail from clients where client=%s',
(client.replace('_', ' '),))
   36   clientEmail = cursor.fetchone()[0]
   37   cursor.execute('select * from %s', (client,))
   38   data = cursor.fetchall()
clientEmail = 'jp...@lpc.com', cursor = MySQLdb.cursors.Cursor object,
cursor.fetchone = bound method Cursor.fetchone of MySQLdb.cursors.Cursor
object

TypeError: unsubscriptable object
  args = ('unsubscriptable object',)

Please advise.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-23 Thread Victor Subervi
Ok, let's start all over again. When I have this code:

  cursor.execute('select clientEmail from clients where client=%s',
(client.replace('_', ' '),))
  clientEmail = cursor.fetchone()[0]

I get this error:

 /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py
   67 /body
   68 /html'''
   69
   70 mailSpreadsheet()
   71
mailSpreadsheet = function mailSpreadsheet
 /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py in
mailSpreadsheet()
   34   subject = 'Order From Client'
   35   cursor.execute('select clientEmail from clients where client=%s',
(client.replace('_', ' '),))
   36   clientEmail = cursor.fetchone()[0]
   37   cursor.execute('select * from %s', (client,))
   38   data = cursor.fetchall()
clientEmail = 'jp...@lpc.com', cursor = MySQLdb.cursors.Cursor object,
cursor.fetchone = bound method Cursor.fetchone of MySQLdb.cursors.Cursor
object

TypeError: unsubscriptable object
  args = ('unsubscriptable object',)

When I have this code:

  print 'select clientEmail from clients where client=%s' %
(client.replace('_', ' '),)
  cursor.execute('select clientEmail from clients where client=%s',
(client.replace('_', ' '),))
  clientEmail = cursor.fetchone()[0]

It prints this:


select clientAppelation, clientLast, clientEmail from clients where
client=Lincoln Properties select clientEmail from clients where
client=Lincoln Properties

and throws this error:

Traceback (most recent call last):
  File /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py, line 71,
in ?
mailSpreadsheet()
  File /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py, line 38,
in mailSpreadsheet
cursor.execute('select * from %s', (client,))
  File /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py, line 163, in
execute
self.errorhandler(self, exc, value)
  File /usr/lib64/python2.4/site-packages/MySQLdb/connections.py, line 35,
in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: (1064, You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right syntax to
use near ''Lincoln Properties'' at line 1)

Clearly, the results should not be None. Please advise.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Problem

2010-06-23 Thread Victor Subervi
On Wed, Jun 23, 2010 at 12:51 PM, Stephen Hansen ixo...@ixokai.io wrote:

 The problem is not this line but:


   File /var/www/html/globalsolutionsgroup.vi/mailSpreadsheet.py, line
 38, in mailSpreadsheet
 cursor.execute('select * from %s', (client,))


 This one.


Yes, can't use the comma, must use the percent. Will be the death of me.
Thanks,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If Not CGI...

2010-06-21 Thread Victor Subervi
I really can't begin to thank you guys enough. Great information, goes
without saying. A lot to consider. I would like to explore rewriting the
shopping cart in Django. The reality of the matter may make it difficult.
Working literally from the time I awake to when I go to sleep and not having
enough hours to complete everything I set for myself makes it difficult, to
say the least, although I love what I do. (My main work is in the arts, not
programming. That just pays the bills.) Again, thank you all so much, and I
will explore and consider my options.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: If Not CGI...

2010-06-21 Thread Victor Subervi
On Mon, Jun 21, 2010 at 9:03 AM, Tim Chase python.l...@tim.thechases.comwrote:

 On 06/21/2010 07:40 AM, Victor Subervi wrote:

 I would like to explore rewriting the shopping cart in Django.
 The reality of the matter may make it difficult. Working
 literally from the time I awake to when I go to sleep and not
 having enough hours to complete everything I set for myself
 makes it difficult,


 The reason for using a framework is because web development is hard work --
 the creators of these frameworks have gone before you doing much of the hard
 work so you can concentrate on your domain-specific tasks instead of the
 infrastructure.

 When you want to drive across the country, do you begin by procuring all
 the land in between and then paving your roads? No...you leave that to
 people who do infrastructure full-time (and with lots of experience in this
 area).  You just get in your car and drive to your destination (your
 domain-specific task) and let the professionals deal with the
 infrastructure.  That common infrastructure investment is then shared
 between many users with widely different destinations.

 So you may find that, by switching to a web framework, you actually end up
 *saving* time because you don't need to recreate all the work of building a
 framework.  Given that tens of thousands of development hours (by some very
 smart  very experienced people) have gone into some of the big-name
 frameworks such as Django, those are tens-of-thousands of hours that *you*
 don't have to spend.


I understand. Thank you.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


If Not CGI...

2010-06-19 Thread Victor Subervi
Hi;
I've caught a lot of flack (imagine that) about using CGI. I understand
there are several other options, to wit: mod_python, fastcgi and wcgi. I've
messed around with mod_python without luck. What are your suggestions?
TIA.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deformed Form

2010-06-16 Thread Victor Subervi
Stephen Hansen suggests running this line before running or testing code:

python -m compileall -f .

Noted. Will do.

Stephen also mentions, along with many others, that using CGI these days is
silly (my word). Noted. I'll switch over, but not today. Got other things
more pressing ;)


DavidA corrects me:

 Since you didn't name your modules (what you persist in calling scripts),
 I can only guess their names from the import statements:
 e.g.:
from New_Passengers_Curr_Customers import New_Passengers_Curr_Customers

I don't see any case difference there.

Right. Gotcha. Started that because I saw others doing it. A bad habit? The
file (in this case) New_Passengers_Curr_Customers.py has only one method, to
wit, New_Passengers_Curr_Customers(). Not a good idea? Please clarify and if
not, why.
Thanks all,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deformed Form

2010-06-16 Thread Victor Subervi
On Wed, Jun 16, 2010 at 2:09 PM, Dave Angel da...@ieee.org wrote:

 Fix any one of them, and I'd probably have kept quiet.


Thanks for piping up ;)
beno



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deformed Form

2010-06-12 Thread Victor Subervi
Stephen Hansen suggests I move the line:
  new_passengers_curr_customers =
int(form.getfirst('new_passengers_curr_customers', 0))
from Script 3 (as he dubs it) to Script 2. Naturally (though he wouldn't
have known) that's how I had it at first. After sending the post that
finally cleared up the confusion, I realized I should have addressed that
question therein (my bad). So here is the tail end of Script 2 with said
change:

  new_passengers_curr_customers =
int(form.getfirst('new_passengers_curr_customers', 0))
  print new_passengers_curr_customers
  new_passengers_curr_customers = New_Passengers_Curr_Customers(customers,
flights)
  if new_passengers_curr_customers  0:
print input type='submit' value=' Send ' /
  print '/body\n/html'
  cursor.close()

create_edit_passengers3()

You will note those very first lines. This also addresses two other
responders who believed perhaps I had called the variable from the form in
question more than once and that it had been used up/consummed in the
first call. Here, the first call is the first line in Script 2 and it
prints the value 0, when the value gathered in the very next line from the
call to Script 3 is 2, not 0.

With respect to Stephens playful jibe about my absurdly long [variable]
names, they're long because they're descriptive, and other posters not so
playfully jibed me about my absurdly short nondescriptive names. Hey, could
you guys coordinate your jibes so you're all on the same page? ;/

DaveA suggested I not use the same name for my fn. as I do for my var;
however, there is a difference in capitalization, and I'm trying to
standardize this way. It makes it easy to recognize the difference (caps)
and easy to recognize which vars go with which fns.

DaveA also says:

 I'd suggest you do all your form interaction from a single script, and
pass any needed data explicitly to functions in the other modules, rather
than having them try to look it up themselves.

Well, yeah, that's what started this post! I'm trying to keep them all in
Script 2.

Stephen also says:

 Yeah, those exact terminology issues tripped me up very hard in
 understanding what was going on.

Yeah, it's hard for me to keep all the terminology straight, frankly. Easy
for you guys, apparently. Sorry.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deformed Form

2010-06-12 Thread Victor Subervi
On Sat, Jun 12, 2010 at 11:46 AM, Stephen Hansen
me+list/pyt...@ixokai.iowrote:

 On 6/12/10 6:19 AM, Victor Subervi wrote:
  You will note those very first lines. This also addresses two other
  responders who believed perhaps I had called the variable from the form
 in
  question more than once and that it had been used up/consummed in the
  first call. Here, the first call is the first line in Script 2 and it
  prints the value 0, when the value gathered in the very next line from
 the
  call to Script 3 is 2, not 0.

 Assuming:

  -- You have only one form construction reading the FieldStorage in
 any module around that's imported or loaded,
  -- That the New_Passengers_Whatever_Other module has no top-level code
 which executes as a side-effect that may be changing things
  -- And that between the 'def New_Passengers_Whatever_Other' and the
 form, then the call to get the value from the FieldStorage, you are not
 doing any other actions which may be messing with stuff, then--

 I call bullshit :)


Yeah, well that's about how I feel, too. I mean, this is hardly the first
time I've used a form like this...I might not be the sharpest programmer,
but I think I know how to use this particular tool. And I've never had this
problem before. I remember when I was working with server farms who shall
remain nameless, it finally dawned on me that it wasn't my programming, but
their crappy hardware that was breaking my code. Perhaps something like that
is going on with this problem.


 You're doing something that you're not telling us. There's something
 else going on. There's no way that form.getfirst() being in another file
 will in and of itself (notwithstanding possibilities of the second
 invocation actually not working at all due to reading the input) return
 different results.


I'm not hiding aces up my sleeve to make you all lose sleep.Honestly.


  With respect to Stephens playful jibe about my absurdly long [variable]
  names, they're long because they're descriptive, and other posters not
 so
  playfully jibed me about my absurdly short nondescriptive names. Hey,
 could
  you guys coordinate your jibes so you're all on the same page? ;/

 Its a question of balance. Using a lot of extremely small nondescriptive
 names is bad. Using a bunch of really long ones is just as bad.

 Seek the middle of the road.


Yeah, well with copy and paste, the middle of the road might not be that far
from absurdly long variables. :) What's lost with long vars? Nothing but
typing time, really. Short vars that aren't descriptive are problematic for
far greater reasons.
TIA,
beno


 --

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deformed Form

2010-06-12 Thread Victor Subervi
On Sat, Jun 12, 2010 at 1:58 PM, Stephen Hansen me+list/pyt...@ixokai.iowrote:

 The only suggestion I have is: try dumping all the .pyc's.


Interestingly,
ls -al
reveals *no* *.pyc files.

Yeah, that problem caught me once as well.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deformed Form

2010-06-11 Thread Victor Subervi
On Thu, Jun 10, 2010 at 2:07 PM, Stephen Hansen me+list/pyt...@ixokai.iowrote:

 On 6/10/10 10:48 AM, Victor Subervi wrote:
  Now, create_edit_passengers3() is called by the form/submit button in
 (you
  guessed it) create_edit_passengers2.py, the latter containing a var in it
  which *should* be accessible to create_edit_passengers3.py, one would
 think.

 Wait, wait, wait.

 If a user is browsing to, say,
 http://example.com/create_edit_passengers2.py; that script will be run,
 and once -done-, print out a form which the user sees.

 At that point, create_edit_passengers2.py is dead. Gone. Over.

 Once a person then clicks Submit, and the form is sent to
 http://example.com/create_edit_passengers3.py; its a whole new
 environment (assuming you're using CGI, which it appears you are).

 The *only* way for state or data to get from one script to another is
 not importing, or shared variables, or anything like that: you *have* to
 pass it into that form, and extract it from the resulting form. You can
 pass the actual variables as a input type=hidden, and then extract
 it like any of the user-fields. Or, you can write out your state to a
 local file with some unique ID, and just write out into the form that
 unique ID. Or use a cookie session. Etc.

 You *can't* pass variables around script-to-script among separate CGI
 sessions. It just totally doesn't work like that. Any success you think
 you have had is false; it works by mere accident or illusion. Each CGI
 script stands alone. It starts, runs, executes, then closes. No state is
 preserved unless you *explicitly* preserve it.


You know, if this were the first time I'd worked with passing variables
around through cgi, I'd think you may be right. But answer me this: if what
you assume is correct, how in the heck is this variable being generated (and
it is) in 
create_edit_passengers2.pyhttp://example.com/create_edit_passengers2.py(as
an input type=text...) and then being reinstantiated in another
script? That is, if what you say is true, I should not be able to access it
through ANY script whatsoever after
create_edit_passengers2.pyhttp://example.com/create_edit_passengers2.pyis
dead, right??? Look closely:

1) variable value generated is
create_edit_passengers2.pyhttp://example.com/create_edit_passengers2.py
2) 
create_edit_passengers2.pyhttp://example.com/create_edit_passengers2.pycalls
create_edit_passengers3.py
http://example.com/create_edit_passengers2.pyvia a form... and
passes the value of the var thereunto.
3) theoretically! Yet for some reason I can't call it in
create_edit_passengers3.py
http://example.com/create_edit_passengers2.pybut *can* call it in a
script that is imported by
create_edit_passengers3.py http://example.com/create_edit_passengers2.py

Now you guys can make fun of me all you want, but until you actually READ
and UNDERSTAND what I'm writing, I'm afraid I think your criticisms are
ridiculous and make you look like fools. For those who don't criticize me
and are trying to help but misunderstand, hey, what can I say, who
misunderstand so much myself lol.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deformed Form

2010-06-11 Thread Victor Subervi
On Fri, Jun 11, 2010 at 12:24 PM, Stephen Hansen
me+list/pyt...@ixokai.iowrote:

 Sure, if you have some file that two separate scripts import, and in
 said file you generate some value-- as long as that value will be the
 same at all times, it'll appear that the two scripts are sharing some
 state. They are not, however. The two scripts can not communicate.


I'm glad you have lots of experience and I respect that. However, I did not
say that two separate scripts import said file. To repeat:

1) variable value generated is
create_edit_passengers2.pyhttp://example.com/create_edit_passengers2.py
2) 
create_edit_passengers2.pyhttp://example.com/create_edit_passengers2.pycalls
create_edit_passengers3.py
http://example.com/create_edit_passengers2.pyvia a form... and
passes the value of the var thereunto.
3) theoretically! Yet for some reason I can't call it in
create_edit_passengers3.py
http://example.com/create_edit_passengers2.pybut *can* call it in a
script that is imported by
create_edit_passengers3.py http://example.com/create_edit_passengers2.py

I think I'm being clear here, am I not? With all your knowledge and
understanding, I still fail to understand how it is you don't understand and
cannot answer my question.


  Now you guys can make fun of me all you want, but until you actually READ
  and UNDERSTAND what I'm writing, I'm afraid I think your criticisms are
  ridiculous and make you look like fools.

 And this comment ends my attempt at assisting you, for multiple reasons
 (from the utter absurdity of you insisting we understand you when you
 take insultingly little care to actually express your problems clearly,
 to your arrogant and repeated refusal to take advice that is given, to
 your abject rudeness here, and so on).


That comment was not addressed to you as you didn't bother to quote the
other part just after it, where I stated I appreciate your help and
understand how difficult it is to not misunderstand each other. Sorry you
misunderstood. I am not being arrogant or rude.

My scripts work. I guess I can just let them work and not bother
understanding *why* they work the way they do and not the way they *should*;
however, if anyone would like to explain, using the 3 steps above, where the
problem is, that would be nice.
Sincerely,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deformed Form

2010-06-11 Thread Victor Subervi
Ok. Starting over. Here is the script that generates the variable
new_passengers_curr_customers:

#!/usr/bin/python

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

def create_edit_passengers():
  print Content-Type: text/html
  print
  print '''
!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Frameset//EN 
http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd;
head xmlns=http://www.w3.org/1999/xhtml;
/head
body
'''
  user, passwd, db, host = login()
  database = MySQLdb.connect(host, user, passwd, db)
  cursor = database.cursor()
  form = cgi.FieldStorage()
  flight = form.getfirst('flight')
  try:
cursor.execute('select c.id, p.name, p.weight, c.first_name,
c.middle_name, c.last_name, c.suffix from Passengers p join Customers c
where p.flights_id=%s;', flight)
passengers = cursor.fetchall()
  except MySQLdb.ProgrammingError:
passengers = []
  cursor.execute('select * from Flights where id=%s;', flight)
  flight_data = cursor.fetchone()
  print bYou have selected flight #%s, departing %s from %s and arriving
%s at %s./bbr /br / % (flight_data[0], flight_data[2],
flight_data[5], flight_data[3], flight_data[6])
  if len(passengers)  0:
print 'form method=post action=create_edit_passengers3.py\n'
Curr_Passengers_Table(passengers)
print h2Add Passengers/h2
  else:
print There are currently no passengers enrolled in this flight. Please
enter some.
print 'form method=post action=create_edit_passengers3.py\n'

*** RIGHT HERE! ***

  print input type='text' size='2' maxlength='2'
name='new_passengers_curr_customers' /br /
 ^
*** SEE IT? ***

  print input type='submit' value=' Send ' /
  print '/body\n/html'
  cursor.close()

create_edit_passengers()



Now, here's the form that *should* be able to access that variable:

!/usr/bin/python

import cgitb; cgitb.enable()
import cgi
import sys,os
sys.path.append(os.getcwd())
import MySQLdb
from login import login
import fpformat
from New_Passengers_Curr_Customers import New_Passengers_Curr_Customers
from New_Passengers_Addl_Customers import New_Passengers_Addl_Customers
from New_Passenger import New_Passenger

form = cgi.FieldStorage()

def sortedDictValues(adict):
  items = adict.items()
  items.sort()
  return [value for key, value in items]

def create_edit_passengers3():
  print Content-Type: text/html
  print
  print '''
!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Frameset//EN 
http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd;
head xmlns=http://www.w3.org/1999/xhtml;
/head
body
'''
  user, passwd, db, host = login()
  database = MySQLdb.connect(host, user, passwd, db)
  cursor = database.cursor()
  cursor.execute('select id from Flights;')
  flights = [itm[0] for itm in cursor]
  cursor.execute('select id, first_name, middle_name, last_name, suffix from
Customers;')
  customers = cursor.fetchall()
  try:
cursor.execute('select p.id, c.first_name, c.middle_name, c.last_name,
c.suffix, c.discount, p.flights_id, p.name, f.price, c.id from Customers c
join Passengers p on c.id=p.customer_id join Flights f on p.flights_id=f.id
;')
passengers = cursor.fetchall()
print 'form method=post action=create_edit_passengers4.py\n'
start_html = table border='2'\n  tr\n
tdbDelete?/b/td\ntdbFlight/b/td\n
tdbName/b/td\ntdbDiscount/b/td\n
tdbPrice/b/td\n  /tr\n
passengers_html = []
ids = []
i = 0
for passenger in passengers:
  do_delete = form.getfirst('%s:delete' % passenger[0])
  passengers_html, i = New_Passenger(passengers_html, passenger,
do_delete, flights, ids, i)
printHTML = sortedDictValues(dict(zip(ids, passengers_html)))
if len(printHTML)  0:
  print start_html
for html in printHTML:
  print html
print /table
  except MySQLdb.ProgrammingError:
pass

*** NOTE THIS: 
  new_passengers_curr_customers = New_Passengers_Curr_Customers(customers,
flights)
*** THAT LINE 

  if new_passengers_curr_customers  0:
print input type='submit' value=' Send ' /
  print '/body\n/html'
  cursor.close()

create_edit_passengers3()


See that line that I marked right at the end? So here's that script:

#!/usr/bin/python

import cgitb; cgitb.enable()
import cgi

form = cgi.FieldStorage()

def New_Passengers_Curr_Customers(customers, flights):

*** RIGHT HERE. SEE THIS LINE? WHY DOES IT WORK HERE AND NOT IN THE 2ND
SCRIPT IN THIS HERE EMAIL WHERE IT SHOULD WORK???***
  new_passengers_curr_customers =
int(form.getfirst('new_passengers_curr_customers', 0))
*** THAT LINE ABOVE. RIGHT ABOVE HERE. OK?? ***

  print input type='hidden' name='new_passengers_curr_customers'
value='%d' / % new_passengers_curr_customers
  if new_passengers_curr_customers  0:
print table border='1'\n
print   tr\ntd colspan='2' align='center'bFrom Current
Customers/b/td\n  /tr
print   tr\n

Deformed Form

2010-06-10 Thread Victor Subervi
Hi;
I have a script that calls values from the form that calls it. This script
imports another script:

from New_Passenger import New_Passenger

def create_edit_passengers3():
  ...
  new_passengers_curr_customers = New_Passengers_Curr_Customers(customers,
flights)
  if new_passengers_curr_customers  0:
print input type='submit' value=' Send ' /

All this works. What puzzles me, however, is that the value of
new_passengers_curr_customers has to be called using cgi from the imported
script (New_Passenger). It cannot be called from the calling script. I would
have thought it would have been the other way around. Please help me
understand why.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deformed Form

2010-06-10 Thread Victor Subervi
On Thu, Jun 10, 2010 at 10:30 AM, Stephen Hansen (L/P) me+list/
pyt...@ixokai.io wrote:

 On 6/10/10 7:14 AM, Victor Subervi wrote:
  Hi;
  I have a script that calls values from the form that calls it. This
 script
  imports another script:
 
  from New_Passenger import New_Passenger
 
  def create_edit_passengers3():
...
new_passengers_curr_customers =
 New_Passengers_Curr_Customers(customers,
  flights)
if new_passengers_curr_customers  0:
  print input type='submit' value=' Send ' /
 
  All this works. What puzzles me, however, is that the value of
  new_passengers_curr_customers has to be called using cgi from the
 imported
  script (New_Passenger). It cannot be called from the calling script. I
 would
  have thought it would have been the other way around. Please help me
  understand why.

 I can't quite figure out what you're asking.
 new_passengers_curr_customers is a variable local to
 create_edit_passengers3;


correct


 you have something that differs only in case
 called New_Passengers_Curr_Customers which -- I assume is defined,
 somewhere.


correct


 Then you haev New_Passenger, and I'm not sure I see what it
 has to do with anything.


My bad. This is another script that is called by the script I have partially
quoted here (main script). It is in that script that I am able to access
the variable in question (as cited by you below).


 But what does cannot be called mean? Cannot usually means an error
 happened -- in which case you shouldn't really even mention it unless
 you're gonna back it up with a traceback.


That is correct. It throws an error if I try and access the variable from
the main script, because I try and use the value of that variable and for
some reason I can't retrieve it.


 The former is a value, you don't call it. You access it. And it being
 local, you can surely only access it within that function (unless you
 pass it somewhere). The latter is -- a class? A function?


fn, a script. I hope that cleared things up. Please advise.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deformed Form

2010-06-10 Thread Victor Subervi
No, I think you've misunderstood because while I thought I was being clear I
probably was not. So here is the complete code of
create_edit_passengers3.py:

#!/usr/bin/python

import cgitb; cgitb.enable()
import cgi
import sys,os
sys.path.append(os.getcwd())
import MySQLdb
from login import login
import fpformat
from New_Passengers_Curr_Customers import New_Passengers_Curr_Customers
from New_Passengers_Addl_Customers import New_Passengers_Addl_Customers
from New_Passenger import New_Passenger

form = cgi.FieldStorage()

def sortedDictValues(adict):
  items = adict.items()
  items.sort()
  return [value for key, value in items]

def create_edit_passengers3():
  print Content-Type: text/html
  print
  print '''
!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Frameset//EN 
http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd;
head xmlns=http://www.w3.org/1999/xhtml;
/head
body
'''
  user, passwd, db, host = login()
  database = MySQLdb.connect(host, user, passwd, db)
  cursor = database.cursor()
  cursor.execute('select id from Flights;')
  flights = [itm[0] for itm in cursor]
  cursor.execute('select id, first_name, middle_name, last_name, suffix from
Customers;')
  customers = cursor.fetchall()
  try:
cursor.execute('select p.id, c.first_name, c.middle_name, c.last_name,
c.suffix, c.discount, p.flights_id, p.name, f.price, c.id from Customers c
join Passengers p on c.id=p.customer_id join Flights f on p.flights_id=f.id
;')
passengers = cursor.fetchall()
print 'form method=post action=create_edit_passengers4.py\n'
start_html = table border='2'\n  tr\n
tdbDelete?/b/td\ntdbFlight/b/td\n
tdbName/b/td\ntdbDiscount/b/td\n
tdbPrice/b/td\n  /tr\n
passengers_html = []
ids = []
i = 0
for passenger in passengers:
  do_delete = form.getfirst('%s:delete' % passenger[0])
  New_Passenger(passenger, do_delete)
printHTML = sortedDictValues(dict(zip(ids, passengers_html)))
if len(printHTML)  0:
  print start_html
for html in printHTML:
  print html
print /table
  except MySQLdb.ProgrammingError:
pass
  New_Passengers_Curr_Customers(customers, flights,
new_passengers_curr_customers)
  new_passengers_addl_customers =
int(form.getfirst('new_passengers_addl_customers', 0))
  New_Passengers_Addl_Customers(customers, flights,
new_passengers_addl_customers)
  if (new_passengers_addl_customers  0) or (new_passengers_curr_customers 
0):
print input type='submit' value=' Send ' /
  print '/body\n/html'
  cursor.close()

create_edit_passengers3()



Now, create_edit_passengers3() is called by the form/submit button in (you
guessed it) create_edit_passengers2.py, the latter containing a var in it
which *should* be accessible to create_edit_passengers3.py, one would think.
*However*, if I put the following line in create_edit_passengers3.py (even
in the beginning outside the fn of the same name):

  new_passengers_curr_customers =
int(form.getfirst('new_passengers_curr_customers', 0))

the value will *always* be 0. *However*, if I put that *same_line* of code
in New_Passengers.py (and fn of same name). it will give me the correct
value, which I can then pass back to the calling script
(create_edit_passengers3.py). Can you explain to me why it would behave like
that? I've never had a problem like this before and I've worked with
accessing variables by this manner in many a script.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


capitalize() NOT the same as var[0].upper _ var[1:]

2010-06-08 Thread Victor Subervi
Sorry, Dennis:

var = 'colorsShort'
var[0].upper + var[1:] = 'ColorsShort'
var.capitalize() = 'Colorsshort'

beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where's the List?

2010-06-06 Thread Victor Subervi
On Sat, Jun 5, 2010 at 4:52 PM, Stephen Hansen apt.shan...@gmail.comwrote:


 cur.execute(sql, [pkg, prodid, tmpTable, quantity] +
 list(option_values))

 Or:

cur.execute(sql, (pkg, prodid, tmpTable, quantity) + option_values)

 I removed the explicit conversion-to-tuple in the first, because... you
 don't need to. Execute takes a sequence. It doesn't have to be a tuple. A
 list is fine. In the second one, I just build my first arguments as a tuple
 instead of as a list, and then add option_values to it... You'll just have
 to go up top and do:

 option_values = ()

 In both places where you currently use []. As you can't add a list to a
 tuple anymore then a tuple to a list, for the same reasons.


Thanks. I always get tripped up on lists and tuples. In fact, just now I
decided to look up the difference again, it's so slight. At any rate, I
deliberately checked my variables using isinstance() and they all checked
out as tuples, so that's why I couldn't figure out where the list was!
Thanks again,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Drop Table w/ MySQLdb?

2010-06-06 Thread Victor Subervi
Hi;
I tried this:

cursor.execute('drop table tmp%s', tmpTable)

and got this error:

Traceback (most recent call last):
  File /var/www/html/angrynates.com/cart/cart.py, line 196, in ?
cart()
  File /var/www/html/angrynates.com/cart/cart.py, line 189, in cart
cursor.execute('drop table tmp%s', tmpTable)
  File /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py, line 163, in
execute
self.errorhandler(self, exc, value)
  File /usr/lib64/python2.4/site-packages/MySQLdb/connections.py, line 35,
in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: (1064, You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right syntax to
use near ''127541158007'' at line 1)

But when I print that statement out (exchanging the comma for a %) and
manually enter it:

mysql drop table tmp127541158007;
Query OK, 0 rows affected (0.00 sec)

I am able to successfully drop the table. Why?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Drop Table w/ MySQLdb?

2010-06-06 Thread Victor Subervi
On Sun, Jun 6, 2010 at 11:40 AM, MRAB pyt...@mrabarnett.plus.com wrote:

  As has been explained already, SQL might not (and here it clearly does
 not) let you use placeholders for table or column names, only for
 values.


Oops. Sorry. Thanks.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Question

2010-06-05 Thread Victor Subervi
On Thu, Jun 3, 2010 at 4:09 PM, John Nagle na...@animats.com wrote:

   The real problem with this is not the Python.  It's the approach
 to SQL.  What's going on here is that you have some collection of
 named options that come in from some external source, and you're
 trying to handle that by dynamically constructing the table schema.

   It would be easier to store the option values in a separate
 table, with something like

CREATE TABLE temp01 (
entryid BIGINT NOT NULL AUTO_INCREMENT UNIQUE PRIMARY KEY,
Store VARCHAR(40) NOT NULL,
PatientID VARCHAR(40) NOT NULL,
ProdID VARCHAR(40) NOT NULL,
Pkg VARCHAR(10) NOT NULL)
ENGINE=INNODB;

CREATE TABLE ouroptions (
FOREIGN KEY (parententry) REFERENCES temp01(entryid)
ON DELETE CASCADE,
optionname VARCHAR(40) NOT NULL,
optionvalue VARCHAR(40) NOT NULL)
ENGINE=INNODB;

   This creates two tables which are locked together.  For any entry
 in temp01, you can create any option entries you need in ouroptions.
 If you delete the entry in temp01, the related options entries will go
 away.
 (That's what ON DELETE CASCADE does.) When inserting, insert the record in
 temp01 first, then the recrods in ouroptions, in a single transaction.

   Incidentally, if you don't specify some indices, lookups will
 take a very long time.


Your solution is very elegant; however, the application here is
inappropriate. I'd been contemplating creating a temp table like you
suggest, but in this application, there is only need for one table. However,
you've given me an idea that will no doubt come in helpful in the future ;)
Thanks,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Where's the List?

2010-06-05 Thread Victor Subervi
Hi;
I have this:

for order in order_details:
  store = order[0]
  prodid = order[1]
  pkg = order[2]
  quantity = order[3]
  if 'PatientID' in order_fields:
patientID = order[4]
try:
  option_values = order[5:]
except TypeError:
  option_values = []
sql = 'insert into orders%s values (Null, %s)' % (store, ,
.join(%s * (4 + len(option_values
cursor.execute(sql, tuple([pkg, prodid, tmpTable, quantity] +
option_values))
  else:
patientID =  ''
try:
  option_values = order[4:]
except TypeError:
  option_values = []
sql = 'insert into orders%s values (Null, %s)' % (store, ,
.join(%s * (4 + len(option_values
#cursor.execute(sql, tuple([pkg, prodid, tmpTable, quantity,
order[4], order[5]]))
cursor.execute(sql, tuple([pkg, prodid, tmpTable, quantity] +
option_values))

It throws this error:

*TypeError*: can only concatenate list (not tuple) to list
  args = ('can only concatenate list (not tuple) to list',)

Where's the list? They're both tuples in that last line of code.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Another MySQL Question

2010-06-03 Thread Victor Subervi
Hi;
I have this code:

options = ''
our_options = []
our_options_string = ''
for op in ops:
  options += '%s varchar(40) not null, ' % (op[0].upper() + op[1:])
  our_options.append('%s' % form.getfirst('%s' % op))
  our_options_string += '%s, ' % op
cursor.execute('''create table if not exists tmp%s (
Store varchar(40) not null,
PatientID varchar(40) not null,
ProdID varchar(40) not null,
Pkg varchar(10) not null,
%s)''' % (tmpTable, options[:-2]))
sql_string = 'insert into tmp%s values (%s, %s, %s, %s, %s)' %
(tmpTable, store, patientID, prodid, pkg, our_options_string[:-4])
print sql_string
sql = 'insert into tmp%s values (%s, %s, %s, %s, %%s)' % (tmpTable,
store, patientID, prodid, pkg)
cursor.execute(sql, (our_options,))

Now, I can insert that printed string, but my execute throws this error:


Traceback (most recent call last):
  File /var/www/html/angrynates.com/cart/insertOrder.py, line 235, in ?
insertOrder()
  File /var/www/html/angrynates.com/cart/insertOrder.py, line 228, in
insertOrder
cursor.execute(sql, (our_options,))
  File /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py, line 163, in
execute
self.errorhandler(self, exc, value)
  File /usr/lib64/python2.4/site-packages/MySQLdb/connections.py, line 35,
in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1136, Column count doesn't match value count at row 1)

So it appears to me that it's saying there's only one value packed in
our_options; however, there are in fact two. Please advise.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Question

2010-06-03 Thread Victor Subervi
On Thu, Jun 3, 2010 at 12:25 PM, MRAB pyt...@mrabarnett.plus.com wrote:

  So our_options is a list containing two values, which you're putting
 into a tuple:

  our_options = [first, second]
  print len(our_options)
 2
  value_tuple = (our_options,)
  print len(value_tuple)
 1
 

 In other words, value_tuple is a tuple which contains one value, a list.


Understood. So I tried this (to include the other values):

  sql_string = 'insert into tmp%s values (%s, %s, %s, %s)' %
(tmpTable, store, prodid, pkg, our_options_string[:-4])
  sql = 'insert into tmp%s values (%%s, %%s, %%s, %%s)' % tmpTable
cursor.execute(sql, (store, prodid, pkg, our_options))

Which, of course, gives me the same error, because I'm still putting in the
same len for the final value. What do now?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another MySQL Question

2010-06-03 Thread Victor Subervi
On Thu, Jun 3, 2010 at 1:48 PM, Dennis Lee Bieber wlfr...@ix.netcom.comwrote:

 On Thu, 3 Jun 2010 08:49:44 -0400, Victor Subervi
 victorsube...@gmail.com declaimed the following in
 gmane.comp.python.general:

options += '%s varchar(40) not null, ' % (op[0].upper() + op[1:])

 Please modernize... Python supports a .capitalize() method for
 strings (I haven't checked the references but I'm pretty sure that's
 been there since 2.3 at least)

  s = this is a mess
  s.capitalize()
 'This is a mess'
 


Thanks. Didn't know about that!!


sql = insert into tmp%s values (%s) % (tmpTable,

, .join(%s *

(4 + len(our_options)))
cursor.execute(sql, tuple([store, patientID, prodid, pkg]
+ our_options))


A minor tweak of this worked nicely. Thanks again! And thanks to MRAB, too!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Opinion On Best Way...

2010-06-02 Thread Victor Subervi
Hi;
I have a script in which I currently pass a number of variables to another
script through the url in a meta http-equiv tag. This seems both awkward and
hackable. I think it would be best to create a temporary mysql table, insert
them there, and pull them from the following script. The situation is where
a purchaser places an item in my shopping cart. A script is called that
simply pushes the data to the cart script. The reason for this step is to
ensure that when the cart script calls itself (in the form tag) through an
update to either update or delete items, the last cached items aren't
re-added to the shopping cart. What are your thoughts on the best way to
preserve the data from script to script?
TIA.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another MySQL Problem

2010-05-28 Thread Victor Subervi
On Thu, May 27, 2010 at 5:47 PM, Tim Chase python.l...@tim.thechases.comwrote:

 On 05/27/2010 03:32 PM, Victor Subervi wrote:

  On Thu, May 27, 2010 at 1:15 PM, Tim Chase wrote:

 That should be:

 ', '.join(['%s'] * len(values)))


 Or as I've done in the past:

  ', '.join('%s' for _ in values)


 Huh? Can you describe that underscore to me? Fascinating!


 The underscore is a valid variable-name, idiomatically used for I don't
 care about this, often seen in places like tuple assignment:

  a,_,_,d = some_4_element_tuple

 So in my above case, it could also have been written as

  ', '.join('%s' for value in values)
  ', '.join('%s' for dont_care_about_the_value in values)

 but the _ idiom means I'm iterating over 'values' but I'm not actually
 using the values I get from it


I should have known. Thanks!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some More MySQL

2010-05-28 Thread Victor Subervi
On Fri, May 28, 2010 at 2:17 AM, Dennis Lee Bieber wlfr...@ix.netcom.comwrote:

 On Thu, 27 May 2010 23:22:24 +0100, MRAB pyt...@mrabarnett.plus.com
 declaimed the following in gmane.comp.python.general:

 
  Placeholders which are handled by .execute shouldn't be wrapped in
  quotes, even is the value is a string, because .execute will handle that
  (and any other details) itself.

 Even more internal details -- the MySQLdb placeholder is %s because
 the adapter, internally, converts ALL parameters to strings, applies
 escapes to them, and THEN wraps them with quotes before using Python
 string interpolation to make the query that gets submitted to the
 server.

This is why you can not use, say %d as a placeholder for a numeric
 parameter... MySQLdb will convert that numeric to a string, and then
 Python will choke when it tries to use a %d formatter and is given a
 string value.


 All of your and MRAB's comments were very helpful. However, I don't see how
these two problems are addressed:

  sql = 'select * from options%s where ID=%%s', (opTable[0].upper() +
opTable[1:])
#  cursor.execute(sql, id)
  cursor.execute('select * from options%s where ID=%s' %
(opTable[0].upper() + opTable[1:], id))

The last one works, but if I comment it out and uncomment the middle line,
it doesn't. Same here:

sql = update options%s set PriceDiff='%%s' where Field='%%s' and
ID=%%s and Store='%%s' % (opTable[0].upper() + opTable[1:])
#cursor.execute(sql, (value, opName, id, store))
cursor.execute('update options%s set PriceDiff=%s where Field=%s
and ID=%s and Store=%s' % (opTable[0].upper() + opTable[1:], value,
opName, id, store))

TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some More MySQL

2010-05-28 Thread Victor Subervi
I still have this code:

  sql = 'select * from options%s where ID=%%s', (opTable[0].upper() +
opTable[1:])
  cursor.execute(sql, (id,))

which throws this error:

 /var/www/html/angrynates.com/cart/enterOptionsPrices2.py
   70 print 'All options prices have been successfully updated.'
   71 print '/body\n/html'
   72
   73 enterOptionsPrices2()
   74
enterOptionsPrices2 = function enterOptionsPrices2
 /var/www/html/angrynates.com/cart/enterOptionsPrices2.py in
enterOptionsPrices2()
   58   id = form.getfirst('%sID' % option)
   59   sql = 'select * from options%s where ID=%%s',
(opTable[0].upper() + opTable[1:])
   60   cursor.execute(sql, (id,))
   61 #  cursor.execute('select * from options%s where ID=%s' %
(opTable[0].upper() + opTable[1:], id))
   62   if cursor.fetchone() is not None:
cursor = MySQLdb.cursors.Cursor object, cursor.execute = bound method
Cursor.execute of MySQLdb.cursors.Cursor object, sql = ('select * from
options%s where ID=%%s', 'Sizes'), id = '0.00'
 /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in
execute(self=MySQLdb.cursors.Cursor object, query=('select * from
options%s where ID=%%s', 'Sizes'), args=('0.00',))
  144 db = self._get_db()
  145 charset = db.character_set_name()
  146 query = query.encode(charset)
  147 if args is not None:
  148 query = query % db.literal(args)
query = ('select * from options%s where ID=%%s', 'Sizes'), query.encode
undefined, charset = 'latin1'

AttributeError: 'tuple' object has no attribute 'encode'
  args = ('tuple' object has no attribute 'encode',)


Please advise.
TIA
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
Hi;
I have this code:

sql = insert into %s (%s) values ('%%s'); % (personalDataTable,
string.join(cols[1:], ', '))
#cursor.execute(sql, string.join(vals[1:], ', '))
cursor.execute('insert into %s (%s) values (%s);' %
(personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], ',
')))

Now, if I uncomment the 2nd line and comment the third, the command fails
because, apparently, that '); at the tail end of sql (1st line) gets
chopped off. Why??
TIA,
beno

(Note to self: enterPeople3.py)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 8:34 AM, Victor Subervi victorsube...@gmail.comwrote:

 Hi;
 I have this code:

 sql = insert into %s (%s) values ('%%s'); % (personalDataTable,
 string.join(cols[1:], ', '))
 #cursor.execute(sql, string.join(vals[1:], ', '))
 cursor.execute('insert into %s (%s) values (%s);' %
 (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], ',
 ')))

 Now, if I uncomment the 2nd line and comment the third, the command fails
 because, apparently, that '); at the tail end of sql (1st line) gets
 chopped off. Why??

 (Note to self: enterPeople3.py)


...and here's another one:

print 'insert into categories (Store, Category, Parent) values(%s,
%s, Null)'% (store, cat)
#cursor.execute('insert into categories (Store, Category, Parent)
values(%s, %s, Null)', (store, cat))

If I print out and manually insert, all goes well. If I uncomment the 2nd
line, it inserts store and cat with single quote marks and screws everything
up!

mysql select * from categories;
+++++
| ID | Store  | Category   | Parent |
+++++
|  1 | 'products' | 'prodCat1' | NULL   |
|  2 | 'products' | 'prodCat2' | NULL   |
+++++

as opposed to

mysql select * from categories;
+++++
| ID | Store  | Category   | Parent |
+++++
|  1 | products | prodCat1 | NULL   |
|  2 | products | prodCat2 | NULL   |
+++++

TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 10:17 AM, Kushal Kumaran
kushal.kuma...@gmail.comwrote:

 On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote:
  Hi;
  I have this code:
 
  sql = insert into %s (%s) values ('%%s'); % (personalDataTable,
  string.join(cols[1:], ', '))
  #cursor.execute(sql, string.join(vals[1:], ', '))
  cursor.execute('insert into %s (%s) values (%s);' %
  (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:],
  ', ')))
 
  Now, if I uncomment the 2nd line and comment the third, the command
  fails because, apparently, that '); at the tail end of sql (1st
  line) gets chopped off. Why??

 That's not why it is failing.

 The second argument to cursor.execute must be a tuple of values that
 will be escaped and interpolated into the query.  You are passing in a
 string instead.


So I tried this:

sql = insert into %s (%s) values (%%s); % (personalDataTable,
string.join(cols[1:], ', '))
cursor.execute(sql, vals[1:])

and got this:

A problem occurred in a Python script. Here is the sequence of function
calls leading up to the error, in the order they occurred.
 /var/www/html/angrynates.com/cart/enterPeople3.py
   85   print a href='enterPeople.py?personalDataTable=%s'Enter more
personal data?/abr / % personalDataTable
   86   print a href='enterProducts.py'Enter products?/a
   87   print '/body\n/html'
   88
   89 enterPeople3()
enterPeople3 = function enterPeople3
 /var/www/html/angrynates.com/cart/enterPeople3.py in enterPeople3()
   42 # We will not include the ID column
   43 sql = insert into %s (%s) values (%%s); % (personalDataTable,
string.join(cols[1:], ', '))
   44 cursor.execute(sql, vals[1:])
   45 #cursor.execute(sql, string.join(vals[1:], ', '))
   46 #cursor.execute('insert into %s (%s) values (%s);' %
(personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], ',
')))
cursor = MySQLdb.cursors.Cursor object, cursor.execute = bound method
Cursor.execute of MySQLdb.cursors.Cursor object, sql = 'insert into
doctorsPersonalData (Store, FirstNam...OB, Email, PW, State, ShippingState)
values (%s);', vals = ['Null', 'prescriptions', 'Beno', 'Candelon', '123',
'456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted',
'00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR']
 /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in
execute(self=MySQLdb.cursors.Cursor object, query='insert into
doctorsPersonalData (Store, FirstNam...OB, Email, PW, State, ShippingState)
values (%s);', args=['prescriptions', 'Beno', 'Candelon', '123', '456',
'789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820',
'2000-01-01', 'benoismyname', '12345', 'CA', 'AR'])
  146 query = query.encode(charset)
  147 if args is not None:
  148 query = query % db.literal(args)
  149 try:
  150 r = self._query(query)
query = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email, PW,
State, ShippingState) values (%s);', db = weakproxy at 0x2b4c17e707e0 to
Connection, db.literal = bound method Connection.literal of
_mysql.connection open to 'localhost' at e6b08c0, args =
['prescriptions', 'Beno', 'Candelon', '123', '456', '789', '11 here', '',
'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01',
'benoismyname', '12345', 'CA', 'AR']

TypeError: not all arguments converted during string formatting
  args = ('not all arguments converted during string formatting',)

You sure about not converting to string??


Also, lose the single quotes around the %s.


Well, sure, if not converting to string. Otherwise it's needed. Dennis
advised not using quotes, but what he meant was not using double quotes.
Single quotes, I have found by experimentation, do work.
TIA
beno


 --
 regards,
 kushal



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 12:11 PM, Kushal Kumaran
kushal.kuma...@gmail.comwrote:

 Since I'm in a good mood today, here's a little present:

 def insert(cursor, table, columns, values):
Insert a row into a table.  columns must be a list of column
names.  values must be a list of values for the new row.  The
columns and values must correspond.
assert len(columns) == len(values)

stmt = 
 insert into %s (%s) values (%s)
  % (table,
   ', '.join(columns),
   ', '.join('%s' * len(values)))
logging.debug('stmt: %s, values: %s' % (stmt, values))

cursor.execute(stmt, values)

 Glad you're in a good mood :)
First, I got an error because logging isn't defined. What should I import?
I commented out that line. Here's my original code, which is now commented
out:

##cursor.execute('insert into %s (%s) values (%s);' %
(personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], ',
')))

I ran this with your code:

insert(cursor, personalDataTable, cols[1:], vals[1:])

and got this error:

 /var/www/html/angrynates.com/cart/enterPeople3.py
   97   print a href='enterPeople.py?personalDataTable=%s'Enter more
personal data?/abr / % personalDataTable
   98   print a href='enterProducts.py'Enter products?/a
   99   print '/body\n/html'
  100
  101 enterPeople3()
enterPeople3 = function enterPeople3
 /var/www/html/angrynates.com/cart/enterPeople3.py in enterPeople3()
   51   if whatDo == 'insert':
   52 # We will not include the ID column
   53 insert(cursor, personalDataTable, cols[1:], vals[1:])
   54 #sql = insert into %s (%s) values (%%s); % (personalDataTable,
string.join(cols[1:], ', '))
   55 #cursor.execute(sql, vals[1:])
global insert = function insert, cursor = MySQLdb.cursors.Cursor object,
personalDataTable = 'doctorsPersonalData', cols = ['ID', 'Store',
'FirstName', 'LastName', 'Phone', 'Cell', 'Fax', 'Address1', 'Address2',
'City', 'Zip', 'ShippingAddress1', 'ShippingAddress2', 'ShippingCity',
'ShippingZip', 'DOB', 'Email', 'PW', 'State', 'ShippingState'], vals =
['Null', 'prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11
here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01',
'victorsubervi', '12345', 'DC', 'AK']
 /var/www/html/angrynates.com/cart/enterPeople3.py in
insert(cursor=MySQLdb.cursors.Cursor object, table='doctorsPersonalData',
columns=['Store', 'FirstName', 'LastName', 'Phone', 'Cell', 'Fax',
'Address1', 'Address2', 'City', 'Zip', 'ShippingAddress1',
'ShippingAddress2', 'ShippingCity', 'ShippingZip', 'DOB', 'Email', 'PW',
'State', 'ShippingState'], values=['prescriptions', 'jane', 'shmo',
'321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there',
'', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK'])
   19   ', '.join('%s' * len(values)))
   20 #   logging.debug('stmt: %s, values: %s' % (stmt, values))
   21cursor.execute(stmt, values)
   22
   23 def enterPeople3():
cursor = MySQLdb.cursors.Cursor object, cursor.execute = bound method
Cursor.execute of MySQLdb.cursors.Cursor object, stmt = '\ninsert into
doctorsPersonalData (Store, FirstNa... %, s, %, s, %, s, %, s, %, s, %, s,
%, s, %, s)\n', values = ['prescriptions', 'jane', 'shmo', '321-654-9870',
'456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted',
'00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK']
 /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in
execute(self=MySQLdb.cursors.Cursor object, query='\ninsert into
doctorsPersonalData (Store, FirstNa... %, s, %, s, %, s, %, s, %, s, %, s,
%, s, %, s)\n', args=['prescriptions', 'jane', 'shmo', '321-654-9870',
'456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted',
'00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK'])
  146 query = query.encode(charset)
  147 if args is not None:
  148 query = query % db.literal(args)
  149 try:
  150 r = self._query(query)
query = '\ninsert into doctorsPersonalData (Store, FirstNa... %, s, %, s, %,
s, %, s, %, s, %, s, %, s, %, s)\n', db = weakproxy at 0x2b13d59857e0 to
Connection, db.literal = bound method Connection.literal of
_mysql.connection open to 'localhost' at 132de990, args =
['prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here',
'', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01',
'victorsubervi', '12345', 'DC', 'AK']

ValueError: unsupported format character ',' (0x2c) at index 221
  args = (unsupported format character ',' (0x2c) at index 221,)

It appears to be separating the '%' from the 's' in your assert of '%s', but
since I don't know anything about asserts, I'm hoping you can help me here.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Quick MySQL Question

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 1:37 PM, Dennis Lee Bieber wlfr...@ix.netcom.comwrote:

 On Wed, 26 May 2010 08:29:21 -0400, Victor Subervi
 victorsube...@gmail.com declaimed the following in
 gmane.comp.python.general:

  valueList = (%value1, %value2, %value3)

If I'd coded it correctly, there should have been a % on both sides
 (I didn't actually test the statement, was coding from memory -- might
 have needed to double up the % to escape them)

  cur.execute(select * from table where name1 like %s and name2 like %s
 and
  name3 like %s, (%value1, %value2, %value3))
 
  Why do the values have that extra %?

 Wild card -- match zero or more characters

%value1% will match value1 /anywhere/ in the field name1; useful
 if doing keyword searches on text fields.

To use my card catalog example:

 BOOK(title, author)
 Witch World, Andre Norton
 A Mankind Witch, Dave Freer
 Three Against the Witch World, Andre Norton
 The Jargoon Pard, Andre Norton

 names = [author, title]
 values = [Norton, Witch]

The final SQL statement should become

 select * from BOOK
 where author like %Norton%
and title like %Witch%

 and that statement will find the first and third book listed.


Ok. Now I understand. Thank you!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 12:56 PM, MRAB pyt...@mrabarnett.plus.com wrote:

 Kushal Kumaran wrote:
 [snip]

  Since I'm in a good mood today, here's a little present:

 def insert(cursor, table, columns, values):
Insert a row into a table.  columns must be a list of column
names.  values must be a list of values for the new row.  The
columns and values must correspond.
assert len(columns) == len(values)

stmt = 
 insert into %s (%s) values (%s)
  % (table,
   ', '.join(columns),
   ', '.join('%s' * len(values)))


 That should be:


   ', '.join(['%s'] * len(values)))

 logging.debug('stmt: %s, values: %s' % (stmt, values))

cursor.execute(stmt, values)

 Hope it helps.

 Yes it did. Thanks. Also figured out the import logging :-}
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Some More MySQL

2010-05-27 Thread Victor Subervi
Hi;
But what about this?

  sql = select pic%d from %s where ID='%%s'; % (pic, store)
  cursor.execute(sql % id)

If I try and rewrite the last line like this:

  cursor.execute(sql, id)

it doesn't work. What do?

How about this one:

cursor.execute(insert into categories (Store, Category, Parent)
values('%s', '%s', Null), (store, cat))

For some reason it puts single quotes around my variables! This doesn't
happen if I change that comma for a percent sign! What do?

How about this one:

  sql = 'select * from options%s where ID=%%s', (opTable[0].upper() +
opTable[1:])
#  cursor.execute(sql, id)
  cursor.execute('select * from options%s where ID=%s' %
(opTable[0].upper() + opTable[1:], id))

The last one works, but if I comment it out and uncomment the middle line,
it doesn't. Same here:

sql = update options%s set PriceDiff='%%s' where Field='%%s' and
ID=%%s and Store='%%s' % (opTable[0].upper() + opTable[1:])
#cursor.execute(sql, (value, opName, id, store))
cursor.execute('update options%s set PriceDiff=%s where Field=%s
and ID=%s and Store=%s' % (opTable[0].upper() + opTable[1:], value,
opName, id, store))

Please help.
TIA,
beno

TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some More MySQL

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 2:54 PM, MRAB pyt...@mrabarnett.plus.com wrote:

 Victor Subervi wrote:

 Hi;
 But what about this?

  sql = select pic%d from %s where ID='%%s'; % (pic, store)
  cursor.execute(sql % id)

 If I try and rewrite the last line like this:

  cursor.execute(sql, id)

 it doesn't work. What do?

 How about this one:

cursor.execute(insert into categories (Store, Category, Parent)
 values('%s', '%s', Null), (store, cat))

 For some reason it puts single quotes around my variables! This doesn't
 happen if I change that comma for a percent sign! What do?

 How about this one:

  sql = 'select * from options%s where ID=%%s', (opTable[0].upper() +
 opTable[1:])
 #  cursor.execute(sql, id)
  cursor.execute('select * from options%s where ID=%s' %
 (opTable[0].upper() + opTable[1:], id))

 The last one works, but if I comment it out and uncomment the middle line,
 it doesn't. Same here:

sql = update options%s set PriceDiff='%%s' where Field='%%s' and
 ID=%%s and Store='%%s' % (opTable[0].upper() + opTable[1:])
 #cursor.execute(sql, (value, opName, id, store))
cursor.execute('update options%s set PriceDiff=%s where
 Field=%s and ID=%s and Store=%s' % (opTable[0].upper() + opTable[1:],
 value, opName, id, store))

  As has already been explained, when working with SQL in Python there are
 2 forms of placeholder:

 1. Python's %s placeholder, replaced by Python's % operator.

 2. SQL's %s placeholder, replaced by the .execute method.

 SQL might not let you use its %s placeholder for table or column names,
 but they are normally hidden from the user and fixed by the application.

 For user-supplied values there's the risk of SQL-injection attacks.
 There are 2 ways of approaching that:

 1. The hard way: check the values and add any necessary quoting or
 escaping before using Python's % operator, then pass the fully-formed
 SQL statement to result to .execute.

 2. The easy way: pass the SQL statement to .execute with a %s for each
 value and let the method substitute the values itself (it'll add
 whatever quoting or escaping is necessary).


 Ok, so you're telling me I'm trying to do it the hard way. That's because I
still don't have my head wrapped around the easy way. I was able to follow
what Kushal Kumaran supplied; however I must still be lost on how that
applies to the above examples. Could you illustrate with the first and let
me try and figure out the rest?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 1:15 PM, Tim Chase s...@thechases.com wrote:

 On 05/27/2010 11:56 AM, MRAB wrote:

 Kushal Kumaran wrote:

', '.join('%s' * len(values)))


 That should be:

 ', '.join(['%s'] * len(values)))


 Or as I've done in the past:

  ', '.join('%s' for _ in values)


Huh? Can you describe that underscore to me? Fascinating!
beno




 --
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Quick MySQL Question

2010-05-26 Thread Victor Subervi
On Wed, May 26, 2010 at 2:42 AM, Dennis Lee Bieber wlfr...@ix.netcom.comwrote:

 I was, for that example, assuming that the user input values was
 being used in a select query and hence wrapped it with wildcard markers
 so that the phrase would match anywhere in the data field.


In said thread you wrote the following:

clauses = []
for nm in nameList:
   clauses.append(nm +  like %s)
where =  and .join(clauses)   #could be  or 
valueList = [%%s% % vl for vl in valueList]
SQL = select * from table where  + where
cur.execute(SQL, valueList)

Ok, so let's assume we have a name list of:

[name1, name2, name3]

and a value list of:

[value1, value2, value3]

Therefore:

clauses = [name1 like %s, name2 like %s, name3 like %s]
where = name1 like %s and name2 like %s and name3 like %s
SQL = select * from table where name1 like %s and name2 like %s and name3
like %s
valueList = (%value1, %value2, %value3)
cur.execute(select * from table where name1 like %s and name2 like %s and
name3 like %s, (%value1, %value2, %value3))

Why do the values have that extra %?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another Little MySQL Problem

2010-05-26 Thread Victor Subervi
On Wed, May 26, 2010 at 11:25 AM, Kushal Kumaran
kushal.kuma...@gmail.comwrote:

 On Tue, 2010-05-25 at 14:45 -0400, Victor Subervi wrote:
  Hi;
  I have this code:
 
  clientCursor.execute('select ID from %s' % (personalDataTable))
  upds = [itm[0] for itm in clientCursor]
  print input type='hidden' name='upds' value='%s' / % upds
 
  The problem is that the values passed are 1L, 2L When I retrieve
  them on the other end and try to convert them to integers, guess what
  happens? So how do I get rid of that L?

 You could build a list of ints instead of a list of longs, like this:

 upds = [int(itm[0]) for itm in clientCursor]


Oh, geez. That should have been obvious to me! Thanks!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Quick MySQL Question

2010-05-25 Thread Victor Subervi
On Tue, May 25, 2010 at 3:50 AM, Dennis Lee Bieber wlfr...@ix.netcom.comwrote:

 On Mon, 24 May 2010 13:37:58 -0400, Victor Subervi
 victorsube...@gmail.com declaimed the following in
Parameterized queries process the parameters to ensure that they are
 safe for use in the SQL statement.

In the case of the MySQLdb adapter (written to be compatible with
 pre-version 5 of MySQL) this means that the parameters are converted to
 a string representation (if not already a string), characters in the
 parameter that are significant to the MySQL dialect of SQL are safely
 escaped, AND the resulting string is WRAPPED in quote marks.

 k. That worked. Thanks!


I suggest you study the SQL standard like comparison, and the use
 of wildcards with it. Consider a card catalog application and how one
 would formulate a query in which the author's last name is Norton, and
 the title of the book contains the word Witch (the word could be
 anywhere within the title).


I understand how to do like queries and use wildcards. I didn't understand
what you were doing over there, something with %values% or some such. If you
care to pick up that thread, fine, otherwise, until the next time.

Thanks you as always, Dennis :)
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Another Little MySQL Problem

2010-05-25 Thread Victor Subervi
Hi;
I have this code:

clientCursor.execute('select ID from %s' % (personalDataTable))
upds = [itm[0] for itm in clientCursor]
print input type='hidden' name='upds' value='%s' / % upds

The problem is that the values passed are 1L, 2L When I retrieve them on
the other end and try to convert them to integers, guess what happens? So
how do I get rid of that L?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


A Quick MySQL Question

2010-05-24 Thread Victor Subervi
Hi;
I have the following:

#sql = 'alter table %s alter column %s set default %%s;' % (store,
col)
#cursor.execute(sql, colValue)
cursor.execute('alter table %s alter column %s set default %s;' %
(store, col, colValue))
database.commit()

Now I don't like that third line, so I tried the commented out lines, but I
got an MySQLdb.OperationalError that the suggested default value could not
be inserted. However, when I printed it out and tried to insert directly, no
problem, and the 3rd line works fine. What gives?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another Strange MySQL Problem

2010-05-22 Thread Victor Subervi
On Fri, May 21, 2010 at 2:40 PM, Tim Chase python.l...@tim.thechases.comwrote:

 On 05/21/2010 12:31 PM, Victor Subervi wrote:

 cursor.execute('insert into Baggage values (Null, %s, %s, %s,
 %s)', (flight_id, customer_id, weight, ticket_no))


 You're trying to insert stuff...


  OperationalError: (1452, 'Cannot add or update a child row: a foreign
 key constraint fails (`seaflight/Baggage`, CONSTRAINT `Baggage_ibfk_2`
 FOREIGN KEY (`customer_id`) REFERENCES `Customers` (`id`))')


 But the value you're giving for the customer_id doesn't exist in the
 Customers table (as mandated by the FK).  Or perhaps the column-order for
 Baggage isn't what you think it is.  I always specify it explicitly:

  INSERT INTO Baggage (
   something, flight_id, customer_id, weight, ticket_no
  ) VALUES (Null, %s, %s, %s, %s)

 just in case the table column-order ever changes during a database update.


As it turns out, my error was confusing my tables Customers and Passengers.
I was calling customer_id when I should have been calling passenger_id,
which is why MySQL couldn't find the correct values :-}
beno



-- 
http://mail.python.org/mailman/listinfo/python-list


Just To Be Sure...MySQL

2010-05-22 Thread Victor Subervi
Hi;
A lister recently responded to my post concerning mysl commands of the
following type:

cursor.execute('insert into foo values (%s, %s)' % (bar, something))

stating that I need to eliminate the % to prevent injection attacks, thus:

cursor.execute('insert into foo values (%s, %s)', (bar, something))

My question is simply this: Is that advice good for *all* mysql commands? Or
are there some where the % is necessary and a comma would fail? I need to
update lots of mysql commands. If I can do it without harmful consequences,
I'll do it across the board. Otherwise, I'll have to test each one.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Another Strange MySQL Problem

2010-05-21 Thread Victor Subervi
Hi;
When I try to execute this code from my Python script, I get this error:

Traceback (most recent call last):
  File 
/var/www/html/creative.vi/clients/sea-flight/reservations/create_edit_bags3.py,
line 38, in ?

create_edit_bags3()
  File 
/var/www/html/creative.vi/clients/sea-flight/reservations/create_edit_bags3.py,
line 32, in create_edit_bags3

cursor.execute('insert into Baggage values (Null, %s, %s, %s,
%s)', (flight_id, customer_id, weight, ticket_no))
  File /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py, line
163, in execute

self.errorhandler(self, exc, value)
  File /usr/lib64/python2.4/site-packages/MySQLdb/connections.py,
line 35, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1452, 'Cannot add or update a child row: a foreign
key constraint fails (`seaflight/Baggage`, CONSTRAINT `Baggage_ibfk_2`
FOREIGN KEY (`customer_id`) REFERENCES `Customers` (`id`))')

However, when I try from the MySQL prompt after duly printing it out from
the code, it works. Why?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Strange MySQL Problem

2010-05-20 Thread Victor Subervi
Hi;
I have this code:

#!/usr/bin/python

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

def create_edit_passengers4():
  print Content-Type: text/html
  print
  print '''
!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Frameset//EN 
http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd;
head xmlns=http://www.w3.org/1999/xhtml;
/head
body
'''
  user, passwd, db, host = login()
  database = MySQLdb.connect(host, user, passwd, db)
  cursor = database.cursor()
  form = cgi.FieldStorage()
  cursor.execute('create table if not exists Passengers (id int(11)
auto_increment primary key, flights_id int(11) not null, customer_id int(11)
not null, foreign key (id) references Flights (flights_id), foreign key (id)
references Customers (customer_id), name varchar(40), weight int)
engine=InnoDB;')
  new_passengers = int(form.getfirst('new_passengers'))
  i = 0
  while i  new_passengers:
cursor.execute('insert into Passengers values (Null, %s, %s, %s, %s);'
% (form.getfirst('%d:flight' % i), form.getfirst('%d:customer' % i),
form.getfirst('%d:name' % i, ''), form.getfirst('%d:weight' % i)))
i += 1
  print All passenger information has successfully been added.
  cursor.close()
  print /body\n/html

create_edit_passengers4()

Now, it throws no errors; however, it doesn't insert. If I print out the
insert statement to screen and then manually insert it in MySQL it inserts.
Huh??
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange MySQL Problem

2010-05-20 Thread Victor Subervi
On Thu, May 20, 2010 at 12:56 PM, MRAB pyt...@mrabarnett.plus.com wrote:


 When performing SQL operations, don't insert the values using Python's
 string formatting, because that makes it vulnerable to SQL-injection
 attacks, ie don't do this:

cursor.execute(sql_command % values)

 do this:

cursor.execute(sql_command, values)


Oh, thank you!


 I think you need to 'commit' any changes to do to the database.


Caught by the commit again. Yes, thanks.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tempering Client Expectations (OT)

2010-04-12 Thread Victor Subervi
On Sat, Apr 10, 2010 at 3:14 PM, Tim Chase python.l...@tim.thechases.comwrote:

 1) Preeminently, address second-order ignorance.


Tim, throughout this post, you're way out of line. The s/w I have already
built for this client works just fine. It's not a matter or not having the
tools or not knowing how to use them. Pay attention to my question, don't
make up your own based on your own inaccurate assumptions and answer those,
please. Stick to the topic.

4) Don't be afraid to reuse existing technologies:  could installing
osCommerce on a $3/month web-server and tweaking the PHP code have sufficed
for what you need?  Could you have used Django+Satchmo to get yourself up
and running with proven code, tweaking what you need?  I remember you
dismissing the suggestion to use existing web-frameworks.

sigh
Bringing that up again, are you? I was all but done with the shopping cart
when you suggested I re-invent the wheel based on another technology. Yeah,
sure, throw out 10,000 lines of the 12,000 line program so I can rebuild on
a new technology. Brilliant, that. Thanks for the suggestion. Now, can we
get back to my question?
/sigh


 5) Regarding scope-creep,


Yeah, that's where we should have been all along, Tim.



 it's a problem most developers  analysts face, but there are several
 mitigating methods you can use.  Experience from past projects helps gauge
 time for future projects and only your own experience will suffice.  If you
 don't have any past projects (personal deployments or school projects)
 you're not yet remotely ready to give estimates.  Even after you've done
 multiple projects, estimation is still as much an art as a science.


Obviously.


 Also, get the client to sign off on basic features in very small bite-sized
 increments, addressing highest-priority needs first. If at any time the
 client sees a failure to progress at the rate they expect, they can pull the
 plug losing far less of their investment keeping the most important features
 developed thus-far.  Part of a developer/analyst's job is to get a good idea
 of a project's scope.  Examining all edge cases, looking for
 infrequently-used processes, probing exceptions, building a mental-model
 that corresponds to the client's mental-model...


Now you're talking.


 6) As for Tempering Client Expectations (the subject line of this OT
 post),


Ah, so you *did* recognize what *my* question was! Good!


 it seems the biggest gap involved not communicating to your client/friend
 I'm using your project as a learning experience for multiple complicated
 technologies and I have minimal idea what is involved so there's no possible
 way I could give you an accurate estimate of scope or cost


True. I ended up taking a bath on it, and I believe that was merited since
it was my first client project. Now, I'm dealing with scope-creep and trying
to work my way out of it, and looking ahead at how to avoid complications
like this in the future.
Thanks,
beno




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Refresh Problem

2010-04-12 Thread Victor Subervi
On Sun, Apr 11, 2010 at 4:29 PM, Tim Chase python.l...@tim.thechases.comwrote:

 On 04/11/2010 02:53 PM, MRAB wrote:

 Victor Subervi wrote:

 Hi;
 I send variables to a script. The script adds appropriate lines into a
 database of an order to my shopping cart. When I refresh the screen, as
 no doubt some customers will do, it re-ads those orders. Now, I can
 delete them, but that's not the point. I don't want it to re-ad the
 orders. How do I skirt this problem?

  When you click on the Submit button on the form it should post the data,
 ie use method=post, not method=get. If refreshing causes it to
 re-submit, then you're using the wrong method. This is basic stuff.


 And if you do POST your data (which you should if you're attempting to
 change state on the server), you should use a post/redirect/get pattern[1].
  This will prevent the browser from giving the you've already submitted
 this data; do you want to resubmit it? message that most should give you if
 you refresh a POST'ed page.

 And therein demonstrates the need to know HTTP as mentioned in my previous
 reply to you (VS, not MRAB).


Man, I just forget this stuff. Dunno why. Yeah, just set a var in the URL of
the post. Right. Sorry. Thanks.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Refresh Problem

2010-04-12 Thread Victor Subervi
On Mon, Apr 12, 2010 at 9:03 AM, Victor Subervi victorsube...@gmail.comwrote:

 On Sun, Apr 11, 2010 at 4:29 PM, Tim Chase 
 python.l...@tim.thechases.comwrote:

 On 04/11/2010 02:53 PM, MRAB wrote:

 Victor Subervi wrote:

 Hi;
 I send variables to a script. The script adds appropriate lines into a
 database of an order to my shopping cart. When I refresh the screen, as
 no doubt some customers will do, it re-ads those orders. Now, I can
 delete them, but that's not the point. I don't want it to re-ad the
 orders. How do I skirt this problem?

  When you click on the Submit button on the form it should post the
 data,
 ie use method=post, not method=get. If refreshing causes it to
 re-submit, then you're using the wrong method. This is basic stuff.


 And if you do POST your data (which you should if you're attempting to
 change state on the server), you should use a post/redirect/get pattern[1].
  This will prevent the browser from giving the you've already submitted
 this data; do you want to resubmit it? message that most should give you if
 you refresh a POST'ed page.

 And therein demonstrates the need to know HTTP as mentioned in my previous
 reply to you (VS, not MRAB).


 Man, I just forget this stuff. Dunno why. Yeah, just set a var in the URL
 of the post. Right. Sorry. Thanks.
 beno

 Correction. I was not familiar with Post/Redirect/Get. Thanks, Tim
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tempering Client Expectations (OT)

2010-04-12 Thread Victor Subervi
On Mon, Apr 12, 2010 at 10:29 AM, Tim Chase
python.l...@tim.thechases.comwrote:

 your own inaccurate assumptions and answer those, please.



 Heh, my wife and I joke that in those can this marriage be saved
 newspaper columns, every answer boils down to communication is key.  Keep
 the customer tightly in the loop with regular communication -- frequent
 feedback regarding progress, costs, and whether your shared understanding
 coincides helps prevent developers from wandering off for 6months only to
 come back with 6mo of costs for a project that doesn't meet the client's
 expectations.  The customer may cut you off if progress is too slow or
 costly, but the earlier that happens, the less pain for both parties.


Yeah, that's pretty much where I'm seeing it, too. Parameterize customer
expectations as much as practicable up front so it's less painful down the
road.
Thanks,
beno




-- 
http://mail.python.org/mailman/listinfo/python-list


Refresh Problem

2010-04-11 Thread Victor Subervi
Hi;
I send variables to a script. The script adds appropriate lines into a
database of an order to my shopping cart. When I refresh the screen, as no
doubt some customers will do, it re-ads those orders. Now, I can delete
them, but that's not the point. I don't want it to re-ad the orders. How do
I skirt this problem?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Tempering Client Expectations (OT)

2010-04-10 Thread Victor Subervi
Hi;
I'm working with my first client where I've developed a custom script. I way
underbid the project and I ate that as part of my learning experience. We
outlined as precisely as I knew how what functionality was needed. Then he
went to input data and lo and behold he needed more functionality. I told
him that would require more investment. This went on a few times and now
he's hopping mad about being nickeled and dimed to death. I bet this sounds
familiar to you all, doesn't it? Good thing he's also a personal friend...we
will survive this. But this red flag has caught my attention. Any good
articles out there (or other advice) on how to deal with a situation like
this?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Help Troubleshooting

2010-03-12 Thread Victor Subervi
Hi;
I'm running Pexpect (no discussion list) with the following code:

#! /usr/bin/python
import pexpect

def runVpopmail(whatdo, acct, domain, newpw, oldpw=''):
  if whatdo == 'vadduser':
child = pexpect.spawn('/home/vpopmail/bin/%s %...@%s %s' % (whatdo, acct,
domain, newpw))
  elif whatdo == 'vchangepw':
child = pexpect.spawn('/home/vpopmail/bin/%s' % (whatdo))
child.expect('Please enter the email address: ')
child.sendline('%...@%s' % (acct, domain))
child.expect('Enter old password: ')
child.sendline(oldpw)
child.expect('Please enter password for %...@%s: ' % (acct, domain))
child.sendline(newpw)
child.expect('enter password again: ')
child.sendline(newpw)
  return child

No matter whether I try to add a user or edit a password, the fn seems to
return that everything is good, but nothing ever happens. When I place a
return of the child value and run it with whatdo==vadduser I get the
following output:

version: 2.3 ($Revision: 399 $) command: /home/vpopmail/bin/vadduser args:
['/home/vpopmail/bin/vadduser', 'te...@globalsolutionsgroup.vi', 'qqq']
searcher: None buffer (last 100 chars): before (last 100 chars): None after:
None match: None match_index: None exitstatus: None flag_eof: False pid:
1518 child_fd: 3 closed: False timeout: 30 delimiter: pexpect.EOF logfile:
None logfile_read: None logfile_send: None maxread: 2000 ignorecase: False
searchwindowsize: None delaybeforesend: 0.05 delayafterclose: 0.1
delayafterterminate: 0.

I don't know what this means. Any ideas on how to troubleshoot this?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Interacting With Another Script

2010-03-11 Thread Victor Subervi
On Wed, Mar 10, 2010 at 10:16 PM, alex23 wuwe...@gmail.com wrote:

 Victor Subervi victorsube...@gmail.com wrote:
   There's a program (vpopmail) that has commands which, when called,
 request
   input (email address, password, etc.) from the command line. I
 would
   like to build a TTW interface for my clients to use that interacts with
   these commands.

 The Pexpect[1] module is pretty much aimed at doing exactly this.

 1: http://www.noah.org/wiki/Pexpect


THIS looks PERFECT! Thanks!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Interacting With Another Script

2010-03-10 Thread Victor Subervi
Hi;
There's a program (vpopmail) that has commands which, when called, request
input (email address, password, etc.) from the command line. I would
like to build a TTW interface for my clients to use that interacts with
these commands. It's easy enough for me to get the information from a
script, but how do I input it when these functions keep requesting
information? I hope I've made myself clear :-}
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Email Script

2010-03-02 Thread Victor Subervi
Hi;
I have the following code:

def my_mail():
  user, passwd, db, host = login()
  database = MySQLdb.connect(host, user, passwd, db)
  cursor= database.cursor()
  ourEmail1 = 'mari...@globalsolutionsgroup.vi'
  ourEmail1 = 'p...@globalsolutionsgroup.vi'
  ourEmail2 = 'benoismyn...@gmail.com'
  form = cgi.FieldStorage()
  name = form.getfirst('name', '')
  email = form.getfirst('from', '')
  message = form.getfirst('message', '')
  message = 'Name: %s\nMessage: %s' % (name, message)
  subject = 'Message from Web Site'
  Email(
  from_address = email,
  to_address = ourEmail1,
  subject = subject,
  message = message
  ).send()
  Email(
  from_address = email,
  to_address = ourEmail2,
  subject = subject,
  message = message
  ).send()
  print 'Thank you, %s, we will get back to you shortly!br /' % (name)

This sends only the first of the two emails. Why doesn't it work to send the
second? What do?
TIA,
beno

-- 
The Logos has come to bear
http://logos.13gems.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Email Script

2010-03-02 Thread Victor Subervi
On Tue, Mar 2, 2010 at 11:48 AM, Victor Subervi victorsube...@gmail.comwrote:

 Hi;
 I have the following code:

 def my_mail():
   user, passwd, db, host = login()
   database = MySQLdb.connect(host, user, passwd, db)
   cursor= database.cursor()
   ourEmail1 = 'mari...@globalsolutionsgroup.vi'
   ourEmail1 = 'p...@globalsolutionsgroup.vi'
   ourEmail2 = 'benoismyn...@gmail.com'
   form = cgi.FieldStorage()
   name = form.getfirst('name', '')
   email = form.getfirst('from', '')
   message = form.getfirst('message', '')
   message = 'Name: %s\nMessage: %s' % (name, message)
   subject = 'Message from Web Site'
   Email(
   from_address = email,
   to_address = ourEmail1,
   subject = subject,
   message = message
   ).send()
   Email(
   from_address = email,
   to_address = ourEmail2,
   subject = subject,
   message = message
   ).send()
   print 'Thank you, %s, we will get back to you shortly!br /' % (name)

 This sends only the first of the two emails. Why doesn't it work to send
 the second? What do?
 TIA,
 beno


Should I put a timer between instances of Email?



-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   >