Re: getfirst and re

2010-01-08 Thread Carsten Haese
Victor Subervi wrote:
 Code snippet:
 [...]
 
 Error:
 [...]
 What do?

After eliminating the pieces of your post that have been copied or
quoted from elsewhere, I am left with a total of five words of your own
to ask this question, which seems to be approximately the same amount of
effort you have put into trying to figure out what's causing the error.

If you put in a little bit more effort than that, you might figure out
yourself what's causing the error, which should then logically lead you
to how to fix the error.

Good luck.

-Carsten

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


Re: getfirst and re

2010-01-08 Thread Carsten Haese
Victor Subervi wrote:
 First I get scolded for not including enough information. Now I get
 scolded for including too much. Seems I can't win. I *am* putting effort
 into understanding this. I'm sorry I'm not as sharp as you are in these
 matters.

I didn't scold you for including too much information. I scolded you for
not demonstrating any effort on your part to try to figure out the
problem. Maybe you did put effort into figuring it out, but you didn't
show us any of it. You simply threw your entire code out there and asked
an open-ended question that gave us no insight into your thought process.

 params = {}, key = 'store', global cgi = module 'cgi' from
 '/usr/lib64/python2.4/cgi.pyc'
, cgi.FieldStorage = class cgi.FieldStorage, ].value undefined
 
 TypeError: unsubscriptable object
   args = ('unsubscriptable object',)
 
 Why is the value undefined? What is an unsubscriptable object?

At least those are specific questions. value undefined means that the
cgitb traceback is unable to show a meaningful value for the object
known as cgi.FieldStorage. Maybe you should ask yourself why that is
and why you're operating on an object that doesn't have a meaningful value.

An unsubscriptable object is an object that can't be subscripted. In
other words, it's an object foo for which the expression foo[bar] is
invalid and results in exactly the kind of exception you're struggling
with right now.

-Carsten

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


Re: Another Screwy Problem

2010-01-08 Thread Carsten Haese
Victor Subervi wrote:
 Hi;
 I have this line of code:
  sql = 'select Name, Price from %sPackages where ID=%s;' % (store, pid)
 which prints to this:
  select Name, Price from productsPackages where ID=1;
 which when I enter it into the MySQL interpreter gives me this:
 mysql select Name, Price from productsPackages where ID=1;
 +--++
 | Name | Price  |
 +--++
 | pkg  | 123.45 |
 +--++
 1 row in set (0.00 sec)
 
 exactly what I expect. However, in my script for some reason it returns
 this:
 ((1,),)

The only logical explanation is that this is not the output from
executing the above-mentioned query. Maybe you should ask yourself what
it actually is.

-Carsten

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


Re: getfirst and re

2010-01-06 Thread Carsten Haese
Victor Subervi wrote:
 I have an automatically generated HTML form from which I need to extract
 data to the script which this form calls (to which the information is
 sent).

Ideally, the script that receives the submitted fields should know how
the form was generated, so it knows what fields to expect. Failing that,
 you should realize that getfirst() is not the only way to access the
contents of a cgi.FieldStorage object.

If you need to know the values of all fields whose names obey a certain
pattern, I recommend you start with a list of all field names in the
FieldStorage object and pick out the ones whose names obey that pattern.
To get the list of field names, you should consider using the .keys()
method of the FieldStorage object.

-Carsten

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


Re: please help shrink this each_with_index() implementation

2010-01-05 Thread Carsten Haese
Phlip wrote:
 Hypo Nt:
 
 def each_with_index(seq):
 index = 0
 result = []
 
 for item in seq:
   result.append([item, index])
   index += 1
 
 return result
 
 My Pythonic sequencing skills are obviously feeble. Can anything think
 of a way to write that in fewer lines?

Couldn't you just use the built-in enumerate() to replace the whole thing?

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: chown'ing by script

2010-01-05 Thread Carsten Haese
Victor Subervi wrote:
 Hi;
 I have a script that is called via the web. This script writes another
 script that is also called by the web, which in turn needs to have
 execution privileges. The problem is that the programmatically created
 file is owned by apache.apache and thus doesn't have execution
 privileges. I've tried os.chown(...) but this throws an OSError. I
 understand that chown'ing programmatically opens a big security hole.
 However, setting the gid to give apache execution privileges isn't any
 better. What do you suggest?

I suggest you find a way to achieve whatever it is you are trying to
achieve without having to execute programmatically created scripts. What
is the underlying problem you're trying to solve with this approach?

-Carsten

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


Re: MySQL Error

2010-01-01 Thread Carsten Haese
Victor Subervi wrote:
 However, ProgrammingError is not an error. How do I discover the real
 error, so I can write the appropriate except statement?

You're not making any sense. How did you determine that ProgrammingError
is not an error or that it's not the real error? Show us the code you
ran, the output you expected, and the output it produced instead.

Blind guess: You're using except ProgrammingError when you should be
using except MySQLdb.ProgrammingError. If this guess is incorrect, see
above.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Cookies

2009-12-30 Thread Carsten Haese
Victor Subervi wrote:
 On Tue, Dec 29, 2009 at 3:43 PM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
 You apparently haven't followed the tutorials carefully enough. You do
 know that a cookie is a piece of information that's stored in your
 browser, don't you? So tell me, which of the above lines of code do you
 suppose is responsible for informing your browser of the cookie's
 contents?
 
 
 This one:
 
 cookie = SimpleCookie()
 
 In the tutorial found here, for example:
 
 http://www.doughellmann.com/PyMOTW/Cookie/index.html
 
 I read the following:
 
 snip
 Cookies are used as state management, and as such as usually set by the
 server to be stored and returned by the client. The most trivial example
 of creating a cookie looks something like:
 
 import Cookie
 
 c = Cookie.SimpleCookie()
 c['mycookie'] = 'cookie_value'
 print c
 
 The output is a valid Set-Cookie header ready to be passed to the client
 as part of the HTTP response:
 
 $ python Cookie_setheaders.py
 Set-Cookie: mycookie=cookie_value
 /snip
 
 Do not the printout words Set-cookie indicate the cookie has been set?

That's exactly what that printout indicates, and ONLY that printout
indicates that. Without that printout, no cookie will be set in the
browser, because that printout is what transports the contents of the
cookie to the browser. However, the line c = Cookie.SimpleCookie()
is not responsible for producing that printout, which can be tested
easily in a Python command line:

py import Cookie
py c = Cookie.SimpleCookie()
py

As you can see, no printout is generated.

By the way, expecting a line of code to produce content that is
established in lines of codes that follow it requires a mental execution
model of Python that involves magic, mind reading, or time travel, none
of which are features Python is known for.

So, guess again. The trivial example has three more lines of code. One
of them is unlike any line you have in your code. That's the line
responsible for producing the Set-Cookie header, and that's the line
you're missing.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Cookies

2009-12-30 Thread Carsten Haese
Victor Subervi wrote:
 Here again is my code:
 
 #! /usr/bin/python
 
 import string
 import cgitb; cgitb.enable()
 import MySQLdb
 import cgi
 import sys,os
 sys.path.append(os.getcwd())
 from login import login
 import datetime, Cookie, random
 from particulars import title
 from templateFrame import top, bottom
 from particulars import myCookie
 import time
 import fpformat
 from sets import Set
 from particulars import ourOptions
 
 def cart():
   print '''Content-Type: text/html\r\n
 !DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
 html
 '''
   cookie = os.environ.has_key('HTTP_COOKIE')
   if not cookie:
 cookie = Cookie.SimpleCookie()
 cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
 cookie['lastvisit'] = str(time.time())
 cookie['lastvisit']['expires'] = cExpires
 cookie['lastvisit']['path'] = cPath
 cookie['lastvisit']['comment'] = cComment
 cookie['lastvisit']['domain'] = cDomain
 cookie['lastvisit']['max-age'] = cMaxAge
 cookie['lastvisit']['version'] = cVersion
 cookie['mycookie'] = 'mycookie'
 cookieFlag = 'new'
   else:
 cookie = Cookie.SimpleCookie(cookie)
 cookieFlag = 'old'
 #  Don't know what to do with this. It's for when client won't accept
 cookies
 #  sessionDir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session'
 #  session = shelve.open(sessionDir + '/sess_' + sid, writeback=True)
 #  session['lastvisit'] = repr(time.time())
 #  session.close()
   print cookieFlag
   cookie.load(cookie)
   print cookie
  ...
 
 Please advise.

Pardon me for not being able to read your mind. The code you're now
posting is significantly more code than your first post included. The
line that I had determined to be missing is in fact not missing, you
just didn't bother to post your actual code.

Now that you've posted your actual code, I can see that the actual
problem is that the line is in the wrong place.

The line in question is print cookie, and it's responsible for
printing a Set-Cookie *HEADER*, which is a fact that at least one of
the tutorials you pointed out has mentioned. You're printing it where it
doesn't belong, in the middle of your HTML output. You need to
reorganize your print statements such that the Set-Cookie header is
printed in the header of your script's output.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Cookies

2009-12-30 Thread Carsten Haese
Victor Subervi wrote:
 I've revised the code thus:
 
   cookie = os.environ.has_key('HTTP_COOKIE')
   if not cookie:
 cookie = Cookie.SimpleCookie()
 cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
 cookie['lastvisit'] = str(time.time())
 cookie['lastvisit']['expires'] = cExpires
 cookie['lastvisit']['path'] = cPath
 cookie['lastvisit']['comment'] = cComment
 cookie['lastvisit']['domain'] = cDomain
 cookie['lastvisit']['max-age'] = cMaxAge
 cookie['lastvisit']['version'] = cVersion
 print cookie
 cookieFlag = 'new'
  
 Unfortunately, this still prints new for the cookieFlag no matter how
 many times I refresh. Please advise.

That tells me nothing, because once again you're not posting your
complete code.

Anyway, the likely answer is that you guessed incorrectly. As I said
before, you need to make sure that the cookie is printed as part of the
page headers. I'll give you one last hint: The page header is where
you're printing the Content-type line.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Cookies

2009-12-30 Thread Carsten Haese
Victor Subervi wrote:
 Comments from a left-brain thinker without any concept of how difficult
 it is for a right-brain thinker to think like you. Care to compare
 poetry? I'd bury you.

That may be so, but the difference is that Steve is not trying to earn a
living writing poetry as far as I know, whereas you appear to be trying
to earn a living writing programs. If you can't learn to think like a
programmer, sooner or later you'll have to face the grim reality that
you'll never earn a living as a programmer. Maybe you should try to earn
a living as a poet instead.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Cookies

2009-12-30 Thread Carsten Haese
Victor Subervi wrote:
 You know, neither one of those tutorials I followed gave clear, or any,
 instruction about putting a
 print cookie
 statement in the header! How misleading!

Don't blame the tutorials for your failure to read them carefully. The
tutorial you mentioned
(http://www.doughellmann.com/PyMOTW/Cookie/index.html) says the
following right at the beginning: The Cookie module defines classes for
parsing and creating HTTP cookie *headers*. [Emphasis mine.]

Further down it says: The output is a valid Set-Cookie *header* ready
to be passed to the client as part of the HTTP response. [Emphasis
mine.] You even copy-and-pasted a snippet containing that very sentence
into an earlier post on this thread, so how you can now claim that the
tutorial didn't mention this is quite beyond me.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Another Sets Problem

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
 Once again, it seems nobody is bothering to address this issue. Is it
 beyond your reach as it is beyond mine? I feel compelled to restate the
 problem once again as I did in my original post, and to once again post
 the entire code. Hopefully someone will help me see my error.

The reason why nobody is addressing your issue is that merely posting
your code is not enough to find out what's going wrong. In order to
diagnose the code, we need to know what inputs it's processing. You're
not giving us any information about that. Alternatively, it would be
helpful to see EXACTLY what output the code is producing. You're not
giving us that either. You're merely giving us a vague description that
the code doesn't print everything you're expecting.

That leaves us with only your code, which is an impenetrable fortress of
poorly named variables, import statements you think you need but don't,
and lots of Python anti-idioms, all of which conspire to make it
impossible for anybody who is not paid to do this work to put in the
effort that's necessary to trace your logic and identify the bug.

Please help us help you.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Another Sets Problem

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
 Since it is difficult to send the inputs but easy to provide the
 outputs, and as opposed to posting the printout, let me direct you here
 to see it first-hand:
 http://angrynates.com/cart/enterProducts2.py?store=products

All right, I've gone to that URL. Now what? I see an HTML table, but I
can't tell how it differs from what you're expecting, because you didn't
describe what you're expecting.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Another Sets Problem

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
 On Tue, Dec 29, 2009 at 12:54 PM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
 
 Victor Subervi wrote:
  Since it is difficult to send the inputs but easy to provide the
  outputs, and as opposed to posting the printout, let me direct you
 here
  to see it first-hand:
  http://angrynates.com/cart/enterProducts2.py?store=products
 
 All right, I've gone to that URL. Now what? I see an HTML table, but I
 can't tell how it differs from what you're expecting, because you didn't
 describe what you're expecting.
 
 
 Sorry. The last two fields have Set({whatever]) when all I want is the
 whatever :)

All right. I'm assuming that the following snippet of code is
responsible for that behavior:

  elif types[x][0:3] == 'set':
for f in field:
  print 'td%s/td\n' % (field)

(It's on lines 134-136 of your script if I copied and pasted it from
your previous email correctly.)

In that branch of code, field is the name of a Set object. You're
iterating over all the elements in that set, giving the name f to
the individual elements, but then you don't do anything with f.
Instead, you're printing field! Printing f instead would seem to
be a step in the right direction, but I'll readily admit that I didn't
study your code hard enough to determine whether that's the complete
solution.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Another Sets Problem

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
 You know I did this before, substituting f for field, and it honestly 
 wouldn't print but threw a 500 error. Now it works. I don't understand.

That's exactly why you keep running into strange problems. I strongly
urge you to learn to understand why your code does what it does. The
desire to find out how something works is, in my opinion, an essential
skill in a programmer, and your maybe I'll figure it out later
attitude displays a disturbing lack of this skill.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Another Sets Problem

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
 On Tue, Dec 29, 2009 at 3:58 PM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
 
 Victor Subervi wrote:
  You know I did this before, substituting f for field, and it
 honestly wouldn't print but threw a 500 error. Now it works. I don't
 understand.
 
 That's exactly why you keep running into strange problems. I strongly
 urge you to learn to understand why your code does what it does. The
 desire to find out how something works is, in my opinion, an essential
 skill in a programmer, and your maybe I'll figure it out later
 attitude displays a disturbing lack of this skill.
 
 
 Wrong. Prioritization is also important. Don't be so foolish as to think
 that I don't want to understand why my code does what it does!

You need to rethink your priorities. Understanding your code is a
prerequisite, not a luxury. You keep saying that you'll get around to
understanding your code when it's done. My point is that your code will
never be done if you don't take the time to understand it.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Cookies

2009-12-29 Thread Carsten Haese
Victor Subervi wrote:
 Hi;
 I have these lines:
 
   cookie = os.environ.get('HTTP_COOKIE')
   if not cookie:
 cookie = Cookie.SimpleCookie()
 cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
 cookie['lastvisit'] = str(time.time())
 cookie['lastvisit']['expires'] = cExpires
 cookie['lastvisit']['path'] = cPath
 cookie['lastvisit']['comment'] = cComment
 cookie['lastvisit']['domain'] = cDomain
 cookie['lastvisit']['max-age'] = cMaxAge
 cookie['lastvisit']['version'] = cVersion
 cookieFlag = 'new'
   else:
 cookie = Cookie.SimpleCookie(cookie)
 cookieFlag = 'old'
   print '''Content-Type: text/html\r\n
 !DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
 html
 '''
   print cookieFlag
 
 cookieFlag prints 'new'. Every time. Even when I refresh. I've imported
 Cookie. I've followed the tutorials :-} I've already been through my
 problem with trying to find the cookies on this computer. The fact that
 I'm using gmail is proof that cookies are enabled. I have also tried:
 cookie = os.environ.has_key('HTTP_COOKIE')
 Please advise.

You apparently haven't followed the tutorials carefully enough. You do
know that a cookie is a piece of information that's stored in your
browser, don't you? So tell me, which of the above lines of code do you
suppose is responsible for informing your browser of the cookie's contents?

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Missing Images

2009-12-26 Thread Carsten Haese
Victor Subervi wrote:
 For some reason, I'm not able to upload images to insert into my
 database. Here's my html:
 
 tdPicture #1/td
 td
 input type=file name=pic0 /
 /td
   /trtr
 tdPicture #2/td
 td
 input type=file name=pic1 /
 /td
 
 Here's the code from the page that processes the data from the preceding
 form:
 
   i = 0
   for picsStore, num in pics().iteritems():
 if picsStore == store:
   numPics = int(num)
   while i  numPics:
 y += 1
 pic = form.getfirst('pic%d' % i)
 try:
   if len(pic)  0:
 ourPics.append(pic)
  
 The output, however, when I print out ourPics, is just the names of the
 images (e.g., image.jpg). I haven't included complete code because it
 appears to me that my code is working perfectly well, but I've simply
 not coded to achieve my goal which, obviously, is to capture the image
 itself, not its name. What have I missed?

It's hard to say what you have missed, since you're not giving us nearly
enough information to determine what you haven't missed. So, we can now
either beg for more information, make random guesses, or point you at a
 code example that shows how file uploads are done with the cgi module.
I'll do the latter:

http://webpython.codepoint.net/cgi_file_upload

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Missing Images

2009-12-26 Thread Carsten Haese
Victor Subervi wrote:
 Right. Thank you again. I'd forgotten to put in
 enctype=multipart/form-data. Now I have the following snipped:
 
   for pic in ourPics:
 sql = 'update %s set pic%d=%s where ID=%s;' % (store, i,
 (MySQLdb.Binary(pic),), id)
 print sql
 #cursor.execute(sql)

This binds the name sql to a string containing an update statement...

 Which prints to screen the following:
 
 insert into products (SKU, Category, Name, Title, Description, Price,
 SortFactor, Availability, OutOfStock, ShipFlatFee, ShipPercentPrice,
 ShipPercentWeight, Associations, TempPrice, LastDatePrice, Weight,
 Metal, PercentMetal, pic0, pic1, sizes, colorsShadesNumbersShort)
 values(prodSKU1, prodCat1, name1, title1, descr, 12.34,
 500, 1, 0, 10.00, 5, 2, , 1, 2000-01-01, 2.5, ,
 20, �JFIF��H�H

...and that's an insert statement, so that's clearly not the output
from the code you posted above.

 and a bunch more binary data. This fails on insert. If I recall
 correctly, I need to convert that binary data into something like (c,
 array(... How do I do that? I'll include all code below in case it's
 necessary.

You have been told many, many times before, by myself and others, not to
embed values directly into the query string. Use parameter binding to
transmit the values to the database. I'm sure you'll find an old post of
mine somewhere in the archives of this list in which I showed you how to
do that.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: getlist question

2009-12-25 Thread Carsten Haese
Victor Subervi wrote:
 Well I've done that. What happens is the storeColNames registers the
 Availability field naturally enough; however, as I stated before, the
 getlist doesn't fetch anything because there is nothing to fetch! No
 such value is passed!

Well, what does getlist return when the situation you're describing as
getlist doesn't fetch anything occurs? Does is raise an exception?
Does it return 0? Does it return None? Does it return an empty list? An
empty string? An empty tuple? Does it return False? Does it not return
at all and causes the universe to fall into a black hole?

 So, what I need to do is figure out a way to log
 the fact that no value is fetched. What I have currently, unfortunately,
 simply ignores the unfetchable value. As I stated before, I need to log
 the fact that no such value is obtained. Please...how do I do that??

Please be less vague. What part do you have a problem with? Checking
whether no value is fetched or log the fact?

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: getlist question

2009-12-25 Thread Carsten Haese
Victor Subervi wrote:
 On Fri, Dec 25, 2009 at 11:35 AM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
 
 Victor Subervi wrote:
  Well I've done that. What happens is the storeColNames registers the
  Availability field naturally enough; however, as I stated
 before, the
  getlist doesn't fetch anything because there is nothing to fetch! No
  such value is passed!
 
 Well, what does getlist return when the situation you're describing as
 getlist doesn't fetch anything occurs? Does is raise an exception?
 Does it return 0? Does it return None? Does it return an empty list? An
 empty string? An empty tuple? Does it return False? Does it not return
 at all and causes the universe to fall into a black hole?
 
 
 It returns nothing. I believe I've stated that three times now.

Bzzzt! Wrong! Nothing is not a Python object, and stating it three
times doesn't make it any less wrong. The result you're getting is a
Python object. It might represent Nothingness to you, but it's not
nothing. Try to find out what that object is, so that you can then use a
Python if-statement to check whether the return value you're getting is
such an object.

 
  So, what I need to do is figure out a way to log
  the fact that no value is fetched. What I have currently,
 unfortunately,
  simply ignores the unfetchable value. As I stated before, I need
 to log
  the fact that no such value is obtained. Please...how do I do that??
 
 Please be less vague. What part do you have a problem with? Checking
 whether no value is fetched or log the fact?
 
 
 No value is fetched because there is no value to fetch. I want to be
 able to log the fact that no value was fetched. How do I do that? Am I
 not being clear? Here, let me try again, as I began this thread with my
 first post. I thought it was so easy, so clear. If I use getfirst, I can
 set a default to log whether getfirst gets anything or not. I cannot do
 that with getlist. Is there a work-around?

See above. Try to find out what kind of object it does return in the
case that's causing you grief, and then devise a Python if-statement to
test for that object. Hint: Use type() and repr() to find out what
getlist() is returning.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: More On the Strange Problem

2009-12-23 Thread Carsten Haese
Victor Subervi wrote:
 [...]
 If in fact the problem has to do with the None value, how can I easily
 substitute a different value? I tried:
 
 if theVal == None:
   theVal = ''
 
 but that didn't capture it.

That indicates one of two things:
* Your problem is not caused by the None value.
* Your problem is caused by code that is executed before the above
substitution.

Unfortunately, nobody is going to be able to offer any concrete advice,
since you're not posting the actual code you're running. My guess is
that something in your code for handling a datetime field is raising an
exception that is caught and silenced with an except: pass somewhere
outside your loop.

The only way we can help you is if you help us help you by posting your
actual code instead of incoherent snippets. You have been asked many
times before to post your actual code. One has to wonder what causes
your persistent inability or unwillingness to honor this request.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Manipulating MySQL Sets

2009-12-13 Thread Carsten Haese
Victor Subervi wrote:
 On Sat, Dec 12, 2009 at 6:35 PM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
 
 The traceback helpfully shows us that colValue is a 1-tuple whose zeroth
 entry, colValue[0], is an actual bona-fide Python Set object. Such
 objects aren't indexable, because sets are unordered. That still doesn't
 tell us where colValue is coming from, though, so why it is a Python Set
 object when you expected it to be a string remains an unsolved mystery.
 
 
 Who said I was expecting a string?

You did, indirectly, since you were expecting the value to be the
contents of a MySQL SET column, which as far as I can determine should
be returned as a string. (Recall that I showed a complete example that
demonstrates this.) The fact that you don't get a string is something
that you ought to be interested in investigating.

 I don't know what I'm expecting!

That statement is the most succinct summary of the root cause of all
your problems. If you don't know what to expect, how could you possibly
write code that produces what you expect? (Don't answer this question.
It's a rhetorical question.)

 I need to be able to parse this thing, whatever it is. You say it's a
 Python Set object. How do I parse it? Googling has been disappointing.

What do you mean by parse? What is the end result you are hoping to
achieve by parsing a Set object?

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Manipulating MySQL Sets

2009-12-13 Thread Carsten Haese
Victor Subervi wrote:
 I need to get at the individual elements of the set (that which is
 between the single quotes).

It's not quite clear what you mean by get at the individual elements,
so I'll just show you a couple of things you can do to a set, and maybe
one of them comes close to what you need:

 from sets import Set
 aSet = Set(['Small', 'Extra-small', 'Medium'])

Do something for each element:

 for element in aSet:
... print element
...
Small
Extra-small
Medium

Convert the set to list:

 list(aSet)
['Small', 'Extra-small', 'Medium']

Test membership in the set:

 'Small' in aSet
True
 'Banana' in aSet
False

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: MySQL set and enum, calling values

2009-12-12 Thread Carsten Haese
Victor Subervi wrote:
 On Fri, Dec 11, 2009 at 8:13 PM, Gabriel Genellina
 gagsl-...@yahoo.com.ar mailto:gagsl-...@yahoo.com.ar wrote:
 Are you sure the column is declared as SET and not, say, VARCHAR?
 
 
 yes

Indeed it is, and knowing that, I can actually decode your original
post. I apologize that I didn't see the forest for all the trees you
gave us.

Your problem is that you are inspecting the metadata of a table to find
out which possible values can be stored in a particular SET column of a
particular table, and when you get the description of the table, you're
getting a Python string object that describes the column, rather than a
list (or set) of strings.

The only solution is the one you already resigned to using, which is to
dissect the string into its parts, as confirmed by this article:
http://dev.mysql.com/tech-resources/articles/mysql-set-datatype.html .

 Anyway, I don't think MySQLdb is able to handle the SET data type
 correctly.
 
 
 Oh, lovely! What do?

MySQLdb does too handle the SET data type correctly, or at least as
correctly as the underlying database itself will allow. It seems that
SET-typed values can only be retrieved as strings or integers, and the
latter only by casting the value to an integer by adding 0 to it. Oh,
the humanity!

The best advice I can give you is to rethink your data schema and avoid
using the SET data type altogether. (Note that I'm only referring to the
MySQL data type here. There's nothing wrong with Python's Set type.)
The above-mentioned article has a section called Why you shouldn't use
SET. You should read it.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Getting Default Values Out of MySQL

2009-12-12 Thread Carsten Haese
Victor Subervi wrote:
 Hi;
 I'm using MySQLdb. If I do a
 cursor.execute('describe myTable;')
 it gives me all sorts of data but not my default values.

That function call doesn't give any data at all, except for the
rowcount (which would be the number of columns in the table). You must
use some other command to retrieve the result set. What command are you
using, and what are the results?

 How do I
 retrieve them?

In my version of MySQL, he default value is in the fifth column of the
result set.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Getting Default Values Out of MySQL

2009-12-12 Thread Carsten Haese
Victor Subervi wrote:
 
 
 On Sat, Dec 12, 2009 at 10:54 AM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
 
 Victor Subervi wrote:
  Hi;
  I'm using MySQLdb. If I do a
  cursor.execute('describe myTable;')
  it gives me all sorts of data but not my default values.
 
 That function call doesn't give any data at all, except for the
 rowcount (which would be the number of columns in the table). 
 
 
 Really?

Yes, really.

 cursor.execute('describe %s;' % store)
 storeDescription = cursor.fetchall()
 print storeDescription
 
 Prints out this:
 [snip...]

So it does. And if you look really, really carefully, maybe you'll be
able to tell the difference between this, your original code snippet:

cursor.execute('describe %s;' % store)

And this, which is what *actually* produces your output:

cursor.execute('describe %s;' % store)
storeDescription = cursor.fetchall()
print storeDescription

The all sorts of data you referred to in your original post is
obtained in the fetchall() call and then printed in the print statement.
As I said, your output did not come from the execute() call.

As usual, in your original post you didn't include the code that
produces the output that's causing you grief, and you didn't include the
output, either. This information is essential for helping you, and you
have been asked many times before to provide this information.
Persistently asking for help and not providing enough information is, as
has been noted before, a form of rudeness.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Manipulating MySQL Sets

2009-12-12 Thread Carsten Haese
Victor Subervi wrote:
 Hi;
 What type does python consider a MySQL Set??

Let's take a look:

 import MySQLdb
 conn = MySQLdb.connect(db=carsten, user=blah, passwd=blah)
 cur = conn.cursor()
 cur.execute(
... create table pizza (
... id integer,
... toppings set('cheese','sauce','peperoni','mushrooms')
... )
... )
0L
 cur.execute(
... insert into pizza values(1, 'cheese,sauce,peperoni')
... )
1L
 cur.execute(select * from pizza)
1L
 rows = cur.fetchall()
 toppings = rows[0][1]
 print toppings
cheese,sauce,peperoni
 print type(toppings)
type 'str'


Looks like a string to me.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Manipulating MySQL Sets

2009-12-12 Thread Carsten Haese
Victor Subervi wrote:
 Yep, sure does, but it isn't. Again:
 
   if isinstance(colValue[0], (str, int, long, float, long,
 complex, unicode, list, buffer, xrange, tuple)):
 pass
   else:
 print 'XXX'
 
 and those strings printed triple-X. It ain't no string. Besides, if it
 were a string, I'd be able to slice it, wouldn't I? Can't slice it either.

Well, then colValue[0] is not a string. This in turn probably means that
colValue[0] does not represent the contents of a SET-type column.
However, I can't tell you what it actually is, because you're once again
not providing enough information. We'd need to see where colValue is
coming from to find out what colValue[0] is.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Manipulating MySQL Sets

2009-12-12 Thread Carsten Haese
Victor Subervi wrote:
 PS:
 
 Changed the code to this:
 
 elif col[:3] != 'pic':
   if isinstance(colValue[0], (str, int, long, float, long,
 complex, unicode, list, buffer, xrange, tuple)):
 pass
   else:
 print 'XXX'
 if col == 'sizes': # One of those lovely sets
   print colValue[0][0]
 
 
 throws this lovely error:
 
  /var/www/html/angrynates.com/cart/display.py
 http://angrynates.com/cart/display.py
96 raise
97   cursor.close()
98   bottom()
99
   100 display()
 display = function display
  /var/www/html/angrynates.com/cart/display.py
 http://angrynates.com/cart/display.py in display()
50 print 'XXX'
51 if col == 'sizes':
52   print colValue[0][0]
53 #ourValue = string.split(colValue[0][6:-3], ',')
54 #   print ourValue
 colValue = (Set(['Small', 'Extra-small', 'Medium']),)
 
 TypeError: unindexable object
   args = ('unindexable object',)

The traceback helpfully shows us that colValue is a 1-tuple whose zeroth
entry, colValue[0], is an actual bona-fide Python Set object. Such
objects aren't indexable, because sets are unordered. That still doesn't
tell us where colValue is coming from, though, so why it is a Python Set
object when you expected it to be a string remains an unsolved mystery.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: MySQL set and enum, calling values

2009-12-11 Thread Carsten Haese
Victor Subervi wrote:
 [...] if I go to print, say,
 colFieldValues[20], which is a set, it prints out the whole set:
 set('Extra-small','Small','Medium','Large','XLarge','XXLarge','XXXLarge')
 But if I print out colFieldValues[20][0], it prints out s.

The only reasonable explanation of this behavior is that despite all
your wishing for it to be a set, colFieldValues[20] is in fact not a
set, but rather a string. It is a string containing the letter s,
followed by the letter e, followed by the letter t, followed by an
openening parenthesis, and so on.

 Also, how can I test
 for it? It's an instance of string. How do I know if it's a set?

That's a fantastic question. Python thinks it's a string. What makes you
think it's a set?

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: My Darned Image Again

2009-12-08 Thread Carsten Haese
Victor Subervi wrote:
 Hi;
 I'm having trouble loading my image again. Here's my code:
 
   for pic in pics:
 sql = 'update %s set %s=%s where SKU=%s;' % (store,
 colNamesPics[i], '%s', sku)
 sql = sql, (MySQLdb.Binary(pics[int(i)]),)
 cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),))
 print sql
 i += 1

Oh boy, programming by accident strikes again. Your immediate problem is
the line sql = sql, (MySQLdb.Binary(pics[int(i)]),) wherein you're
reassigning the name sql to become a 2-tuple consisting of the
string formerly known as sql and the 1-tuple containing the picture
contents. That line has no business being there. Delete it.

There are also some stylistic problems in your code that aren't actually
wrong, but they make my toenails curl in horror. Please allow me to
improve your code.

First of all, you're iterating over pics, and assigning the name
pic to each one, but you're not referring to that name anywhere.
Instead, you use an artificial index counter (i), which you're then
using to look up the i-th picture. Of course, you need i to look up
the i-th column name. Instead, you should do a parallel iteration that
iterates over the column name and the picture simultaneously. Look in my
code below for the line containing zip to see how that's done.

Also, you should only use string interpolation to build the parts of the
query that aren't values. In other words, only the variable table and
column names should be put into the query via string interpolation. The
sku should be passed as a parameter. Also, you should just use %%s to
get a literal %s through the interpolation step instead of
interpolating %s into %s markers.

Putting all that together, I'd rewrite your code above as follows:


for (column_name, pic) in zip(colNamesPics, pics):
query = (update %s set %s = %%s where SKU=%%s %
(store, column_name) )
parameters = (MySQLdb.Binary(pic), sku)
cursor.execute(query, parameters)


There, that's much less cluttered.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: My Darned Image Again

2009-12-08 Thread Carsten Haese
Victor Subervi wrote:
 I don't know what happened, but when I
 pulled that out, it threw a familiar error that alerted me to quote the
 last variable (SKU=%s) and the blob went straight in. Thanks!

The fact that you had to quote the SKU value indicates to me that it's
an alphanumeric value (or worse), which means you should really heed the
advice I've given in my other response on this thread: Use parameter
binding instead of string interpolation to provide the SKU value. That
way, regardless of what craziness the SKU value contains, the syntactic
integrity of your database query is not in danger.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: unsupported operand type(s) for %: 'NoneType' and 'tuple'

2009-12-07 Thread Carsten Haese
Victor Subervi wrote:
 I'll do my best to remember to do that from
 now on to:
 
 allTrees = [{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {},
 'presCat2': {}}]
 level = 0
 tree = []
 for aTree in allTrees:
 ...   for name in sorted(aTree.keys()):
 ... tree.append(%s%s % (\t * level, name))
 ... print aTree([name], level + 1)
 ...
 Traceback (most recent call last):
   File stdin, line 4, in ?
 TypeError: 'dict' object is not callable

 
 So It would seem I need to either figure a way to coerce the dicts into
 being tuples a la:
 http://code.activestate.com/recipes/361668/
 (which looks like a lot of work) or I need to supply tuples instead of
 dicts.

No. You need to test the actual code you want to test. The code you
typed manually has some very significant differences from the code you
first posted. For example, one uses printTree(aTree[name], level +
1), and the other uses print aTree([name], level + 1). The
conclusions you are drawing from this test are meaningless guesses that
have nothing to do with solving your actual problem.

 The dicts come from here:
 
 cursor.execute('select category from categories%s order by Category;' %
 (store[0].upper() + store[1:]))
 theTree = expand(cursor.fetchall())
 
 which is the magical code supplied by the lister that does all the heavy
 lifting but that I don't understand :-}
 Suggestions?

Start by understanding the code you're using.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: unsupported operand type(s) for %: 'NoneType' and 'tuple'

2009-12-07 Thread Carsten Haese
Victor Subervi wrote:
 Well, if you could point me in the right direction, it would be
 appreciated. I've tried googling this with no luck. Apparently, expand
 is not a well-documented term in python and, of course, it's an
 often-used term in English, which further confuses the issue. Yes, I
 would like to understand this code.

If I remember correctly from one of your earlier posts, expand is a
name of a function that's actually defined in your code. Understanding
its name won't help you understand what it does. It would do exactly the
same if it were called frobnicate and all instances of expand in
your code were replaced with frobnicate.

To understand what the function does, look at the function definition
and pretend that you're the Python interpreter: Follow the code one
instruction at a time and imagine what each instruction does. If you do
this correctly, you will understand what the code does. This won't tell
you *why* it does it, but it's your code, and you put it there to serve
a particular purpose. If you don't understand its purpose, you shouldn't
be using it at all.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Nested Dicts

2009-12-05 Thread Carsten Haese
Victor Subervi wrote:
 d = {'cat': {'one':'two'}}
 for a, b in d:
 ...
   File stdin, line 2
 
 ^
 IndentationError: expected an indented block
 d = {'cat': {}}
 for a, b in d:
 ...
   File stdin, line 2
 
 ^
 IndentationError: expected an indented block

 
 So apparently, if either the nested dict is populated or not doesn't
 seem to throw any errors in the interpreter.

What do you mean by doesn't seem to throw any errors in the
interpreter? Can't you see the IndentationErrors above?!?
IndentationErrors *are* errors!

A for-loop needs to have at least one statement inside the suite after
the colon. You're not putting any statements after the colon, and that's
why Python is throwing the same error in either case.

Because you're not entering syntactically correct code, the interpreter
session never even gets around to iterating over the dictionary, so your
session dies before it gets a chance to reproduce the error you're
looking for. If you put a dummy pass statement into the loop, you'll
reproduce the ValueError you're trying to troubleshoot:

 d = {'cat': {'one':'two'}}
 for a, b in d:
... pass
...
Traceback (most recent call last):
  File stdin, line 1, in module
ValueError: too many values to unpack

As far as what's causing this error, I already explained that two weeks
ago: http://groups.google.com/group/comp.lang.python/msg/b9e02a9a9b550ad3

The fact that you're still struggling with this error is deeply
disturbing to me.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Nested Dicts

2009-12-05 Thread Carsten Haese
Victor Subervi wrote:
 Of course I knew about those indentation errors

That may be so, but you cleverly disguised this fact by saying the exact
opposite.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Insane Problem

2009-12-03 Thread Carsten Haese
Victor Subervi wrote:
 I believe I mentioned in my first post that the print test does print
 the exact fields being called from the referring page.

Was any part of What do the print statements actually print? Please
copy and paste their output. unclear to you in any way?

 Perhaps this
 is a bug in the cgi interface?

Unlikely.

It's much more likely that whatever frankencode you stitched together
from examples you found on the internet without understanding how they
work is doing something unexpected, and you are unable to diagnose the
problem because you don't understand how your code works.

In order to help you diagnose the problem, we need to see the *exact*
code you're running, we need to see the *exact* inputs going into it,
and we need to see the *exact* output coming out of it.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Insane Problem

2009-12-03 Thread Carsten Haese
Victor Subervi wrote:
 In order to help you diagnose the problem, we need to see the *exact*
 code you're running, we need to see the *exact* inputs going into it,
 and we need to see the *exact* output coming out of it.
 
 
 Let's see your answers and see if you're right that the above output
 helps you arrive at the correct conclusion.

No, it doesn't, because you've only provided one third of what I asked
for. I also asked for the code and the inputs that go into it.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Insane Problem

2009-12-03 Thread Carsten Haese
Victor Subervi wrote:
 No, it doesn't, because you've only provided one third of what I asked
 for. I also asked for the code and the inputs that go into it.
 
 
 I provided those earlier.

No, you didn't provide the exact code you're running. You provided a
selected snippet you deemed important, but because you don't actually
know what the problem is and where it is, your determination of what's
important is not helpful. You actually managed to snip away the part
that causes the problem.

The code snipped you posted earlier showed cgi.FieldStorage being called
once. The code you're posting now makes it clear that cgi.FieldStorage
is actually called multiple times in a loop:

 [snip...]
 def optionsPrintout(table):
   form = cgi.FieldStorage()
   fn = getattr(options, table)
   ourOptionsNames = []
   optionsNames, doNotUse  = fn('names')
 
 [snip...]

   for table in storesTables:
   [snip...]
   print optionsPrintout(table)
   [snip ...]

The problem is that the first call to cgi.FieldStorage() consumes all
POST variables that were given to the script, so any subsequent call
reads an empty file and results in an empty FieldStorage object. Rewrite
your code to construct the FieldStorage object once and refer to that
one object in every pass of the loop.

As you can see, and as I suspected, it's not a bug in the cgi module.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Moving from Python 2 to Python 3: A 4 page cheat sheet

2009-12-02 Thread Carsten Haese
John Posner wrote:
  Goal: place integer 456 flush-right in a field of width 8
 
   Py2: %%%dd % 8 % 456
   Py3: {0:{1}d}.format(456, 8)
 
 With str.format(), you don't need to nest one formatting operation
 within another.

With string interpolation, you don't need to do that, either.
 '%*d' % (8,456)
' 456'

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Exec Statement Question

2009-11-30 Thread Carsten Haese
Victor Subervi wrote:
 Taking out the parenthesis did it! Thanks. Now, you state this is an
 option of last resort. Although this does indeed achieve my desired aim,
 here is a complete example of what I am trying to achieve. The following
 is from 'createTables2.py':
 
   for table in tables:
 try:
   exec 'from options import %s' % table
 except:
   pass
 try:
   exec '%s()' % table
 except:
   pass

Here's a rough sketch of rewriting that snippet in a way that uses
attribute lookup instead of dynamic code execution:

#---#
import options
for table in tables:
tablefunc = getattr(options, table)
tablefunc()
#---#

The main ideas behind this approach are:

1) Rather than importing the functions from the options module piecemeal
into the local namespace, I just import the entire options module as its
own separate namespace.

2) I use getattr on that separate namespace to look up the desired
function object from the options module. I assign the local name
tablefunc to the resulting function object.

3) I call that function using the local name tablefunc.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Can't Encode Pic

2009-11-27 Thread Carsten Haese
Victor Subervi wrote:
 The difficulty I am having is that for
 some reason it's not inserting. The form inserts the first image but not
 the second.

My guess is that you're not calling db.commit() after inserting the
second image. (If you had shown your code, I wouldn't have to guess.)

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: why do I get this behavior from a while loop?

2009-11-27 Thread Carsten Haese
S. Chris Colbert wrote:
 In [15]: t = 0.
 
 In [16]: time = 10.
 
 In [17]: while t  time:
: print t
: t += 0.1   
:
:
 0.0 
 0.1 
 0.2 
 0.3 
 --snip--
 9.4
 9.5
 9.6
 9.7
 9.8
 9.9
 10.0
 
 
 I would think that second loop should terminate at 9.9, no? 

It would, if a floating point number could represent the number 0.1 and
its multiples precisely, but it can't.

 I am missing something fundamental?
 

Yes. Read http://docs.python.org/tutorial/floatingpoint.html .

Then, change print t to print repr(t) to see what's going on.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Can't Encode Pic

2009-11-27 Thread Carsten Haese
Victor Subervi wrote:
 On Fri, Nov 27, 2009 at 12:13 PM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
 
 Victor Subervi wrote:
  The difficulty I am having is that for
  some reason it's not inserting. The form inserts the first image
 but not
  the second.
 
 My guess is that you're not calling db.commit() after inserting the
 second image. (If you had shown your code, I wouldn't have to guess.)
 
 
 That was the logical guess and yes, it hit the target. I should have
 known better. Thank you.
 Now, I have this line of code on another page that calls the images once
 the database is populated:
 
   print 'img src=getpic.py?pic=%did=%d
 width=100/td\n' % (a, w)
 
 This is looped through for every value of pic/id returned from the
 database, producing the following code on the Web page:
 
 img src=getpic.py?pic=1id=1 width=100/td
 img src=getpic.py?pic=1id=2 width=100/td
 
 The problem here is that only one of the images prints on the said page!
 However, if I surf to those URLs, the images appear!

Are you sure that you're surfing to *exactly* those URLs? When I go to
http://www.angrynates.com/cart/getpic.py?pic=2id=1, I get an image, but
when I go to http://www.angrynates.com/cart/getpic.py?pic=1id=2, I get
an error message. I am guessing that you have your pic and id parameter
switched around.

 Is it possible that
 because I'm passing values to the variables and perhaps simultaneously
 calling the script, that it can only fulfill the first request?

That's possible if your script is doing something stupid, but I find my
above guess much more likely.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Can't Encode Pic

2009-11-26 Thread Carsten Haese
Victor Subervi wrote:
 Hi;
 I have the following code:
 
 import cgitb; cgitb.enable()
 import cgi
 import MySQLdb
 from login import login
 user, passwd, db, host = login()
 db = MySQLdb.connect(host, user, passwd, db)
 cursor= db.cursor()
 form = cgi.FieldStorage()
 pic1 = form.getfirst('pic1')
 cursor.execute('update products set pic1=%s where ID=1;' % pic1)
 
 which throws the following error:

 [snip UnicodeDecodeErrors and various blind guesses...]
  
 Please advise.

The UnicodeDecodeErrors are a red herring. The real problem is that
you're using string interpolation (the %-operator) to pass the image
data to the database, so your code is force-feeding binary junk directly
into the query string. This results in an SQL query that's not
syntactically correct.

In order to pass values to the database safely, you need to use
parameter binding. In this case, that'll look something like this:

cursor.execute('update products set pic1=%s where ID=1',
(MySQLdb.Binary(pic1),))

[That comma between the two closing parentheses is not a typo. Do not
leave it out!]

Note that I'm not using string interpolation to shoehorn the picture
contents into the query string. I'm passing two arguments to
cursor.execute(). The first is the query template, with a %s placeholder
for your image contents. (Note that the query template is a plain ASCII
string, so all your Unicode-related problems will disappear in a puff of
magic.) The second argument is a tuple containing the actual parameters
to be filled into the query by the database engine. This query needs
only one parameter, so I'm making a 1-tuple containing the picture
contents, wrapped inside a MySQLdb.Binary object to tell the database
that this is a binary object.

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Can't Encode Pic

2009-11-26 Thread Carsten Haese
Victor Subervi wrote:
 Hang on. Not done yet. The line of code I gave you was just a test case.
 The real ones, and the error they threw, follows:
 [...]
73 cursor.execute(sql, (MySQLdb.Binary(pics[id]),))
 [...]
 
 TypeError: list indices must be integers
   args = ('list indices must be integers',)
 
 Please advise,

I know the answer, but I'm not going to spoon-feed it to you this time,
since even a mediocre programmer should be able to figure this one out,
and you really need to start thinking for yourself if you ever want to
grow as a programmer.

How much time did you spend trying to figure out what that error message
is telling you? What thought processes, if any, have you followed?

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Raw strings as input from File?

2009-11-24 Thread Carsten Haese
utabintarbo wrote:
 I have a log file with full Windows paths on a line. eg:
 K:\A\B\C\10xx\somerandomfilename.ext-/a1/b1/c1/10xx
 \somerandomfilename.ext ; txx; 11/23/2009 15:00:16 ; 1259006416
 
 As I try to pull in the line and process it, python changes the \10
 to a \x08.

Python does no such thing. When Python reads bytes from a file, it
doesn't interpret or change those bytes in any way. Either there is
something else going on here that you're not telling us, or the file
doesn't contain what you think it contains. Please show us the exact
code you're using to process this file, and show us the exact contents
of the file you're processing.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Switching Databases

2009-11-23 Thread Carsten Haese
Victor Subervi wrote:
 Hi;
 I have the following code:
 
 import MySQLdb
 ...
 user, passwd, db, host = login()
 db = MySQLdb.connect(host, user, passwd, 'cart')
 cursor= db.cursor()
 ...
 cursor.close()
 db = MySQLdb.connect(host, user, passwd, db)
 cursor= db.cursor()
 
 Now, python complains about me opening a new connection.

Do not paraphrase error messages. Copy and paste the actual error
message and traceback.

 But I thought
 I'd closed the first one!

You thought you did, but did you? The code snippet above doesn't show
any code that closes a database connection.

 So, I replaced the last 3 lines with this:
 
 cursor.execute('use %s;' % db)
 
 but it didn't like that, either.

Do not paraphrase error messages. Copy and paste the actual error
message and traceback.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: print function in python3.1

2009-11-23 Thread Carsten Haese
Anjanesh Lekshminarayanan wrote:
 As of now, there is no mysql adaptor for Python3. Hence cant use 
 escape_string()

Maybe it would help if you explained what you are actually trying to
accomplish.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Switching Databases

2009-11-23 Thread Carsten Haese
Victor Subervi wrote:
 On Mon, Nov 23, 2009 at 9:17 AM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
 
 You thought you did, but did you? The code snippet above doesn't show
 any code that closes a database connection.
 
 
 Would you be so kind as to tell me exactly what code *does* close a
 database, then?

Assuming that db is the name of the database connection object,
db.close() closes the connection.

 That would solve this handily. Other than than, when I
 am at a computer when I can provide you error messages, I will, but it
 all boils down to that code that closes the database, doesn't it?

Only if your diagnosis of the problem is accurate, and I have my doubts
about that. A MySQL database server is perfectly capable of entertaining
multiple simultaneous connections, so I find it unlikely that your
inability to open a second connection is caused by not closing the first
connection.

As I said, the best way we can help you is if you copy the actual error
message so that we may diagnose the actual problem and suggest a
solution that fixes the problem.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Switching Databases

2009-11-23 Thread Carsten Haese
Victor Subervi wrote:
 On Mon, Nov 23, 2009 at 10:08 AM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
 
 As I said, the best way we can help you is if you copy the actual error
 message so that we may diagnose the actual problem and suggest a
 solution that fixes the problem.
 
 
 That gave me the idea that I should simply open two separate
 connections. Here's the error that got thrown with the second connection:

 [snip...]

37   db2 = MySQLdb.connect(host, user, passwd, db)

 [snip...]

 TypeError: connect() argument 4 must be string, not Connection

Have you tried to *read* and *understand* this error message? My guess
is no. The error message tells you all you need to know. You need to
pass a string as argument 4, but you aren't. db is a database
connection object, not a string. Change db to a string containing
the name of the MySQL database to which you want to connect.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Don't Understand Error

2009-11-23 Thread Carsten Haese
Victor Subervi wrote:
 [Mon Nov 23 09:52:21 2009] [error] [client 66.248.168.98] Premature end
 of script headers: mailSpreadsheet.py, referer:
 http://globalsolutionsgroup.vi/display_spreadsheet.py
 
 Why?

A CGI script is expected to produce output. Your script doesn't produce
any output, and Apache is complaining about that.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Too Many Values To Unpack

2009-11-21 Thread Carsten Haese
Victor Subervi wrote:
   File /var/www/html/angrynates.com/cart/catTree.py
 http://angrynates.com/cart/catTree.py, line 25, in getChildren
 for (nm, dt) in levelDict:
 ValueError: too many values to unpack
 
 Please advise.

I already explained what's causing this error. Read my first response on
this thread.
(http://mail.python.org/pipermail/python-list/2009-November/1227008.html)

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Python Will Not Send Email!!

2009-11-20 Thread Carsten Haese
Victor Subervi wrote:
 On Thu, Nov 19, 2009 at 5:01 PM, Kev Dwyer kevin.p.dw...@gmail.com
 mailto:kevin.p.dw...@gmail.com wrote:
 
 On Thu, 19 Nov 2009 11:28:37 -0400, Victor Subervi wrote:
 
 Hello Victor,
 
 There are some pages on the internet that suggest that this problem
 my be
 caused by a module named email.py (or email.pyc) in your pythonpath.  If
 you try import smtplib in the interpreter do you get this error message?
 If so, start a new interpreter session and try import email - is the
 email module imported from the stdlib?
 
 
 Both of these import just fine.

Kevin neglected to mention that the new interpreter session must be
started in the same directory as the one you're in when you run your
testMail.py script. Since he didn't mention that, we can't be sure that
that's what you did, so this experiment doesn't prove anything.

Please show us a copy-and-paste of your command line window contents
that result from executing python testMail.py and then executing
python -c import email; print email immediately thereafter.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Too Many Values To Unpack

2009-11-20 Thread Carsten Haese
Victor Subervi wrote:
 Hi;
 At one point Dennis Lee Bieber helped me with the following slightly
 modified code:

 [snippage...]

 def getChildren(levelDict, level = 0):
   MAXLEVEL = 7
   if level  MAXLEVEL:
 return  #possibly the data has a cycle/loop
   for (nm, dt) in levelDict:
 cursor.execute('''select c.name http://c.name from categories as c
   inner join relationship as r
   on c.ID = r.Child
   inner join categories as p
   on r.Parent = p.ID
   where p.category = %s
   order by c.name http://c.name''', (nm,))
 levelDict[nm] = expand(cursor.fetchall())
 # recursive call to do next level
 getChildren(levelDict[nm], level + 1)
   # no data return as we are mutating dictionaries in place

 [snippage...]

 [Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58] for (nm,
 dt) in levelDict:
 [Fri Nov 20 07:41:11 2009] [error] [client 208.84.198.58] ValueError:
 too many values to unpack
Iterating over a dictionary, such as what you're doing in the line for
(nm, dt) in levelDict, only produces the keys that are in the
dictionary. This means that this line only works if the keys in
levelDict are pairs of nms and dts, whatever nm and dt
represent. (In case the foregoing is too subtle a clue: Choose better
variable names.)

However, the line levelDict[nm] = expand(...) indicates that the
keys in levelDict are only nms, which are presumably single objects,
not pairs. Also, the dt that you're trying to unpack from levelDict's
keys is not used anywhere in your function.

So, this would indicate that changing the offending line to for nm in
levelDict should fix this particular error.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Python Will Not Send Email!!

2009-11-20 Thread Carsten Haese
Victor Subervi wrote:
 On Fri, Nov 20, 2009 at 11:14 AM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote: 
 Please show us a copy-and-paste of your command line window contents
 that result from executing python testMail.py and then executing
 python -c import email; print email immediately thereafter.
 
 
 [r...@13gems globalsolutionsgroup.vi http://globalsolutionsgroup.vi]#
 python testMail.py
 Traceback (most recent call last):
   File testMail.py, line 2, in ?
 import smtplib
   File /usr/lib64/python2.4/smtplib.py, line 49, in ?
 from email.base64MIME import encode as encode_base64
 ImportError: No module named base64MIME
 [r...@13gems globalsolutionsgroup.vi http://globalsolutionsgroup.vi]#
 python -c import email; print email
 module 'email' from 'email.pyc'

Thank you. This proves conclusively that there IS in fact a file called
email.pyc (and/or email.py) in your directory next to testMail.py. It is
this email.pyc that is being imported instead of the email.py from the
Python library. Getting rid of both email.py and email.pyc (by renaming
them, deleting them, or moving them somewhere else) will fix your problem.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Too Many Values To Unpack

2009-11-20 Thread Carsten Haese
Victor Subervi wrote:
 Now what I don't understand about the above code, provided by Dennis Lee
 Bieber, is the expand statement.

It's not a statement. It's a function. The function is defined in your
code. Or rather, it's defined in the code that you copied from Dennis
Lee Bieber, apparently. Look at the function definition. It'll tell you
what the function does.

 Could
 someone please explain what this code does?

Maybe you should ask the person that wrote the code.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Python Will Not Send Email!!

2009-11-19 Thread Carsten Haese
Victor Subervi wrote:
 Hi;
 I created this testMail.py file as root:
 
 #!/usr/bin/env python
 import smtplib
 session = smtplib.SMTP(localhost)
 subject = Hello, 
 header = Subject: %s \r\nContent-type: text/html; charset=utf-8\r\n\r\n
 message = world!
 email_from = vic...@is.awesome
 email_to = [em...@myhost.com mailto:em...@myhost.com]
 session.sendmail(email_from, email_to, header+messages)
 
 [r...@13gems globalsolutionsgroup.vi http://globalsolutionsgroup.vi]#
 chmod 755 testMail.py
 [r...@13gems globalsolutionsgroup.vi http://globalsolutionsgroup.vi]#
 python testMail.py
 Traceback (most recent call last):
   File testMail.py, line 2, in ?
 import smtplib
   File /usr/lib64/python2.4/smtplib.py, line 49, in ?
 from email.base64MIME import encode as encode_base64
 ImportError: No module named base64MIME
 
 What gives??

Do you have a file called email.py in your current directory or
anywhere else on Python's path outside of the standard library? If so,
it's hiding the real email module from your script and you'll need to
get rid of your email.py by renaming or moving it.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Code for finding the 1000th prime

2009-11-17 Thread Carsten Haese
Stefan Behnel wrote:
 Robert P. J. Day, 15.11.2009 15:44:
 On Sun, 15 Nov 2009, mrholtsr wrote:

 I am absolutely new to python and barely past beginner in programming.
 Also I am not a mathematician. Can some one give me pointers for
 finding the 1000th. prime for a course I am taking over the internet
 on Introduction to Computer Science and Programming. Thanks, Ray
   it's 7919.
 
 Now, all that's left to do is write a prime number generator (a random
 number generator will do, too, but writing a good one isn't easy), run it
 repeatedly in a loop, and check if the returned number is 7919. Once it
 compares equal, you can print the result and you're done.

Just do a brute-force search:

for i in range(1):
if i==7919:
# Found it!
print i

;-)

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Calling Python functions from Excel

2009-11-14 Thread Carsten Haese
Cannonbiker wrote:
 Please I need Calling Python functions from Excel and receive result
 back in Excel. Can me somebody advise simplest solution please? I am
 more VBA programmer than Python.

Maybe this will help:
http://oreilly.com/catalog/pythonwin32/chapter/ch12.html (Scroll down to
Implementing a COM Server.)

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Can't Write File

2009-11-11 Thread Carsten Haese
Victor Subervi wrote:
 Here's
 a bigger code snippet with the entire try clause:
 
   if 14  x  20: # This just shows that it's a pic, not some
 other type of data
 y += 1
 w += 1
 try: # It does this, because I've printed 'getpic1.py' etc.
   getpic = getpic + str(w) + .py
   try:
 os.remove(getpic)
   except:
 pass
   code = #! /usr/bin/python
 import cgitb; cgitb.enable()
 import MySQLdb
 import cgi
 import sys,os
 sys.path.append(os.getcwd())
 from login import login
 def pic():
   user, passwd, db, host = login()
   form = cgi.FieldStorage()
   db = MySQLdb.connect(host, user, passwd, db)
   cursor= db.cursor()
   sql = select pic%s from products where ID=%s;
   cursor.execute(sql)
   content = cursor.fetchone()[0]
   cursor.close()
   print content
 print 'Content-type: image/jpeg'
 print
 pic() % (str(w), str(i))
   script = open(getpic, w) # I've deleted everything below
 this line to the except to test
   script.write(code)
   print 'tdinput type=hidden name=%s /\n' % str(x)
   os.chmod(getpic, 0755)
   print 'img src=%s width=100br /br //td\n' %
 (getpic)
   count2 += 1
 except:
   print 'tdnope/td'
   else:
 print 'td%s/td\n' % (field)
   x += 1

If I'm understanding correctly what you're doing here, you're generating
an HTML page with image tags, and at the same time you're generating the
scripts whose purpose it is to serve the corresponding images' data.
This is a terrible approach for the following reason: If two different
users request this page for two different product IDs at roughly the
same time, the getpic scripts for the first user will be overwritten by
the getpic scripts for the second user before the first user's browser
had a chance to issue its requests for the results for his getpic scripts.

Rather than auto-generating on-the-fly variants of the getpic scripts
that only differ in the picture number and product ID, you should have
just one static getpic script that takes parameters from the URL that
tell it which image number and product ID to use.

This will fix your problem indirectly because then your script won't
have to write out any files at all.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Can't Write File

2009-11-11 Thread Carsten Haese
Victor Subervi wrote:
 I will do that after I fix the problem

Doing that is the fix.

 No, this doesn't fix the problem!

How do you know? You obviously haven't tried it, since you say you have
yet to do it.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Calling a method with a variable name

2009-11-04 Thread Carsten Haese
Simon Mullis wrote:
 def main():
 stats_obj = Statistic()
 name = re.sub([^A-Za-z], , sys.argv[0])
 method = getattr(stats_obj, name, None)
 if callable(method):
 stats_obj.name()  #  HERE
 else:
 print nope, not sure what you're after
 ---
 
 However, as I'm sure you've all noticed already, there is no method
 called name. I would really prefer to get a nudge in the right
 direction before I start evaling variables and so on.

At the point you marked HERE, you've already found the method, and you
have determined that it is callable. You just need to call it. Like
this: method().

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Calendar Problem

2009-11-04 Thread Carsten Haese
Victor Subervi wrote:
 That's what I initially had. My server, that I am in
 the process of leaving, rejected that syntax.

What version of Python does that server use? The calendar.Calendar class
first appeared in Python 2.5. I suspect your server is using an older
version.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: regexp help

2009-11-04 Thread Carsten Haese
Nadav Chernin wrote:
 Thanks, but my question is how to write the regex.

See http://www.amk.ca/python/howto/regex/ .

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Sqlite3. Substitution of names in query.

2009-11-03 Thread Carsten Haese
Lawrence D'Oliveiro wrote:
 In message mailman.2504.1257216390.2807.python-l...@python.org, Carsten 
 Haese wrote:
 
 With all due respect, but if your experience is exclusive to
 MySQL/MySQLdb, your experience means very little for database
 programming practices in general.
 
 I wonder about the veracity of your claims, because:

 And here are the corresponding results on my laptop:
 $ python -mtimeit -s from querytest import Tester; t=Tester()
 't.with_params()'
 1 loops, best of 3: 20.9 usec per loop
 $ python -mtimeit -s from querytest import Tester; t=Tester()
 't.without_params()'
 1 loops, best of 3: 36.2 usec per loop
 
 Didn't you say previously that there should be a seven orders of magnitude 
 difference? What happened to that claim?

That claim was an exaggeration I resorted to after you distorted the
concept of choosing the right tool for the job into premature
optimization. It wasn't my initial claim.

The seven orders (which is actually log-10 orders of however often the
same query is executed with different values) is of course only the cost
increase on parsing the query itself, which as you pointed out is
drowned out by other fixed costs associated with performing database
queries. However, you can't dispute the fact that using string
interpolation *is* in general less efficient than parameter binding, and
that was my initial claim.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Sqlite3. Substitution of names in query.

2009-11-01 Thread Carsten Haese
Lawrence D'Oliveiro wrote:
 On what grounds are you asserting that it's not necessary to mix the
 two? Please elaborate your point.
 
 On the grounds that Python has more general and powerful string parameter-
 substitution mechanisms than anything built into any database API.

That statement is fundamentally flawed. You are assuming that the
preferred way of getting a value into a query is by substituting a
literal into the query string. That is, in general, not true, because
that would be horribly inefficient. This is also why I despise the term
parameter substitution, since it implies incorrectly that passing
parameters to a query is merely a string formatting exercise. The
correct term is parameter binding.

Most databases actually provide an API for supplying parameters
separately from the query string. This is more efficient, because it
eliminates the need to render the parameter value into a literal form on
the client side and to parse the literal form on the server side. Also,
it allows the engine to perform the same query multiple times with
different values without having to re-parse the query.

Finally, you're assuming that every value that can be supplied to a
query actually HAS a literal form. That is not true. For example, in
Informix databases, there are no literals for BYTE-type values. (You'd
probably call them blobs.) So, if vomiting literals into the query
string were your only way of conveying values to the database, you'd
never be able to populate a BYTE column on an Informix database. The
only way to pass a BYTE value to an Informix database is by parameter
binding.

Since parameter binding is in general much more than string
substitution, it is indeed necessary to mix the two.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Sqlite3. Substitution of names in query.

2009-11-01 Thread Carsten Haese
Lawrence D'Oliveiro wrote:
 Says someone who hasn't realized where the real inefficiencies are. Remember 
 what Tony Hoare told us: premature optimization is the root of all evil. 
 These are databases we're talking about. Real-world databases are large, and 
 reside on disk, which is several orders of magnitude slower than RAM. And 
 RAM is where string parameter substitutions take place. So a few hundred 
 extra RAM accesses isn't going to make any significant difference to the 
 speed of database queries.

You're just not getting it. The cost is not in performing the parameter
substitutions themselves. The cost is in parsing what's essentially the
same query one million times over when it could have been parsed only
once. You might find an increase of seven orders of magnitude
insignificant, but I don't.

 Probably why I don't use Informix. What use is a binary data type if you 
 can't insert and retrieve binary data values?

You CAN insert and retrieve binary data values. You just have to use the
right tool for the job, and that is parameter binding.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Sqlite3. Substitution of names in query.

2009-10-31 Thread Carsten Haese
Lawrence D'Oliveiro wrote:
 In message mailman.2357.1256964121.2807.python-l...@python.org, Dennis Lee 
 Bieber wrote:
 
 This way regular string interpolation operations (or whatever Python
 3.x has replaced it with) are safe to construct the SQL, leaving only
 user supplied (or program generated) data values to be passed via the
 DB-API parameter system -- so that they are properly escaped and
 rendered safe.
 
 Mixing the two is another recipe for confusion and mistakes.

Mixing the two is necessary. According to the SQL standard, parameters
can only take the place of literal values. Parameters can't take the
place of identifiers or keywords that make up the structure of the query.

So, you use string manipulation to build the structure of the query, and
then you use parameter binding to fill values into the query. They are
two different tools for two fundamentally different jobs. As long as you
understand what you're doing, there should be no confusion. (And if you
don't understand what you're doing, you shouldn't be doing it!)

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Sqlite3. Substitution of names in query.

2009-10-31 Thread Carsten Haese
Lawrence D'Oliveiro wrote:
 In message mailman.2376.1257005738.2807.python-l...@python.org, Carsten 
 Haese wrote:
 
 Lawrence D'Oliveiro wrote:

 In message mailman.2357.1256964121.2807.python-l...@python.org, Dennis
 Lee Bieber wrote:

 This way regular string interpolation operations (or whatever Python
 3.x has replaced it with) are safe to construct the SQL, leaving only
 user supplied (or program generated) data values to be passed via the
 DB-API parameter system -- so that they are properly escaped and
 rendered safe.
 Mixing the two is another recipe for confusion and mistakes.
 Mixing the two is necessary.
 ...
 As long as you understand what you're doing, there should be no confusion.
 (And if you don't understand what you're doing, you shouldn't be doing
 it!)
 
 But if you understand what you're doing, you don't need to mix the two.

Are we talking about the same thing here? I thought we're talking about
string interpolation and parameter binding, and I explained that mixing
those two is necessary if you have a query in which the movable bits
are identifiers or other syntax elements.

On what grounds are you asserting that it's not necessary to mix the
two? Please elaborate your point.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Capturing a var from JavaScript

2009-10-19 Thread Carsten Haese
Victor Subervi wrote:
 It doesn't work. What I want is to capture winX and winY and use them in
 python. How?

Since you're still not heeding the advice from this article, please
allow me to refer you to it again:
http://catb.org/~esr/faqs/smart-questions.html

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: The Never-Ending Saga Continues

2009-10-19 Thread Carsten Haese
Victor Subervi wrote:
 Can you give me an example of this?

That depends. How much of your client's money are you offering us for
doing your work?

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: More More Fun w/ Pics MySQL

2009-10-18 Thread Carsten Haese
Victor Subervi wrote:
 Thank you all. I have __no__idea__ why the link I sent you, that you
 tested, __didn't__ work for me. Was it a problem with the browser?

My Magic 8-Ball says Unclear. Ask again later.

 Regarding Carsten's misunderstanding of my mentioning of commenting out
 statements,  are the following two statements identical or not?
 
 print 'Content-type: image/jpeg'
 
 
 print 'Content-type: image/jpeg'
 #print 'Content-type: text/plain'

Those two sets of lines are functionally identical, and they *will*
*always* produce the same results in the same context. If they don't,
then your server isn't executing the code that you think it's executing.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: More More Fun w/ Pics MySQL

2009-10-17 Thread Carsten Haese
Victor Subervi wrote:
 in line...
 
 On Sat, Oct 17, 2009 at 11:33 AM, Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
 Why would turning a comment into a statement NOT make a difference?!?
 
  
 You misunderstood. Leaving in the __commented__ line __commented__ and
 __not__uncommented__ made a difference. Why?

Alright, so let me rephrase the question: Why would turning a statement
into a comment not make a difference?

Answer: The only way commenting out a line of code makes no difference
is if the line of code was superfluous to begin with. The fact that
commenting it out *does* make a difference therefore means that the line
of code is not superfluous.

 What the heck is a broken image of correct dimensions? 
 
  
 http://allpointsmarinevi.com/stxresort/cart/getpic1.py

That doesn't look like a broken image to me. When I try that URL, I get
a 750x900 pixel JPEG image that appears to be a line-drawing of sorts.
Of course I have no idea whether that's the expected result because for
some reason you decided to keep that a secret.

 You can prove whether it's your server farm or you by running the same
 code on a different server.
 
  
 Which one?

Which one what? Which code? Try all versions you have, until you find
one that works. When you do, run that on your server farm to see if it
still works.

 Again, you have to help us help you. I have listed the three things you
 need to post together, and you haven't done that. You're giving us bits
 and pieces, but nothing that's sufficiently cohesive to do any
 meaningful troubleshooting on.
 
  
 Forgive me. I must have misunderstood. I have deleted the old message.
 Would you be so kind as to re-post those three things you need me to
 provide you?

Here's what I said earlier:

The only way we have a fighting chance to help you in figuring out
what's going in is if you post the *exact* code you're running (and by
that I mean the actual code that you know your server is executing, and
not just some code that somewhat resembles the code that the server
might be executing), a detailed description of the result you're
expecting, and a detailed description of the result you're getting instead.


So, the three things I'm asking for:
* Show us EXACTLY the code you're running.
* Tell us the result you're expecting.
* Tell us the result you're getting instead.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: More More Fun w/ Pics MySQL

2009-10-16 Thread Carsten Haese
Victor Subervi wrote:
 [snip...]

 print 'Content-type: image/jpeg'
 print 'Content-Encoding: base64'
 print
 print pic().encode('base64')
 print '/body/html'

 [snip...]

Why are you printing /body/html at the end of a page that is
supposed to be a base64-encoded JPEG file?

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: More More Fun w/ Pics MySQL

2009-10-16 Thread Carsten Haese
Victor Subervi wrote:
 I was trying all sorts of crap. I tried it without, too. Still didn't
 work :(

Please help us help you. Still didn't work tells us nothing. See
http://catb.org/~esr/faqs/smart-questions.html for hints on how you can
ask a questions in a way that makes them more likely to get helpful answers.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: More More Fun w/ Pics MySQL

2009-10-16 Thread Carsten Haese
Victor Subervi wrote:
 I'm sorry. These scripts worked fine before and should have been
 plug-and-play. I have wasted 2 frustrating weeks trying to figure out
 why they don't work only to discover things that make no sense at all
 that do the trick. I thought programming was straight-forward and
 logical...boy, am I disappointed. Sorry for the jade.

Clearly, you're not jaded enough. When my code does things that I don't
understand, I try to understand what's going on. Your approach seems to
be to randomly mutate your code until it works. There is nothing
inherently wrong with that as long as you then try to understand *why*
it works once you get it work. You seem to have omitted this step. Since
you never understood why your code worked, consequently now you don't
understand why your code has stopped working.

 What I mean is that the code supplied merely posts a broken image, with
 the correct dimensions, interestingly enough. It makes no difference at
 all if one adds the line print '/body/html' or not. I also believe
 (and hope) my initial post is pretty clear.

Actually, your original post was not clear at all. Your original post
said This will print all sorts of crap to the screen. This is not
useful at all. The only reason why I responded at all was because I
noticed the /body/html line in your code that clearly didn't have
any business being there. The fact that you even considered the
possibility that that line could help shows just how little you know
about what's going on in your code.

By the way, you now have changed your story from random crap to a
broken image. Which one is it?

The only way we have a fighting chance to help you in figuring out
what's going in is if you post the *exact* code you're running (and by
that I mean the actual code that you know your server is executing, and
not just some code that somewhat resembles the code that the server
might be executing), a detailed description of the result you're
expecting, and a detailed description of the result you're getting instead.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: executing a function/method from a variable

2009-10-16 Thread Carsten Haese
Yves wrote:
 Right now I use an eval, but I'm wondering if there isn't a better way:

There's (almost) always a better way than using eval. In this case, you
should use getattr().

Here's your simplified example modified to use getattr:

import sys

class dummy(object):
  def __init__(self, arg):
self.todo = print+arg

  def printa(self):
print 'a'

  def printb(self):
print 'b'

  def doit(self):
func = getattr(self, self.todo)
func()

o = dummy(sys.argv[1])
o.doit()

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Error en el bus from python

2009-10-12 Thread Carsten Haese
Yusniel wrote:
 Exactly. hanoi.pl is a prolog program. I'm using Ubuntu(9.04) 32
 bit. In this case, this error is generated when I try run the above
 script. However, others scripts in python, not throws this error, I
 think that there are some problem with this library.

Maybe, but it's impossible to tell what exactly the problem is if you
don't show us your code. hanoi.pl is part of your code, but you haven't
posted it. Please post it.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Problem Displaying Pics

2009-10-07 Thread Carsten Haese
Victor Subervi wrote:
 [...]
 print '''Content-Type: image/jpeg
 
 Content-Encoding: base64
 '''
 [...]

You have a spurious blank line between those header lines.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: store encrypted data in sqlite ?

2009-10-02 Thread Carsten Haese
Stef Mientki wrote:
 hello,
 
 I want to store some fields in an sqlite database.
 
 I use ezPyCrypto to encrypt and decrypt:
 
 User = ['z684684', 'Mientki, Stef', 1,1,0,1,1 ]
 
 encryption_key_1 = ezPyCrypto.key ( 512 )
 
 SQL_Base = 'insert or replace into __USERS__ values ('
 for field in User :
SQL += ,' + encryption_key_1.encString ( str ( item ))+ '
 SQL += ')'
 
 
 Now this fails, probably, because the second character of the encrypted
 string is a binary zero.
 
 By trial and error, I found a work around,
 but I'm not sure this will garantee that it will work always:
 by converting the encrypted buffer with base64.encode:
 
SQL += ,' + base64.encodestring(EnCrypt_1 ( str ( item )))+ '
 
 Will this method work always ?
 Are there better methods ?

There is definitely a better method! You should use parameter binding
instead of rolling the query by hand:

SQL = insert or replace into __USERS__ values (?,?,?,?,?,?,?)
params = [ encryption_key_1.encString(str(x)) for x in User ]
cur.execute(SQL, params)

That way, the parameters are passed separately and safely, and the query
syntax is protected from all the dangerous characters that are floating
around in the parameters.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Q: sort's key and cmp parameters

2009-10-01 Thread Carsten Haese
kj wrote:
 
 Challenge: to come up with a sorting task that cannot be achieved
 by passing to the sort method (or sorted function) suitable values
 for its key and reverse parameters, but instead *require* giving
 a value to its cmp parameter.

Such a task can't exist, because any arbitrary comparison function can
be transformed into a key function. The idea behind the transformation
is to construct wrapper objects that can compare themselves to other
wrapper objects by invoking the given comparison function on their
wrapped originals.

Google for Hettinger cmp2key if you want to see the code that does
this transformation.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: accessing dictionary keys

2009-10-01 Thread Carsten Haese
Andreas Balogh wrote:
 Hello,
 
 when building a list of points like
 
 points = [ ]
 points.append((1, 2))
 points.append((2, 3))
 
 point = points[0]
 
 eventually I'd like to access the tuple contents in a more descriptive
 way, for example:
 
 print point.x, point.y

I'm not sure exactly what you're asking, but maybe the following code
will serve as a zeroth iteration toward the solution you seek:

py class Point(object):
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
py points = []
py points.append(Point(1, 2))
py points.append(Point(2, 3))
py
py point = points[0]
py print point.x, point.y
1 2

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Passing Variables WITHOUT Dynamic URLs

2009-09-17 Thread Carsten Haese
Victor Subervi wrote:
 Right. Bad example on my part. How about if I want to pass a cookie from
 page to page? Or some data called up from a database query?

Cookies are also passed in the header.

Results from a database query are best left on the server rather than
passing them back and forth between server and client. You should look
into the concept called session variables.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Confessions of a Python fanboy

2009-07-30 Thread Carsten Haese
r wrote:
 Of course in python you would do...
   vector.reverse -- in-place
   vector.reversed -- in-place

You do know that only one of those works in-place, right?

 The above example works pretty good, but this doesn't always sound
 good. Take for example this...
   point3d.offset -- return a new pt
   point3d.offseted -- What did you say!?!?!
 
 Now try Ruby's way
   point3d.offset!
   point3d.offset
 
 a symbol works better for these things

Or you could use a better verb:

point3d.move - modifies in place
point3d.moved - returns a new point

-Carsten

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


Re: problem with import path on a python C extension

2009-02-09 Thread Carsten Haese
fredbasset1...@gmail.com wrote:
 [...]
 So my question is why can't Python locate the new extension module
 when I try to import it with import project.drivers.dio.diomodule?
This import statement binds the module to the name
project.drivers.dio.diomodule. It does not bind anything to the name
diomodule, which is the name you want to use to refer to the module.

To bind the diomodule name to this module, you can do one of two things:

1:
   from project.drivers.dio import diomodule

2:
   import project.drivers.dio.diomodule
   diomodule = project.drivers.dio.diomodule

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with import path on a python C extension

2009-02-09 Thread Carsten Haese
fredbasset1...@gmail.com wrote:
 I can only get it to work if I copy the .so file to the directory
 where daemon.py is and change the import to import diomodule.

And to supplement my previous reply, another solution is to make sure
that /root/project/drivers/dio is in your PYTHONPATH. Then you can
simply import diomodule and refer to the module by the name diomodule.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reuse of DB-API 2.0 cursors for multiple queries?

2009-01-28 Thread Carsten Haese
moreati wrote:
 Today, I used the adodbapi module against an SQL Server Express
 database. I was surprised to get an exception, when I attempted to
 submit a second query with my cursor object. The full session is
 below.
 
 With cx_Oracle I've become used to reusing a cursor for subsequent
 queries. The PEP doesn't specify either way, that I can see.

The PEP doesn't say explicitly that a cursor can execute multiple
queries, but it's definitely implied by the second paragraph:


.execute(operation[,parameters])

Prepare and execute a database operation (query or
command).  Parameters may be provided as sequence or
mapping and will be bound to variables in the operation.
Variables are specified in a database-specific notation
(see the module's paramstyle attribute for details). [5]

A reference to the operation will be retained by the
cursor.  If the same operation object is passed in again,
then the cursor can optimize its behavior.  This is most
effective for algorithms where the same operation is used,
but different parameters are bound to it (many times).


You might want to check on a list dedicated to adodbapi whether there
are module-specific quirks or caveats to watch out for. Or wait for
somebody with adodbapi-specific knowledge to chime in.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get first/last day of the previous month?

2009-01-20 Thread Carsten Haese
Hussein B wrote:
 Hey,
 I'm creating a report that is supposed to harvest the data for the
 previous month.
 So I need a way to get the first day and the last day of the previous
 month.

In order to not deprive you of the sense of accomplishment from figuring
things out for yourself, I'll give you a couple of hints instead of
fully formed Python code:

1) Think about how you can find the first day of the *current* month.

2) Think about how you can get to the last day of the previous month
from there.

3) Think about how you can get to the first day of the previous month
from there.

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get first/last day of the previous month?

2009-01-20 Thread Carsten Haese
Marco Mariani wrote:
 dateutil can do this and much, much more.

Using dateutil for this is like using a sledgehammer to kill a fly. The
task at hand can (and IMHO should) be solved with the standard datetime
module.

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to remove 'FFFD' character

2009-01-09 Thread Carsten Haese
webcomm wrote:
 I don't know what the character encoding of this data is and don't
 know what the 'FFFD' represents.

The codepoint 0xFFFD is the so-called 'REPLACEMENT CHARACTER'. It is
used replace an incoming character whose value is unknown or
unrepresentable in Unicode. The browser might display these if for
example a page is encoded in latin-1 but it claims to be utf-8, so the
byte stream will contain byte sequences that can't be decoded into
unicode code points.

 I just
 want to scrub it out.  I tried this...
 
 clean = txt.encode('ascii','ignore')
 
 ...but the 'FFFD' still comes through.

You must be doing something wrong, then:

py u'Hello,\ufffd World'.encode('ascii', 'ignore')
'Hello, World'

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: can the sequence of entries in a dictionary be depended on?

2008-11-23 Thread Carsten Haese
Diez B. Roggisch wrote:
 AFAIK the order is deterministic as long as you don't alter the dict between
 iterations. However, this is an implementation detail.

It's not an implementation detail. It's documented behavior. Thus quoth
http://docs.python.org/library/stdtypes.html#mapping-types-dict :


If items(), keys(), values(), iteritems(), iterkeys(), and itervalues()
are called with no intervening modifications to the dictionary, the
lists will directly correspond.


--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: can the sequence of entries in a dictionary be depended on?

2008-11-23 Thread Carsten Haese
John Machin wrote:
 the lists will directly correspond? What does that mean? 

It means that e.g. zip(d.keys(), d.values()) == d.items() is guaranteed
to be True.

 Why not
 the lists will be equal i.e. list1 == list2?
 
 How about Provided that keys are neither added nor deleted, the order
 of iteration will not change?

Neither of those convey the above guarantee.

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unyeilding a permutation generator

2008-11-02 Thread Carsten Haese
[EMAIL PROTECTED] wrote:
 Anyway what I want to do is experiment with code similar to this (i.e.
 same algorithm and keep the recursion) in other languages,
 particularly vbscript and wondered what it would look like if it was
 rewritten to NOT use the yield statement

An obvious (though memory-inefficient) replacement is to accumulate a
list and return the list. Initialize a result variable to an empty list,
and instead of yielding elements, append them to the result variable.
Then return the result variable at the end of the function.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the instance reference of an object

2008-10-16 Thread Carsten Haese
Astley Le Jasper wrote:
 Sorry for the numpty question ...
 
 How do you find the reference name of an object?
 
 So if i have this
 
 bob = modulename.objectname()
 
 how do i find that the name is 'bob'

Why do you need to find that? You know that its name is 'bob'.

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pure Python interface to MySQL?

2008-10-06 Thread Carsten Haese
Roy Smith wrote:
 Does there exist a pure Python version of a MySQL module?

A quick google search turns up this:

http://github.com/mopemope/pure-python-mysql/tree/master/pymysql

I've never used it, though, so I have no idea whether it works or how
well it works.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: rpath

2008-09-30 Thread Carsten Haese
Kyle Hayes wrote:
 Is there a way to use the 'r' in front of a variable instead of
 directly in front of a string? Or do I need to use a function to get
 all of the slashes automatically fixed?

Please describe the actual problem you're trying to solve. In what way
do slashes need to be fixed, and why?

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: OS.SYSTEM ERROR !!!

2008-09-30 Thread Carsten Haese
Blubaugh, David A. wrote:
 To All, 
 
 
 I have been attempting to execute the following program within the
 Python environment:
 
 Myprogram.exe, which means this is an executable file!!
 
 I would usually execute this program (with the appropriate arguments) by
 going to following directory within MS-DOS (Windows XP):
 
 C:\myprogramfolder\run Myprogram.exe 1 1 acc 0
 
 
 The executable would execute perfectly.  
 
 
 However, when I would try to execute the following lines of source code
 within a python script file:
 
 import os
 
 os.system(rC:\myprogramfolder\run\Myprogram.exe 1 1 acc 0) 
 
 
 The executable file would start to execute until it would print an error
 stating that it cannot use a (.dat) file, which is located under the
 following directory:  
 
 
 C:\myprogramfolder\run\inputs\io\control.dat
 
 
 I believe I may be missing something here that prevents the executable
 file working within python from utilizing this (.dat).  The printed
 final error is the following:
 
 ERROR opening inputs/io/control.dat
 
 Does anyone know what that could be ??

The program (myprogram.exe) is not looking for
C:\myprogramfolder\run\inputs\io\control.dat, it's looking for
inputs/io/control.dat relative to its current working directory. That
will only work if the current working directory of the program is
C:\myprogramfolder\run. Is it?

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   >