Communicating from Flash to Python
Hi; I have an AS3 script that is supposed to communicate with a python script and I don't think it is. The python script is to email. How can I trouble-shoot this? Beno -- http://mail.python.org/mailman/listinfo/python-list
Re: Communicating from Flash to Python
On Fri, Mar 4, 2011 at 2:57 AM, Godson Gera wrote: > You can use PyAMF http://pyamf.org > Thanks! Beno -- http://mail.python.org/mailman/listinfo/python-list
Absolutely Insane Problem with Gmail
Hi; I have this code: #!/usr/bin/python import sys, os, string import cgitb; cgitb.enable() import cgi cwd = os.getcwd() dirs = string.split(cwd, '/') dirs = dirs[1:-1] backLevel = '/' + string.join(dirs, '/') sys.path.append(cwd) sys.path.append(backLevel) import string form = cgi.FieldStorage() // all the fields here subject = 'Order For Maya 2012' msg = 'First Name: %s\nLast Name: %s\nEmail Address: %s\nAddress2: %s, City: %s\nState: %s\nCountry: %s\nZip: %s\nPhone: %s\nFax: %s\nMessage: %s\n' % (firstNameText, lastNameText, emailText, addrText, addr2Te xt, cityText, stateText, countryText, zipText, faxText, messageText) ### LOOK AT THESE TWO LINES ourEmail = 'myemaila...@gmail.com' ourEmail = 'q...@xxx.com' def my_mail(): emailOne() emailTwo() def emailOne(): from simplemail import Email Email( from_address = ourEmail, to_address = emailText, subject = 'Thank you for your order!', message = msg ).send() def emailTwo(): from simplemail import Email Email( from simplemail import Email Email( # from_address = emailText, # to_address = ourEmail, from_address = ourEmail, to_address = emailText, subject = 'Order for Maya 2012', message = msg ).send() print '''Content-type: text/html ''' my_mail() print ''' ''' Now what's absolutely crazy about this is that if I use my online form and enter my gmail address I get the email confirmations. However, if I get rid of that garbage value for ourEmail and use the other one which is the _very_same_gmail_address I get nothing!! No email. Ditto if I uncomment those lines in emailTwo and delete the next two lines. What on earth could be doing this??? TIA, Beno -- http://mail.python.org/mailman/listinfo/python-list
Re: Absolutely Insane Problem with Gmail
On Sat, Mar 5, 2011 at 11:11 PM, Littlefield, Tyler wrote: > >ourEmail = ' > myemaila...@gmail.com' > > >ourEmail = ' > q...@xxx.com' > > You redefine this twice. > Right. The second definition, of course, overwrites the first. That is deliberate. I simply comment out the second when I'm testing. The second is, of course, bogus. But it works while the first doesn't!!! WHY??? > You also don't define a variable down lower. > ># to_address = ourEmail, > > > from_address = ourEmail, > > to_address = emailText, > I could be wrong, but emailText isn't defined. > No, in fact, emailText *is* defined. And it, too, works, *unless* it's going to a gmail address!! In fact, I just now tested it, commenting out the second bogus email address, and using another gmail address but different than the one defined as ourEmail, and everything works as expected. Therefore, it appears that gmail, for whatever reason, filters out emails send to the same address from which they are sent. Thanks, Beno -- http://mail.python.org/mailman/listinfo/python-list
How Translate This PHP
Hi; How do I translate this PHP code? if($ok){ echo "returnValue=1"; }else{ echo "returnValue=0"; } In other words, when the email successfully sends, send back both the name of the variable and its value. TIA, Beno -- http://mail.python.org/mailman/listinfo/python-list
Re: How Translate This PHP
On Sun, Mar 6, 2011 at 10:53 AM, Noah Hall wrote: > On Sun, Mar 6, 2011 at 2:45 PM, Victor Subervi > wrote: > > Hi; > > How do I translate this PHP code? > > > > if($ok){ > > echo "returnValue=1"; > > }else{ > > echo "returnValue=0"; > > } > > From the code provided - > > if ok: >print 'returnValue=1' > else: >print 'returnValue=0' > Ah. I thought I had to "return" something! Thanks, Beno -- http://mail.python.org/mailman/listinfo/python-list
Re: How Translate This PHP
On Sun, Mar 6, 2011 at 12:00 PM, Noah Hall wrote: > On Sun, Mar 6, 2011 at 3:11 PM, Victor Subervi > wrote: > > Ah. I thought I had to "return" something! > > Well, based on what you asked, you would've, but based on the code, > all it was doing is printing "returnValue - value" > > Of course, a better way of doing it would be to use formatting - > > For example, > > print 'returnValue=%d' % ok > Thanks. Beno -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't Want Visitor To See Nuttin'
On Wed, Mar 9, 2011 at 5:33 PM, Ian wrote: > On 09/03/2011 21:01, Victor Subervi wrote: > >> The problem is that it prints "Content-Type: text/html" to the screen >> > If you can see what is intended to be a header, then it follows that you > are not sending the header correctly. > > Sorry - can't tell you how to send a header. You don't say what framework > you are using. > Framework? Python on CentOS, if that's what you're asking. From what I know of python, one always begins a web page with something like this: print "Content-Type: text/html" print print ''' http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";> and this has worked in the past, so I'm surprised it doesn't work here. Don't understand what I've done wrong, nor why it prints the first line to screen. TIA, Beno -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't Want Visitor To See Nuttin'
On Thu, Mar 10, 2011 at 8:50 PM, Benjamin Kaplan wrote: > > print "Content-Type: text/html" > > print > > print ''' > > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";> > > > > > > > > and this has worked in the past, so I'm surprised it doesn't work here. > > Don't understand what I've done wrong, nor why it prints the first line > to > > screen. > > TIA, > > Beno > > > > Typically, people developing web applications use a framework such as > Django or TurboGears (or web.py or CherryPy or any of a dozen others) > rather than just having the CGI scripts print stuff out. Rather than > having your Python script just print out a page, you make a template > and then have a templating engine fill in the blanks with the values > you provide. They'll also protect you from things like Injection > attacks and cross-site scripting (if you don't know what those are, > you're probably vulnerable to them). > > ok. I'm looking into Django. I'm ok for injections and I think most of my data is sanitized. Now, can someone please address my question? See above. TIA, Beno -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't Want Visitor To See Nuttin'
On Fri, Mar 11, 2011 at 3:54 AM, Ian Kelly wrote: > On Wed, Mar 9, 2011 at 2:01 PM, Victor Subervi > wrote: > > Maya 2012: Transform At the Source > > Yow. You're designing a Maya 2012 website to help some travel company > bilk gullible people out of thousands of dollars? I would be ashamed > to have anything to do with this. > Um...just for the record, these guys have ben featured on the FRONT PAGES OF: The Wall Street Journal The Los Angeles Times The San Francisco Chronicle and have appeared on: Eye-To-Eye with Connie Chung CNN's Travel Guide and National Geographic's Travel Magazine called them "the graddaddy of metaphysical tours." If you'll go to the "About Us" page you'll see their photo with the Dalai Lama. They're ligit :) Beno -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't Want Visitor To See Nuttin'
On Fri, Mar 11, 2011 at 4:26 AM, Dennis Lee Bieber wrote: > On Thu, 10 Mar 2011 18:00:10 -0800 (PST), alex23 > declaimed the following in gmane.comp.python.general: > > > He's comp.lang.python's version of Sisyphus. Or maybe Sisyphus' > > boulder...I forget where I was going with this. > > The boulder -- given that we are the ones suffering... > OK, fine, don't respond. The page works. I'm changing names and email addresses. CU as someone else. Bye, Beno -- http://mail.python.org/mailman/listinfo/python-list
Try/Except/Yield/Finally...I'm Lost :-}
Hi; I am trying to find words in a document that are identical to any word in a vocabulary list, to replace that word with special markup. Let's say the word is "dharma". I don't want to replace the first few letters of, say "dharmawuhirfuhi". Also, to make matters more difficult, if the word "adharma" is found in the document, I need to replace that with special markup, too. (In Sanskrit, "a" preceding a word negates the word.) But I don't want to replace "adharma" and then go off and replace the "dharma" in "adharma", thus having nested markup. Now, I tried separating out all the words in the line (I go through the doc line by line), but then, of course, I lost all the punctuation! So now I have this code: for word in vocab: aword = "a" + word try: line = re.sub(aword, pu_four + aword + pu_five + aword + pu_six, line) except: pass try: line = re.sub(word, pu_one + word + pu_two + word + pu_three, line) except: pass which, of course, ends up breaking all the above! Can someone send me a shovel to dig my way out of this mess? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Why Don't Return?
Hi; Here is sample function: def a(): b() print c def b(): c = "Hi" return c if __name__ == "__main__": a() then run a(). Throws error about c not being defined. How do I return c from b? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Don't Return?
Thanks :) On Dec 3, 2007 6:58 PM, Terry Reedy <[EMAIL PROTECTED]> wrote: > > "Victor Subervi" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > | def a(): > | b() > > Here is the error: should be > c = b() > > | print c > | > | def b(): > | c = "Hi" > | return c > | > | if __name__ == "__main__": > | a() > | > | then run a(). Throws error about c not being defined. How do I return c > from > | b? > > You did, but you did not 'catch' it within a(). See above for change. > > tjr > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Fill In a Form Automatically
Hi; I'm trying to fill in a Zope form automatically. I have this script, which works great for creating the page...but how do I write to it? import urllib2 theurl = 'example.com' protocol = 'http://' my_id = "test" text = "Hello, world!" realm_dir = '/a_dir/' realm1 = 'manage_addProduct/PageTemplates/manage_addPageTemplate?id=' + my_id realm2 = my_id realm3 = my_id + '?content_type=text/html&title=testing' username = 'name' password = 'pass' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, theurl, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) pagehandle = urllib2.urlopen(protocol + theurl + realm_dir + realm1) pagehandle.close() pagehandle = urllib2.urlopen(protocol + theurl + realm_dir + realm2) # data = pagehandle.write() pagehandle.close() TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Fill In a Form Automatically
Thanks! Mechanize looks really cool :)) Victor On Dec 7, 2007 4:11 PM, Ismail Dönmez <[EMAIL PROTECTED]> wrote: > Friday 07 December 2007 22:06:23 tarihinde Victor Subervi şunları > yazmıştı: > > Hi; > > I'm trying to fill in a Zope form automatically. I have this script, > which > > works great for creating the page...but how do I write to it? > > Use Mechanize [0]. > > [0] http://wwwsearch.sourceforge.net/mechanize/ > > -- > Never learn by your mistakes, if you do you may never dare to try again. > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: [Plone-Users] Why Can't I Do This?
...but applicable ONLY for that instance. The other solution provided is more universal ;) On Dec 14, 2007 10:41 AM, Encolpe Degoute <[EMAIL PROTECTED]> wrote: > Victor Subervi a écrit : > > Hi; > > Why can't I do this? > > > >>>> author = "By Juan Garcia" > >>>> if author[0:2] == "by " | "By " | "BY": > > if author[0:2].lower() == "by": > > > -- > Encolpe Degoute > INGENIWEB (TM) - S.A.S 5 Euros - RC B 438 725 632 > 17 rue Louise Michel - 92300 Levallois Perret - France > web : www.ingeniweb.com - « les Services Web Ingénieux » > Tel : 01.78.15.24.08 / Fax : 01 47 57 39 14 > > > - > SF.Net email is sponsored by: > Check out the new SourceForge.net Marketplace. > It's the best place to buy or sell services > for just about anything Open Source. > > http://ad.doubleclick.net/clk;164216239;13503038;w?http://sf.net/marketplace > ___ > Plone-Users mailing list > [EMAIL PROTECTED] > https://lists.sourceforge.net/lists/listinfo/plone-users > -- http://mail.python.org/mailman/listinfo/python-list
Re: [Plone-Users] Why Can't I Do This?
Great! Thanks! On Dec 14, 2007 10:38 AM, Eric Smith <[EMAIL PROTECTED]> wrote: > Victor Subervi wrote: > > Hi; > > Why can't I do this? > > > > >>> author = "By Juan Garcia" > > >>> if author[0:2] == "by " | "By " | "BY": > > ... author = author[3:] > > ... > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: unsupported operand type(s) for |: 'str' and 'str' > > > > This is a python question, not a plone question. The python logical or > operator is "or", but for this you might want to use "in". This code > might point you in the right direction, although it's not a complete (or > very good) solution: > > author = "By Juan Garcia" > if author[0:2] in ["by", "By", "BY"]: > author = author[2:] > print author > > - > SF.Net email is sponsored by: > Check out the new SourceForge.net Marketplace. > It's the best place to buy or sell services > for just about anything Open Source. > > http://ad.doubleclick.net/clk;164216239;13503038;w?http://sf.net/marketplace > ___ > Plone-Users mailing list > [EMAIL PROTECTED] > https://lists.sourceforge.net/lists/listinfo/plone-users > -- http://mail.python.org/mailman/listinfo/python-list
Re: [Plone-Users] Why Can't I Do This?
whatever[0:2] will yield THREE characters, so my "by " is correct and "by" will fail every time :)) Victor On Dec 14, 2007 12:06 PM, Derek Broughton <[EMAIL PROTECTED]> wrote: > Encolpe Degoute wrote: > > > Derek Broughton a écrit : > >> Victor Subervi wrote: > >> > >>> Hi; > >>> Why can't I do this? > >>> > >>>>>> author = "By Juan Garcia" > >>>>>> if author[0:2] == "by " | "By " | "BY": > >>> ... author = author[3:] > >>> ... > >>> Traceback (most recent call last): > >>> File "", line 1, in ? > >>> TypeError: unsupported operand type(s) for |: 'str' and 'str' > >> > >> because | is unsupported, and it doesn't make sense that way. > >> > >> Wouldn't: > >> if author[0:2].lower() == "by": > >> make more sense (btw, that trailing space in your "by " would have made > >> it fail anyway). > > > > Are you sure of this ? > > Yes, because I executed it in python... > > -- > derek > > > - > SF.Net email is sponsored by: > Check out the new SourceForge.net Marketplace. > It's the best place to buy or sell services > for just about anything Open Source. > > http://ad.doubleclick.net/clk;164216239;13503038;w?http://sf.net/marketplace > ___ > Plone-Users mailing list > [EMAIL PROTECTED] > https://lists.sourceforge.net/lists/listinfo/plone-users > -- http://mail.python.org/mailman/listinfo/python-list
How Does This Static Variable Work?
Hi; I read this example somewhere, but I don't understand it <:-) Can someone please explain how static variables work? Or recommend a good how-to? import random def randomwalk_static(last=[1]): # init the "static" var(s) rand = random.random() # init a candidate value if last[0] < 0.1: # threshhold terminator return None # end-of-stream flag while abs(last[0]-rand) < 0.4: # look for usable candidate print '*', # display the rejection rand = random.random() # new candidate last[0] = rand # update the "static" var return rand TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: How Does This Static Variable Work?
Thanks. I'll study that. Victor On Jan 4, 2008 12:34 PM, Neil Cerutti <[EMAIL PROTECTED]> wrote: > On Jan 4, 2008 10:17 AM, Victor Subervi <[EMAIL PROTECTED]> wrote: > > > Hi; > > I read this example somewhere, but I don't understand it <:-) Can > > someone please explain how static variables work? Or recommend a good > > how-to? > > > > > > import random > > > > def randomwalk_static(last=[1]): # init the "static" var(s) > > > > rand = random.random() # init a candidate value > > > > Simulating C's static local variables is the (in)famous application for > this case of optimization in Python's design. > > Consult the following entry in the Python General Programming FAQ for > further information. > > > http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects > > -- > Neil Cerutti > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Unicode Problem
Hi; New to unicode. Got this error: Traceback (most recent call last): File "", line 1, in File "", line 29, in tagWords File "/usr/local/lib/python2.5/codecs.py", line 303, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 9: ordinal not in range(128) I think the problem comes from this code snippet: for line in sentences: print line tup = re.split(' ', line) for word in tup: for key, value in dictionary.items(): if key == word: word = word + '::' + value newLine.append(word) sentences.close() TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Anyone Know Unicode? Help!
Hi; Second post on this. Googling shows many others with same problem, but no answers! Help! New to unicode. Got this error: Traceback (most recent call last): File "", line 1, in File "", line 29, in tagWords File "/usr/local/lib/python2.5/codecs.py", line 303, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 9: ordinal not in range(128) I think the problem comes from this code snippet: for line in sentences: print line tup = re.split(' ', line) for word in tup: for key, value in dictionary.items(): if key == word: word = word + '::' + value newLine.append(word) sentences.close() TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Can´t Surf Python Pages in Windoze
Hi; I try to surf to this code in Windoze and it doesn't work...just posts a small, black screen for a split second. Why? print "Content-Type: text/html" print print """ http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";> http://www.w3.org/1999/xhtml"; xml:lang="en"> Yeah """ Also, Zope is installed, but when I go to: localhost:8080/manage_main or local:8080/Zope-Instance/manage_main I get a 404, after having started the service and everything is go. I have Python up. What gives? Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Can´t Surf Python Pages in Windoze
On 12/26/08, Tino Wildenhain wrote: > > > print "Content-Type: text/html" >> print >> print """ >> > http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";> >> http://www.w3.org/1999/xhtml"; xml:lang="en"> >> >> >> >> Yeah >> >> """ >> > > this could be fine if called in CGI context. Can you state clearly what "CGI context" means¿ Should I be importing a CGI module¿ I pulled this code from a page that was working. If it had an importation of something CGI, I believe I would have tested that with all the other things that were imported that I tested, but perhaps not. I am not at my home computer to test, and will not be back online for a week. I am not worried about Zope now, but the above code, yes. TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Can´t Surf Python Pages in Windoze
On Fri, Dec 26, 2008 at 8:00 PM, Gabriel Genellina wrote: > En Fri, 26 Dec 2008 15:11:44 -0200, Victor Subervi < > victorsube...@gmail.com> escribió: > >> On 12/26/08, Tino Wildenhain wrote: >> > > print "Content-Type: text/html" >>>> print >>>> print """ >>>> >>> http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";> >>>> >>> > I think there should be only one blank line between header and content, you > have two (so the document contains an empty line before the doctype > declaration, and I think this is invalid). > Will try. Thanks. Let you know next week if problem. Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Can´t Surf Python Pages in Windoze
On Fri, Jan 2, 2009 at 4:24 PM, Victor Subervi wrote: > On Fri, Dec 26, 2008 at 8:00 PM, Gabriel Genellina > wrote: > >> En Fri, 26 Dec 2008 15:11:44 -0200, Victor Subervi < >> victorsube...@gmail.com> escribió: >> >>> On 12/26/08, Tino Wildenhain wrote: >>> >> >> print "Content-Type: text/html" >>>>> print >>>>> print """ >>>>> >>>> http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";> >>>>> >>>> >> I think there should be only one blank line between header and content, >> you have two (so the document contains an empty line before the doctype >> declaration, and I think this is invalid). >> > I tried eliminating the second line (print) but it didn´t help. Seems there is a problem with Python on my Windoze box. I reinstalled with no luck. I tried opening a page which should have opened (works fine on my server) with same "black box" problem. Thanks, Victor > > Will try. Thanks. Let you know next week if problem. > Victor > > -- http://mail.python.org/mailman/listinfo/python-list
How Get Name Of Working File
Hi; If I am writing a script that generates HTML, how do I grab the name of the actual file in which I am working? For example, let us say I am working in test.py. I can have the following code: import os dir = os.getcwd() and that will give me the working dir. But what about "test.py"? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Printing Out Called Function Calls
Hi; Due to screwy problems at my server farm that they refuse to fix, I need to call lines that execute code from other files, like this: theContent += `tidBits[i][y][:-2]` but what that returns is this (as an example): tableTop(348,180) when I need it to execute the fn tableTop. What do? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing Out Called Function Calls
> > change server famrs? > Really. But I imagine they are all trash for the price I pay. > > use eval() or exec()? > eval worked, exec no. Thanks! > > andrew > > -- http://mail.python.org/mailman/listinfo/python-list
Eval Problem
Hi: I have this code: x = 1 while x <= bitties: file = open(p + str(x) + ".txt") for line in file: print line print eval(bits[x - 1]) x += 1 which throws this error: [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler mod_python.cgihandler: Traceback (most recent call last): [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler mod_python.cgihandler: File "/usr/lib64/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch\n result = object(req) [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler mod_python.cgihandler: File "/usr/lib64/python2.4/site-packages/mod_python/cgihandler.py", line 96, in handler\n imp.load_module(module_name, fd, path, desc) [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler mod_python.cgihandler: File "/var/www/vhosts/ articles.13gems.com/httpdocs/index_frame.py", line 89, in ?\n print eval(bits[1]) [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler mod_python.cgihandler: File "", line 1 [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler mod_python.cgihandler: tableBottom(348,180) [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler mod_python.cgihandler: ^ [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler mod_python.cgihandler: SyntaxError: invalid syntax However, if I edit out the offending line and add: print tableBottom(348,180) it prints! What´s wrong? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Eval Problem
Yes, Python is dynamic, but my server farm, in this era of big business screwing the client and cutting all services and customer support, uses such crappy hardware that all normal code breaks, so I am forced to find work-arounds. Here is more complete code: ourFile = string.split(__file__, "/") p = ourFile[len(ourFile) - 1] p = p[: - 9] site = ourFile[4] bitsFile = p + ".bits" bitties = 0 bits = [] Above, I define a bits file with bits of code that the broken python interpreter will not evaluate with normal text, so must be separated into its own file and called line by line and blended with separated files that quote only text. Pain in the hind end ;) try: file = open(bitsFile, "r") for line in file: if len(line) > 2: bits.append(line) bitties += 1 except: pass x = 1 while x <= bitties: file = open(p + str(x) + ".txt") for line in file: print line print eval(bits[x - 1]) x += 1 I have excluded the code where I call the separate text files for printing normal text. They work. It's my code that I cannot get to work. For example, if I take out the "eval" part of the above, it will nicely print the commands, such as this: tableTop(123,456) which is supposed to call said fn. If I place that line in the file calling the text files and the bits file it will execute just fine, but that inevitably makes my job harder. Ideas? TIA, Victor On Mon, Apr 6, 2009 at 6:37 PM, J. Clifford Dyer wrote: > On Mon, 2009-04-06 at 15:11 -0400, Victor Subervi wrote: > > Hi: > > I have this code: > > > > x = 1 > > while x <= bitties: > > file = open(p + str(x) + ".txt") > > for line in file: > > print line > > print eval(bits[x - 1]) > > x += 1 > > > > which throws this error: > > > > [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] > > PythonHandler mod_python.cgihandler: Traceback (most recent call > > last): > > [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] > > PythonHandler mod_python.cgihandler: File > > "/usr/lib64/python2.4/site-packages/mod_python/apache.py", line 299, > > in HandlerDispatch\n result = object(req) > > [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] > > PythonHandler mod_python.cgihandler: File > > "/usr/lib64/python2.4/site-packages/mod_python/cgihandler.py", line > > 96, in handler\n imp.load_module(module_name, fd, path, desc) > > [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] > > PythonHandler mod_python.cgihandler: File > > "/var/www/vhosts/articles.13gems.com/httpdocs/index_frame.py", line > > 89, in ?\n print eval(bits[1]) > > [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] > > PythonHandler mod_python.cgihandler: File "", line 1 > > [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] > > PythonHandler mod_python.cgihandler: tableBottom(348,180) > > [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] > > PythonHandler mod_python.cgihandler: ^ > > [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] > > PythonHandler mod_python.cgihandler: SyntaxError: invalid syntax > > > > Hmm. That's not the problem I get. For me, your code raises: > "NameError: name 'bitties' is not defined" > > It's easier for us to help you if you present a self-contained piece of > code that exhibits the problem you've encountered. Creating that code > will often reveal the problem with the original code, and you will have > solved your own problem. > > The other problem with your code is that you are using eval. Eval leads > to difficult-to-debug errors, and is usually unnecessary, given the > dynamic nature of python. If you need to access a class method using a > string, you can use getattr. If you need to dynamically select a > function based on some condition known in another variable, you can use > a dictionary to hash into the function. > > It's hard to say what might be appropriate for your situation, because > your code fragment is so... fragmentary. > > Cheers, > Cliff > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom Classes?
On 5/9/08, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > > En Thu, 08 May 2008 12:33:55 -0300, Victor Subervi < > [EMAIL PROTECTED]> escribió: > > Okay, trying this again with everything working and no ValueError or any > > other errors, here we go: > > > > getpic = "getpic" + str(w) + ".py" > > > > Why do you *generate* the getpicNN.py? It contains always the same code, > why don't you just use a single getpic.py? > > and then surf to: > > http://whatever.url/getpic20.py?id=6&x=1 > > Because I initially could not get it to work that way...and then I forgot about it. But you are right. That is what I need to do. So I will work on that. Uhm, I don't think there is something specific for this list. There is an > article from E.S.Raymond "How to ask questions the smart way?" that you can > find with Google Thanks. Got it. Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom Classes?
I remember why I had the number with the getpic. It is because I display several of these images on a single page, and apparently I cannot call the same script and get more than one image from an HTML page. Victor On Fri, May 9, 2008 at 10:26 AM, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > En Thu, 08 May 2008 12:33:55 -0300, Victor Subervi < > [EMAIL PROTECTED]> escribió: > > Okay, trying this again with everything working and no ValueError or any > > other errors, here we go: > > > > getpic = "getpic" + str(w) + ".py" > > > > Why do you *generate* the getpicNN.py? It contains always the same code, > why don't you just use a single getpic.py? > > and then surf to: > > http://whatever.url/getpic20.py?id=6&x=1 > > > > Why don't you post the error you get instead...? Including the complete > exception report. > > Also, please re-send the link on how to post good questions to the list. I > > cannot find it. > > > > Uhm, I don't think there is something specific for this list. There is an > article from E.S.Raymond "How to ask questions the smart way?" that you can > find with Google > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom Classes?
Well, you are right. It looks like one of those instances where I fixed something and did not check to see if it influenced the problem now at hand. Thanks again. Victor On 5/15/08, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > > En Tue, 13 May 2008 15:10:21 -0300, Victor Subervi < > [EMAIL PROTECTED]> escribió: > > I remember why I had the number with the getpic. It is because I display >> several of these images on a single page, and apparently I cannot call the >> same script and get more than one image from an HTML page. >> > > That's not true. If you still have the example I posted a few weeks ago, > you can use this script to show a full listing of all uploaded pictures. > It's a small variation of album.py. > I think you were saving the pictures on disk - DON'T do that. It's > unnecesary, wastes time and disk space, and if not done properly one request > interferes with the other. > > -- > Gabriel Genellina > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Simplify Code
Hi; Forgive multiple posts in one day: online very infrequently I set the following variables: # Headers are kept in order to determine nesting of chapters # They are labeled according to font size h36 = '' h26 = '' h22 = '' h18 = '' h14 = '' h12 = '' header_sizes = [36, 26, 22, 18, 14, 12] # Size is the font size of the header size = 0 I write code that grabs the size var. Then I have the following very laborious spaghetti code: if size == 36: h36 = line h26 = '' h22 = '' h18 = '' h14 = '' h12 = '' elif size == 26: h26 = line h22 = '' h18 = '' h14 = '' h12 = '' elif size == 22: h22 = line h18 = '' h14 = '' h12 = '' elif size == 18: h18 = line h14 = '' h12 = '' elif size == 14: h14 = line h12 = '' elif size == 12: h12 = line else: # THROW ERROR! I would like something more elegant, like this: # del is used to determine if should reset the lower header values to '' del = 0 for header_size in header_sizes: if header_size == size: # The following line is ILLEGAL h + string(header_size) = line del = 1 if del = 1 # The following line is ILLEGAL h + string(header_size) = '' How can I rewrite those illegal lines, such that I can create the proper name for the variable, and write the necessary data? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Type Problem
Hi; Forgive multiple posts in one day: online very infrequently Why am I getting this error? import os dir_dict = {6:36, 5:26, 4:22, 3:18, 2:14, 1:12} cur_dir = os.getcwd() dirs = os.path.split(cur_dir) len = len(dirs) type(len(dirs)) Traceback (most recent call last): File "", line 1, in type(len(dirs)) TypeError: 'int' object is not callable Forgot to bring it with me, but type(len) gives me an intelligent response. TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Characters Being Misread
Hi; Forgive multiple posts in one day: online very infrequently I'm having the darndest time trying to figure out how the character '\b0' is being read in "('\x0c')" >>> test = re.search('(?<=\\b)[0]', '\x0c0') >>> test.group(0) '0' >>> type('\x0c') >>> import binascii >>> binascii.unhexlify('\x0c') Traceback (most recent call last): File "", line 1, in binascii.unhexlify('\x0c') TypeError: Odd-length string What gives here? Here's another one: >>> rtf_markup = '\viewkind4\\uc1\\pard\nowidctlpar\\qc\\i\x0c0\x0cs36' >>> a = [] >>> a.append(re.compile('\\i').match(rtf_markup, 1)) >>> a [<_sre.SRE_Match object at 0x011802F8>] >>> a = [] >>> a.append(re.compile('\\qc').match(rtf_markup, 1)) [None] What's the problem? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Simplify Code
Thanks. That worked. Victor On 7/16/08, Alexandr N Zamaraev <[EMAIL PROTECTED]> wrote: > > header_sizes = (36, 26, 22, 18, 14, 12) > if x not in header_sizes: > raise Exception() > else: > h36, h26, h22, h18, h14, h12 = tuple( >line if x == size else '' for x in header_sizes) > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Windows Interpreter
Hi: I would like to make my windows python interpreter work like my linux one. I want to be able to cut and paste multiple lines of code. Now I can only paste one line at a time. I do not want it to indent automatically. How can I change this? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
RTF Parsing
Hi; I have this code: def a(): chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', '\\yz'] rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the Beast? Who can wage war against him?\par' for char in chars: c = '(?<=' + char + ')' test = re.search(c, rtf_markup) try: junk = test.group(0) print char except: pass which gives this result: >>> a() \qc \b0 \i \u \b >>> which makes no sense at all. I expected this: >>> a() \qc \i >>> Why do I get more than that? Also, if I change this line thus: c = '(?<=' + char + ')[0 ]' I get this result: >>> a() \b >>> Why? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Interpreter
def a(): chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', '\\yz'] rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the Beast? Who can wage war against him?\par' for char in chars: c = '(?<=' + char + ')' test = re.search(c, rtf_markup) try: junk = test.group(0) print char except: pass Now, I can paste that entire fn in linux. But in windows I have to paste it line_by_line. Pain in butt! And it indents automatically. How change that behavior. TIA, Victor On 7/29/08, Tim Golden <[EMAIL PROTECTED]> wrote: > > Victor Subervi wrote: > >> Hi: >> I would like to make my windows python interpreter work like my linux one. >> I want to be able to cut and paste multiple lines of code. >> > > You can already do this: what are you trying which isn't working? > > Now I can only paste one line at a time. I do not want it to indent >> automatically. How can I change this? >> > > I realise this is a difficult thing to describe in words, > but I regularly cut and paste multiple lines of code > into my Python interpreter and it doesn't indent automatically. Can you > give some specific examples of what you do and what does or doesn't work? > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Interpreter
I´ll try that. Back online in a week. Victor On 7/29/08, Tim Golden <[EMAIL PROTECTED]> wrote: > > Victor Subervi wrote: > >> def a(): >> chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', >> '\\yz'] >> rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the >> Beast? Who can wage war against him?\par' >> for char in chars: >>c = '(?<=' + char + ')' >>test = re.search(c, rtf_markup) >>try: >> junk = test.group(0) >> print char >>except: >> pass >> >> Now, I can paste that entire fn in linux. But in windows I have to paste >> it line_by_line. Pain in butt! And it indents automatically. How change that >> behavior. >> > > Well, I'm not really sure what to say. I've just copied that > whole section with drag-mouse, Ctrl-C. I then opened a new > interpreter window (effectively, Start > Run > python) and > right-clicked over the window. At this point, the lines I > copied were copied in and the function accepted by the > interpreter. > > I do have QuickEdit on by default in all by console windows, > but the only difference I expect that to make is that you'd > otherwise have to use the window's System Menu (Alt-Space, > Edit, Paste). > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Cutting and Pasting in Windows IDLE
Hi; A couple of weeks ago I asked how to cut and paste multiple lines in the Windows IDLE interface. I can only paste one line at a time! Frustrating. I want it to work like my Linux interpreter. Why doesn´t it? Please help. Someone wrote this, which did not help at all: Well, I'm not really sure what to say. I've just copied that whole section with drag-mouse, Ctrl-C. I then opened a new interpreter window (effectively, Start > Run > python) and right-clicked over the window. At this point, the lines I copied were copied in and the function accepted by the interpreter. I do have QuickEdit on by default in all by console windows, but the only difference I expect that to make is that you'd otherwise have to use the window's System Menu (Alt-Space, Edit, Paste). TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Adding Images to MySQL
Hi; I´m trying to figure out how to upload images into a MySQL database. (Yes, that is what I want to do.) I have a form that asks for data, like this: 1ra Foto Pequeña: Then I send that form to a python script that processes like this: cursor.execute('insert into products (' + col_names + ') values (' + col_values + ');') where col_names is all the names of the columns and col_values, obviously, the values. Works fine for strings and digits. Not so well for files :) What do? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding Images to MySQL
I have tried the following code: #!/usr/local/bin/python import _mysql import MySQLdb host = 'mysqldb2.ehost-services.com' user = 'user' passwd = 'pass' db = 'bre' print 'Content-Type: image/jpeg\r\n' print '\nHi!\n' db=MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) c=db.cursor() imgfile=open("1.jpg",'rb') f = imgfile.read() sqlstr="insert into photo (id, img) values ('1', '" + _mysql.escape_string(imgfile.read()) +"');" c.execute(sqlstr) imgfile.close() c.close() print '\nBye!\n' which prints Hi! but not Bye! and gives me an HTTP 200 error. I threw the line f = imgfile.read() in there just to make sure it is reading the imgfile. Also, I tested it with all the import statements alone to make sure it was importing everything. So the problem is the c.execute statement. Please advise. TIA, Victor On Tue, Apr 1, 2008 at 1:37 PM, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > En Tue, 01 Apr 2008 09:36:00 -0300, Victor Subervi > <[EMAIL PROTECTED]> escribió: > > > Hi; > > I´m trying to figure out how to upload images into a MySQL database. > > (Yes, > > that is what I want to do.) I have a form that asks for data, like this: > > 1ra Foto Pequeña: > > > > Then I send that form to a python script that processes like this: > > cursor.execute('insert into products (' + col_names + ') values (' + > > col_values + ');') > > where col_names is all the names of the columns and col_values, > > obviously, > > the values. Works fine for strings and digits. Not so well for files :) > > What > > do? > > Always use bound parameters - not only it's easier and less error prone, > it's safer too. How parameters are specified depends on the DBAPI module > you're using - read the module documentation. I think MySQLdb accept > dictionary-like marks: > > values = {'name': 'Red jar', > 'descr': 'A nice red jar', > 'pic': binary(picdata) > } > cursor.execute('''insert into products (name,description,picture) > values (%(name)s, %(descr)s, %(pic)s);''', values) > > See PEP249 http://www.python.org/dev/peps/pep-0249/ and the documentation > for your database module. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Strange MySQL Problem...
Hi; I have this code which works fine: #!/usr/local/bin/python import _mysql import MySQLdb, cPickle host = 'mysqldb2.ehost-services.com' user = 'user' passwd = 'pass' db = 'bre' print 'Content-Type: image/jpeg\r\n' print '\nHi!\n' connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) imgfile=open("1.jpg",'rb') f = imgfile.read() cursor = connection.cursor() cursor.execute("CREATE TABLE justatest (name TEXT, ablob BLOB)") names = 'aramis', 'athos', 'porthos' data = {} for name in names: datum = list(name) datum.sort() data[name] = cPickle.dumps(datum, 1) sql = "INSERT INTO justatest VALUES (%s, %s)" cursor.execute(sql, ('ramis', _mysql.escape_string(f)) ) imgfile.close() connection.close() print '\nBye!\n' Now, if I take out this part, which I can´t see does anything at all in the code, it no longer works: names = 'aramis', 'athos', 'porthos' data = {} for name in names: datum = list(name) datum.sort() data[name] = cPickle.dumps(datum, 1) Why? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange MySQL Problem...
Comments in line... On Thu, Apr 3, 2008 at 12:35 AM, John Nagle <[EMAIL PROTECTED]> wrote: > Steve Holden wrote: > > Define "no longer works". > Sorry. Throws HTTP 200 error. On Thu, Apr 3, 2008 at 12:35 AM, John Nagle <[EMAIL PROTECTED]> wrote: > John Nagle wrote: > > "works fine"? Please check again... > > The same remarks I've posted earlier apply here. > Must have missed those. Yes, the code works fine. Repeatedly. > > >In addition, you're not committing the database update. > You need to do > >connection.commit() Oh, thanks :) > > > after updating. > >In general, server side programs should have a try-block > wrapped around most of the program, with some code to display or > log errors in some useful way. Curious. Why? During testing, I understand, but after testing, why? On Thu, Apr 3, 2008 at 12:35 AM, John Nagle <[EMAIL PROTECTED]> wrote: > Gabriel Genellina wrote: > > > print 'Content-Type: image/jpeg\r\n' > > print '\nHi!\n' > > Don't you see a conflict among those two lines? > (You're a liar: first you promise to send a nice picture and then you only > send a letter!) > LOL! Okay, make me honest ;) I want to post both text and images. What use? > > > > cursor.execute("CREATE TABLE justatest (name TEXT, ablob BLOB)") > > Note that you *always* attempt to create a table. > Yeah, I am dropping it, too. This was just some code I found online and tweaked. > > > > sql = "INSERT INTO justatest VALUES (%s, %s)" > > cursor.execute(sql, ('ramis', _mysql.escape_string(f)) ) > > You're using bound parameters now, a good thing. There is no need to > escape strings passed as parameters - in fact, it is wrong, as the adapter > will escape the text again. > In this case, the column is a BLOB, and you have to use the Binary > function: MySQLdb.Binary(f) > Nope. Threw me another HTTP 200. > > Now, if I take out this part, which I can´t see does anything at all in > > the > > code, it no longer works: > > I don't think "it no longer works" because you removed anything, but > because this script can only be run at most once. Probably you're getting > an error in the CREATE TABLE statement. > Wrong. I check the mysql and drop the table if the code throws me an HTTP 200 error. I have run this code many times now. That is what makes the whole thing so ridiculously strange to me. That code snippet, that the script insists on, is a relic from the code I tweaked. It was there to make a binary, that is all. So why do I still need the darn thing?? > > You have to look at the server error logs, else you're blind fighting. > I am blind fighting. No longer run my own server, no longer have root access. > See > other suggestions in my previous post. > Sorry. Can you repost it? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange MySQL Problem...
On Thu, Apr 3, 2008 at 9:34 AM, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > En Thu, 03 Apr 2008 09:43:57 -0300, Victor Subervi > <[EMAIL PROTECTED]> escribió: > > >> Steve Holden wrote: > >> Define "no longer works". > > Sorry. Throws HTTP 200 error. > > HTTP 200 means OK. Yes. But there is an error somewhere, because it doesn´t run all the code. For example, I have to manually drop the table. > > > >> > The same remarks I've posted earlier apply here. > > Must have missed those. Yes, the code works fine. Repeatedly. > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/b732eee4e91b1868/ Thank you. I believe you mean by bound, something like this, right? binary(picdata) I am now doing that, if I am not mistaken. > display or *log* errors... Yeah. There are always errors... > *post*? This is the server response. Return either text *or* an image (the > text may be an html referencing the image) Yes, post. But what do I write instead of this? print 'Content-Type: image/jpeg\r\n' > Test it locally (just the database thing, no web), test the cgi script > without database interaction, only then join the two. Okay, but how do I upload an image into mysql without a script? And once I can do that, everything´s (almost) solved! > But you can read the server logs at least? I am new to Plesk. I discovered I can read logs. More following... > > Your code is throwing exceptions but you're not seeing them. Use the cgitb > module http://docs.python.org/lib/module-cgitb.html Now here you give me another laugh :) I added this line to the script import cgitb; cgitb.enable() and suddenly I can take out these junk lines that were throwing the HTTP 200 error: names = 'aramis', 'athos', 'porthos' data = {} for name in names: datum = list(name) datum.sort() data[name] = cPickle.dumps(datum, 1) Is this some kind of magic wand? :) Okay, where I am at now... I have a script called start.py which has this code in it: import cgitb; cgitb.enable() import MySQLdb import struct import _mysql, sys Lots of imports, just to try things out. Most not needed... col_names = ['id', 'name_en', 'name_es', 'name_it', 'category', 'title_en', 'title_es', 'title_it', \ 'description_en', 'description_es', 'description_it', 'price', 'bedrooms', 'bathrooms', 'pic1', 'sort_factor'] Just notice the pic1 there... Then I make a nice list of colnames like MySQL wants... col_names_with_commas = '' for name in col_names: col_names_with_commas += name + ', ' count = len(col_names_with_commas)-2 col_names_with_commas = col_names_with_commas[0:len(col_names_with_commas)-2] All that I have checked, it is good... Here is the sticky point: for id in ids: for d in id: print '\n' cursor.execute('select ' + col_names_with_commas + ' from products where id = ' + str(d) + ';') col_fields = cursor.fetchall() i = 0 x = 0 for field in col_fields[0]: if x == 0: # This is the ID field i += 1 check = 'check' + str(i) print '\n' if x == 15: print '', field, '\n' else: print '', field, '\n' x += 1 I have to do both of those for statements. The sticky point is in the last if statement. 15 is the pic1 field. Should I use binary(field) instead? It does not like that. I send the whole thing over to another script which has this: import cgitb; cgitb.enable() import MySQLdb import cgi import struct Same old same old... Here´s the sticky part... if what_do == 'insert': data = ['', '', '', '', '', '', '', '', '', '', '', 0.0, '', '', '', 500] the_form(data, what_do) elif what_do == 'update': cursor.execute('select * from products where id=' + update_these[0] + ';') data = cursor.fetchall() the_form(data[0], what_do) And then try to render... 1ra Foto Grande: I show you both parts, because the Internal Server Error comes from the second page, but the logged error points to the first page. Here is the log record... [Thu Apr 03 09:53:33 2008] [error] [client 190.166.0.65] PythonHandler mod_python.cgihandler: File "/var/www/vhosts/ livestocksling.com/httpdocs/test/python/Shop/iud.py", line 210, in the_form\n print '"', binary(data[14]), '"', referer: http://livestocksling.com/test/python/Shop/start.py [Thu Apr 03 09:53:33 2008] [error] [client 190.166.0.65] PythonHandler mod_python.cgihandler: NameError: global name 'binary' is not defined, referer: http://livestocksling.com/test/python/Shop/start.py TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding Images To MySQL
>* *(What a mess! I don't know where to begin...) Yeah. Never claimed to be any good at this :( Just persistent :) >* *- You say Content-Type: image/jpeg but you emit HTML code. You're lucky if you see any >* *text at all. Well, I tried Content-Type: text/html and that threw an HTTP 500 Error. >* *- HTTP 200 is not an error, it means the request was successful. When it doesn´t execute the code, how can it be called successful? If it doesn´t execute the code, how can you say it´s not an error? What is it, then? >* *- As a general advice, try to isolate the problems. Test the database stuff alone, in a local >* *application. Test the cgi script alone, without database interaction. Test the database stuff in >* *the web server (better if you have a shell account). Merge all and test again. Very good advice. Please help me understand how to do that. This is what I have done. I have tried these: sql = "'insert into products (" + col_names + ") values (" + val + ")', (" + col_names + ")" cursor.execute(sql) and sql = "'insert into products (" + col_names + ") values (" + val + ")'" cursor.execute(sql, (col_names,)) Neither work. However, if I print what that code spits out: sql = "'insert into products (" + col_names + ") values (" + val + ")', (" + col_names + ")" print sql then copy and paste it into a cursor.execute() statement, viola! Everything works _just_fine_. Go figure. Why?? Incidentally, all that is without using images, and obviously since it posted to the database after copying and pasting, I believe I am dealing only with a python problem. Now, concerning images, this is what I have so far. I put an image on the server, and did this: imgfile=open("1.jpg",'rb') f = imgfile.read() pic1 = _mysql.escape_string(f) It does not like this (forgot error): pic1 = MySQLdb.Binary(f) Escaping the string, I can successfully load this image into the database, along with all the other fields. Now, when I load an image from the form on the previous page with this code: -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding Images To MySQL
in line... On 4/5/08, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > > En Sat, 05 Apr 2008 11:32:00 -0300, Victor Subervi > <[EMAIL PROTECTED]> escribió: > > >> * *- You say Content-Type: image/jpeg but you emit HTML code. You're > >> lucky > > if you see any > > > >> * *text at all. > > > > Well, I tried Content-Type: text/html and that threw an HTTP 500 Error. > > If your script raised any exception, that's the expected code. (500 = > internal error = your code has errors). But it's not very useful for > debugging; using cgitb or wrapping the code in try/except as has already > been suggested, lets you see the exception and traceback. Yes, and I have employed your suggestion of cgtib, and I sent you personally under separate cover the errors, since I forgot to include them in this post. >> * *- HTTP 200 is not an error, it means the request was successful. > > > > When it doesn´t execute the code, how can it be called successful? If it > > doesn´t execute the code, how can you say it´s not an error? What is it, > > then? > > Well, your web server thinks all went ok... BTW, you did't provide details > about it, I *guess* you're using CGI because of the print "Content-Type" > line. Yes, that is correct... >> * *- As a general advice, try to isolate the problems. Test the database > > stuff alone, in a local > >> * *application. Test the cgi script alone, without database > interaction. > > Test the database stuff in > >> * *the web server (better if you have a shell account). Merge all and > >> test > > again. > > > > Very good advice. Please help me understand how to do that. > > > > This is what I have done. I have tried these: > > > > sql = "'insert into products (" + col_names + ") values (" + val + ")', > > (" + > > col_names + ")" > > > > cursor.execute(sql) > > > > and > > > > sql = "'insert into products (" + col_names + ") values (" + val + ")'" > > > > cursor.execute(sql, (col_names,)) > > > > Neither work. > > You got a syntax error, I guess. What's that ' at the start? > I'll try to explain it from the ground up. This would be a valid SQL > statement:: > > insert into PRODUCTS (PRODID, NAME, DESCRIPTION) > values (123, 'Easter egg 80g', 'A longer description'); > > In Python, you need the SQL text inside a string:: > > sql = "insert into PRODUCTS (PRODID, NAME, DESCRIPTION) " \ > "values (123, 'Easter egg 80g', 'A longer description');" > > and you can execute it with:: > > cursor.execute(sql) > > That would be OK when you create the database for the first time. Later > your boss comes in and says: "We've got bigger eggs! Code 124, 150g each. > We need them in the database". You write an sql statement similar to > above. Some days later, they decide to sell bubble gum. Forty-two > different sizes and flavors and brands. You don't want to write all that > sql statements by hand. Your first thought is to build the sql text by > pieces:: > > sql = "insert into PRODUCTS (PRODID, NAME, DESCRIPTION) " \ > "values ("+str(prodid)+", '"+prodname+"', '"+description+"');" > > But then you remember to have read something about sql injection and you > don't like that mess of " + ) ' ( anyway. After reading some articles > about DBAPI 2, PEP 249, the MySQLdb module, you write this:: > > sql = "insert into PRODUCTS (PRODID, NAME, DESCRIPTION) " \ > "values (%s,%s,%s);" > cursor.execute(sql, (prodid, prodname, description)) > > and it works fine. > > Note that execute has two arguments: first, a string with the sql > statement text; second, a tuple containing the values. The %s in the sql > text are placeholders, they're replaced with the corresponding value from > the second argument. And there is no ' anywhere. Well, what I did, that now works, was essentially what you suggested, and simply assigned null values to variables that accept null values in the database. That works. What I was trying to do was build up just those variables that were to be updated or entered, and supply only those arguments. At this point it is rather academic, but can that be done? > However, if I print what that code spits out: > > > > sql = "'insert into products (" + col_names + ") val
String Literal to Blob
Hi: I am able (finally) to upload an image to the database. However, when I try to retrieve it, I get a string literal. Here is my code: #!/usr/local/bin/python import cgitb; cgitb.enable() import MySQLdb def test(): host = 'mysqldb2.ehost-services.com' user = 'user' passwd = 'pass' db = 'bre' db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) cursor= db.cursor() cursor.execute('select pic1 from products where id="3";') content = cursor.fetchall() # print 'Content-Type: image/jpeg\r\nContent-Length: %d\n' % len(content) print 'Content-Type: image/jpeg\r\n' print '\n' print content print '\n' cursor.close() test() (Apparently, Plesk doesn´t like if __name__ == '__main__': ) The commented out line gives me a leading less than sign...and that´s it. What do? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
Thanks. I apparently am printing some holder for the image. I stripped out most of it with this content[0][0] but then I am left with this: array('c', '\xff\xd8\xff\xe0\\0\x10JFI...) How do I extract an image from that? TIA, Victor On Tue, Apr 8, 2008 at 11:15 AM, Steve Holden <[EMAIL PROTECTED]> wrote: > Victor Subervi wrote: > > Hi: > > I am able (finally) to upload an image to the database. However, when I > > try to retrieve it, I get a string literal. Here is my code: > > > > #!/usr/local/bin/python > > import cgitb; cgitb.enable() > > import MySQLdb > > def test(): > > host = 'mysqldb2.ehost-services.com < > http://mysqldb2.ehost-services.com>' > > user = 'user' > > passwd = 'pass' > > db = 'bre' > > db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) > > cursor= db.cursor() > > cursor.execute('select pic1 from products where id="3";') > > content = cursor.fetchall() > > # print 'Content-Type: image/jpeg\r\nContent-Length: %d\n' % > len(content) > > print 'Content-Type: image/jpeg\r\n' > > print '\n' > > print content > > print '\n' > > cursor.close() > > > > test() > > (Apparently, Plesk doesn´t like if __name__ == '__main__': ) > > The commented out line gives me a leading less than sign...and that´s > > it. What do? > > TIA, > > Victor > > > Your headers indicate you intend to serve a JPEG image, so you should > *not* then include HTML. Take a look at the HTML of a web page with an > image inside it (look for the tag) and you will see that > HTML pages reference images as separate web resources. > > Thus once you have printed out your HTML headers you should them > immediately send the contents of the database column. > > regards > Steve > -- > Steve Holden+1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
On Wed, Apr 9, 2008 at 1:14 AM, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > > Thanks. I apparently am printing some holder for the image. I stripped > > out > > most of it with this > > content[0][0] > > but then I am left with this: > > > > array('c', '\xff\xd8\xff\xe0\\0\x10JFI...) > > How do I extract an image from that? > > print content.tostring() Now *that* gave me something that *looks* a lot more like an image from a programmers perspective, but still no image... ÿØÿàJFIF... Actually, it does not copy and paste well, but you can see it for the moment here: http://livestocksling.com/test/python/Shop/display_es2.py So, how do I convert *that* to a real live image? > Or perhaps, replace that line with content.tofile(sys.stdout) Printed nothing. > >> > print 'Content-Type: image/jpeg\r\n' > >> > print '\n' > >> > print content > >> > print '\n' > >> > cursor.close() > >> > > >> > test() > > >> > The commented out line gives me a leading less than sign...and that´s > >> > it. What do? > > Try to understand now *why* you got a single character with your previous > code. No clue :/ BTW, for purposes of documentation, it appears that, when sending the form with the image to the script that processes the form, the following is inadvisable: form = cgi.FieldStorage() pic1 = form.getfirst('pic1', '') This appears to work better: form = cgi.FieldStorage() imgfile=open("pixel.gif",'rb') pixel = imgfile.read() pic1 = form.getfirst('pic1', pixel) because it gives a binary default. The string appears to screw things up. Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
On Wed, Apr 9, 2008 at 10:24 AM, Steve Holden <[EMAIL PROTECTED]> wrote: > Victor Subervi wrote: > > On Wed, Apr 9, 2008 at 1:14 AM, Gabriel Genellina > > <[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>> wrote: > > Now all you have to do is what I told you in the first place, which is > to remove the print statements before and after "print content". That is what I figured after I sent the email. However, I had tried that with a test script and the working script, with bad results. Here is the test script that should have worked flawlessly: #! /usr/bin/python import MySQLdb print "Content-type: image/jpeg\r\n" host = 'host' db = 'bre' user = 'user' passwd = 'pass' connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) cursor = connection.cursor() cursor.execute('select img from photo where id="7";') content = cursor.fetchall() print "Content-Type: image/jpeg\nContent-Length: %d\n" % len(content) print content connection.commit() connection.close() This prints out the URL as an image! No idea why. But it does not produce the desired image. The following is the heart of the script for display. I tried entering the Content-type where indicated, but it produces everything up to the image, then produces the result of code from the exception... cursor.execute('select id from products where category="' + category + '" order by sort_factor desc, price desc;') ids = cursor.fetchall() if len(ids[0]) != 0: for id in ids: for d in id: print '\n' cursor.execute('select * from products where id = ' + str(d) + ';') col_fields = cursor.fetchall() if lang == 'es': print 'ID: ', col_fields[0][0], '' print 'Nombre: ', col_fields[0][2], '' print 'Título: ', col_fields[0][6], '' print 'Descripción: ', col_fields[0][9], '' print 'Precio: ', col_fields[0][11], '' print 'Recámaras: ', col_fields[0][12], '' print 'Baños: ', col_fields[0][13], '' content = col_fields[0][14].tostring() print "Content-Type: image/jpeg\nContent-Length: %d\n" % len(content) print content, '' ... except: if lang == 'es': print 'Lo siento. Todavía no tenemos propiedades para enseñarse en la categoría de ', category, '.\n' > You are NOT generating HTML, you are generating a JPEG image. I am producing both, and this is causing me confusion. BTW, when we are finally done with this, I will write a nice how-to (since there is not one in python, while php has some nice ones) on how to do this, and give you and Gabrielle all your due credit. I will post it to this list, because that is sure to rank highly in google right away. Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
On Wed, Apr 9, 2008 at 11:10 AM, Steve Holden <[EMAIL PROTECTED]> wrote: > Victor Subervi wrote: > > > On Wed, Apr 9, 2008 at 10:24 AM, Steve Holden <[EMAIL PROTECTED] > [EMAIL PROTECTED]>> wrote: > > connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) > > cursor = connection.cursor() > > cursor.execute('select img from photo where id="7";') > > content = cursor.fetchall() > > > > Bzzt! Nope. Cursor.fetchall() returns a list (length 1) or tuples (length > 1) here, so this should be > > content = cursor.fetchall()[0][0] > > or, perhaps better > > content = cursor.fetchone()[0] I tried both of these, and they, too, gave me the same identical image of the url, not the image I am after. > > > You really don't understand how the web works, do you? I am just really, really, stupid, Steve. Please forgive me for being so stupid. But I am persistent. And I have built dozens of Web site with images. > In order to include an image in a page your browser must make TWO > requests. The first is for an HTML page that will reference the image in > this way: > >http://your URL here"> > > Seeing this img tag causes the browser to make a SECOND request, which the > script I corrected above should respond to with an image. > > The bytestream is critical in the image response. Even one misplaced byte > will mess things up terribly. In my stupidity, I have assumed you meant this: content = col_fields[0][14].tostring() print '' Obviously I am wrong. Could you please give me a little more insight? > BTW, when we are finally done with this, I will write a nice how-to (since > > there is not one in python, while php has some nice ones) on how to do this, > > and give you and Gabrielle all your due credit. I will post it to this list, > > because that is sure to rank highly in google right away. > > Victor > > > > That's great, though hardly the point of the exercise. I think Google > already know about Gabriel (*not* Gabrielle) and me already ... Well, I just thought it might be a good way to get the information out, since it is not out there yet. And I believe it is only proper to give credit where credit is due. I would not be doing this to praise you. Rather, I would be doing this because it is needed, and I would feel wrong for not crediting those who deserve credit. Please let me know, however, if you feel otherwise. TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
On Wed, Apr 9, 2008 at 12:51 PM, Steve Holden <[EMAIL PROTECTED]> wrote: > Victor Subervi wrote: > > > On Wed, Apr 9, 2008 at 11:10 AM, Steve Holden <[EMAIL PROTECTED] > [EMAIL PROTECTED]>> wrote: > > > > I'm having a problem believing this, but I don't think you are lying. > Are you *sure* you have stored the correct omages in your database? Well, the Plesk PHP/MySQL interface indicates that a blob has been successfully stored. Furthermore, the output I get has strings like either 'Adobe Photoshop' or 'GIMP', depending on the editor I used. And the output is like I have seen before from incorrectly rendered images. And images are what I loaded into those fields through my form. So I believe they are indeed images. > The fact remains that cursor.fetchall() will return a list containing one > tuple containing (what you believe is) your image, so there is NO way your > code above can do what you want. Right. I used your suggestion of cursor.fetchall()[0][0] and the result was *still* the image of the url. (I also used the other suggestion.) > > > I can therefore only assume that this is a CGI script and that your web > server does something *extremely* funky when it gets a CGI output it isn't > expecting. But this doesn't make a lot of sense. Okay. How trouble-shoot this? Pass it on to the techies where I host? Generally they are less than receptive, but maybe if I show them this thread I can get their attention. > > > Stupidity and ignorance are entirely different things, and you (current) > ignorance in no way implies stupidity. We all have to learn. > True. I have never found programming easy. But I have been very persistent. It still is not easy for me. > However, if you bring up one of the pages from one of your many web sites > containing an image, and get your browser to display the HTML of that page > you will surely find that the image does not appear direectly in the HTML, > but instead appears as a tag in the HTML. Something like: > >http://server/path/image.jpg";> > > though the src attribute doesn't really need to be that complex. > Of course. > > > In my stupidity, I have assumed you meant this: > > > >content = col_fields[0][14].tostring() > >print '' > > > > Well, here I have no idea what the content of your database might be, > but if the fifteenth column you retrieve is the web server path to the > graphic, that should be right except for the spaces around it, which might > give trouble. You might consider instead > >content = col_fields[0][14].tostring() >print '' % content Great suggestion! Those spaces always mess me up. Unfortunately, it *still* did not render properly :( > > > Forget HTML for now. If you direct your browser to the URL on which your > server is serving the graphic then it should be displayed in the browser > window. Until that happy condition pertains, we are stabbing around in the > dark. Again...time to alert the teckies where I host? > > It's not that I mind, but I do feel that this knowledge is already > available, though clearly I might be wrong ... Well, I may have missed it in all my googling, but I thought I was pretty thorough. At any rate, it certainly cannot hurt to document it again (if it is indeed 'again') TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
On Wed, Apr 9, 2008 at 1:49 PM, Steve Holden <[EMAIL PROTECTED]> wrote: > Victor Subervi wrote: > > On Wed, Apr 9, 2008 at 12:51 PM, Steve Holden <[EMAIL PROTECTED] > > <mailto:[EMAIL PROTECTED]>> wrote: > I imagine the following code should do so, given your earlier writings: > > #! /usr/bin/python > > import MySQLdb > > print "Content-type: image/jpeg\r\n" > host = 'host' > db = 'bre' > user = 'user' > passwd = 'pass' > connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) > cursor = connection.cursor() > cursor.execute('select img from photo where id="7";') > content = cursor.fetchall()[0][0] > f = open("somefile.jpg", "w") > f.write(content) > f.close() > > Then see if you can deal with "somefile.jpg" like any other JPEG. If you > can't then your blobs are somehow being mangled. If you can, we'll take > it from there. Yes, I can. Shows up in browser when surfed to, and it was pulled from the database. No mangling. I am signing off, back tomorrow morning. TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
Okay, here is where we find the fly in the ointment. If I run this code: #! /usr/bin/python import MySQLdb print "Content-type: image/jpeg\r\n" host = 'mysqldb2.ehost-services.com' db = 'benobeno_bre' user = 'benobeno' passwd = '21122112' connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) cursor = connection.cursor() cursor.execute('select pic1 from products where id="2";') content = cursor.fetchall()[0][0] content = content.tostring() print content f = open("2.jpg", "w") f.write(content) f.close() all is well :) If, however, I change two lines to make it an html page: #! /usr/bin/python import MySQLdb # print "Content-type: image/jpeg\r\n" print "Content-type: text/html\n" host = 'mysqldb2.ehost-services.com' db = 'benobeno_bre' user = 'benobeno' passwd = '21122112' connection = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) cursor = connection.cursor() cursor.execute('select pic1 from products where id="2";') content = cursor.fetchall()[0][0] content = content.tostring() print '' % content # print content f = open("2.jpg", "w") f.write(content) f.close() it prints garbage. It does not yield the image. Now, what? TIA. Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
Well, what I did was this: content = col_fields[0][14].tostring() pic = "tmp" + str(i) + ".jpg" img = open(pic, "w") img.write(content) print '' % pic img.close() where I am incrementing i. Ugly. Stupid. But if it is the only way to do it in python, and I do not want to invest the time doing it in php, which I think would be prettier in this instance, then I guess it will do. Your thoughts appreciated. Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
Nope. Do not see it. My ugly stupid way works. I guess I will just proceed with that and write my howto accordingly. Victor On Thu, Apr 10, 2008 at 9:01 PM, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > En Thu, 10 Apr 2008 14:04:43 -0300, Victor Subervi > <[EMAIL PROTECTED]> escribió: > > > Well, what I did was this: > > > > content = col_fields[0][14].tostring() > > pic = "tmp" + str(i) + ".jpg" > > img = open(pic, "w") > > img.write(content) > > print '' % pic > > img.close() > > where I am incrementing i. Ugly. Stupid. But if it is the only way to do > > it > > in python, and I do not want to invest the time doing it in php, which I > > think would be prettier in this instance, then I guess it will do. Your > > thoughts appreciated. > > You REALLY should read some material on how HTTP works. I'll try to sketch > a few important points. First, suppose you have an HTML page (album.html) > with two images in it: > > > This is me: > and this is my cat > > > Suppose the URL for that page is http://some.server.com/gabriel/album.html > and you type that in your favorite browser. This is what happens: > 1) The sees the initial "http:" and says "I'll use HTTP". Then sees > "some.server.com" and opens a connection to that server on port 80. Then > sees "/gabriel.album.html" and builds an HTTP GET request for it. > 2) The server receives the GET request, looks for the "album.html" > document, determines the right Content-Type, and returns it specifying > "Content-Type: text/html" > 3) The browser receives the HTML text and tries to display it. When it > encounters the first tag it looks at the src attribute; it doesn't > know that image; so a *NEW* HTTP request is required. This time it says > "GET /images/myself.jpg" > 4) The server receives the GET request, looks for a file with that name, > determines that it's a jpeg image, and returns its contents along with a > "Content-Type: image/jpeg". > 5) The browser receives the image and is able to display it. > 6) The same thing happens with the second tag, there is a third HTTP > GET request for it. > > Note that: > - The images themselves *aren't* in the HTML page, they are somewhere > else. HTML is text and contains ONLY the URI for the image. > - THREE DIFFERENT requests are done to show that page. Each one returns A > SINGLE OBJECT of A SINGLE TYPE. > > The above was using static HTML with static images. If you use CGI to > generate dynamic content, it's the same thing. From the browser point of > view, there is no difference: it still will generate three different > requests for the three pieces (one html document with two images). > Your CGI script (or scripts) will receive three different requests then: > when requested for HTML, return HTML; when requested for an image, return > an image. They are DIFFERENT things, DIFFERENT requests, happening at > DIFFERENT times, so don't mix them. > > I think that combining Steve's responses and mine you now have enough > information to be able to solve your problems. Perhaps if you re-read the > whole thread from start you'll have now a better understanding of what's > happening. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
I have worked on this many hours a day for two weeks. If there is an easier way to do it, just take a minute or two and point it out. Have you heard of the Law of Diminishing Returns? I have passed it long ago. I no longer want to waste time trying to guess at what you are trying to tell me. Victor On Fri, Apr 11, 2008 at 8:55 AM, Steve Holden <[EMAIL PROTECTED]> wrote: > Victor Subervi wrote: > > Nope. Do not see it. My ugly stupid way works. I guess I will just > > proceed with that and write my howto accordingly. > > Victor > > > OK, but be prepared for some pretty scathing feedback. You will make it > clear you do not understand the web. I'd suggest a little more reading > first. > > regards > Steve > -- > Steve Holden+1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
in line... On Fri, Apr 11, 2008 at 2:05 PM, Steve Holden <[EMAIL PROTECTED]> wrote: > Victor Subervi wrote: > > I have worked on this many hours a day for two weeks. If there is an > > easier way to do it, just take a minute or two and point it out. Have > > you heard of the Law of Diminishing Returns? I have passed it long ago. > > I no longer want to waste time trying to guess at what you are trying to > > tell me. > > Victor > > > > On Fri, Apr 11, 2008 at 8:55 AM, Steve Holden <[EMAIL PROTECTED] > > <mailto:[EMAIL PROTECTED]>> wrote: > Where you have > > content = col_fields[0][14].tostring() > pic = "tmp" + str(i) + ".jpg" > img = open(pic, "w") > img.write(content) > print '' % pic > img.close() > > instead write > > print content Like this, I presume? img = open(pic, "w") img.write(content) print '' % pic print content #print '\n' % pic Does not work _at_all LOL. You will recall, also, that you once gave me a line similar to the one commented out (but without writing then opening the file). THAT did not work, either. So now do you see why I am frustrated?? > > > Then browse to the URL this program serves and you will see the image > (assuming you are still sending the image/jpeg content type). Well, as I mentioned before, I am sending text/html because the page, like almost all web pages, has a whole lot more content than just images. Or, perhaps you are suggesting I build my pages in frames, and have a frame for every image. Unsightly! > Once you > can see the image, THEN you can write a page that refers to it. Until > you start serving the image (NOT pseudo-html with image data embedded in > it) nothing else will work. My solution works just fine, thank you. It is inelegant. But it now appears to me, and I dare say rather clearly, that this inelegance is the fault of python itself. Perhaps this should be brought to Guido´s attention. Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
Thanks to all, especially Gabriel. The base64 is a good idea, but you state a definite problem. I will look at your code at home (offline)...thank you very much! It looks like the kicker is this line here: " % (picid, cgi.escape(title)) Now, why didn´t you share that before? I can see how calling a separate script like that would work! Again, you should have shared that before. How was I to think of that clever trick from the bare information you gave me earlier?? Steve, thank you for all your help, but do overcome your temper :)) Victor On Sun, Apr 13, 2008 at 7:05 AM, Steve Holden <[EMAIL PROTECTED]> wrote: > Jason Scheirer wrote: > [...] > > > > There _is_ a way to embed image data in HTML that is supported by > > every major browser. It is ugly. Using the RFC 2397 (http:// > > www.ietf.org/rfc/rfc2397) spec for data URLs you could go > > > > '' % base64.b64encode(image_data) > > > > Obviously you need to import the base64 module somewhere in your code > > and base64-encoded data is about a third larger than it would be > > otherwise, so embedding anything particularly large is going to be a > > huge pain and affect page load times pretty badly. > > This is hardly likely to help someone who hasn't yet grasped the concept > of referencing graphics and prefers to write database output to disk to > serve it statically. But who knows, maybe it will ... > > regards > Steve > -- > Steve Holden+1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
Gabriel; That's really nice code you wrote. I will rewrite my app accordingly, after I catch a breather! Say, would you please publish this somewhere? Why should I write a howto on this and credit you when all I would be doing is republishing (plagerizing) what you published? Please insert these keywords: mysql, image, python, mysqldb and maybe picture and photo (you already have photo). Call it something like "MySQL/Python Tutorial for Posting and Retrieving Images / Photo Album". I ask you to do this because I scoured google looking for just what you've provided and it simply isn't out there. At all. There are nice howto's in php. Please post this for those interested in python, somewhere like the cookbook. Thanks, Victor On Tue, Apr 15, 2008 at 3:23 AM, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > En Mon, 14 Apr 2008 11:03:54 -0300, Steve Holden <[EMAIL PROTECTED]> > escribió: > > Victor Subervi wrote: > >> Thanks to all, especially Gabriel. [...] > >> Steve, thank you for all your help, but do overcome your temper :)) > > > > I'm glad the penny finally dropped. You may have been treated to a > > modest display of exasperation, but please be assured you have not yet > > seen anything remotely like temper from me :-) > > And I'm glad to see that you finally "got it", too! > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: String Literal to Blob
The _keywords_ are _essential_. It is currently published at the end of a long and exhaustive thread. This is not good. It should be republished correctly, and with the kw people will use to search. For example, I would never have thought to search for a photo album. Victor On Tue, Apr 15, 2008 at 10:55 AM, J. Cliff Dyer <[EMAIL PROTECTED]> wrote: > It is published. On comp.lang.python. Google groups has it, so google > (search) will find it. > > Cheers, > Cliff > > > On Tue, 2008-04-15 at 17:04 +0200, Victor Subervi wrote: > > Gabriel; > > > > That's really nice code you wrote. I will rewrite my app accordingly, > > after I catch a breather! Say, would you please publish this > > somewhere? Why should I write a howto on this and credit you when all > > I would be doing is republishing (plagerizing) what you published? > > Please insert these keywords: mysql, image, python, mysqldb and maybe > > picture and photo (you already have photo). Call it something like > > "MySQL/Python Tutorial for Posting and Retrieving Images / Photo > > Album". I ask you to do this because I scoured google looking for just > > what you've provided and it simply isn't out there. At all. There are > > nice howto's in php. Please post this for those interested in python, > > somewhere like the cookbook. > > > > Thanks, > > > > Victor > > > > > > > > On Tue, Apr 15, 2008 at 3:23 AM, Gabriel Genellina > > <[EMAIL PROTECTED]> wrote: > > En Mon, 14 Apr 2008 11:03:54 -0300, Steve Holden > > <[EMAIL PROTECTED]> > > escribió: > > > Victor Subervi wrote: > > >> Thanks to all, especially Gabriel. [...] > > >> Steve, thank you for all your help, but do overcome your > > temper :)) > > > > > > > > I'm glad the penny finally dropped. You may have been > > treated to a > > > modest display of exasperation, but please be assured you > > have not yet > > > seen anything remotely like temper from me :-) > > > > > > And I'm glad to see that you finally "got it", too! > > > > -- > > Gabriel Genellina > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Oook, > J. Cliff Dyer > Carolina Digital Library and Archives > UNC Chapel Hill > > -- http://mail.python.org/mailman/listinfo/python-list
Importing My Own Script
Hi: How do I import my own script from a second script? That is, I have script x and I want to import script y. How? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
More Fun With MySQL and Images
Hi again: Here is my code, an edit of Gabriel´s: #!/usr/local/bin/python import cgitb; cgitb.enable() import MySQLdb def test(): host = 'host' db = 'db' user = 'user' passwd = 'pass' db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) cursor= db.cursor() cursor.execute('select pic1 from products where id="2";') content = cursor.fetchall()[0][0].tostring() f = open("somefile.jpg", "w") f.write(content) f.close() print 'Content-Type: image/jpeg\r\nContent-Length: %d\n' % len(content) print '\n' print content print '\n' cursor.close() test() Now, when I surf to the url of this script, it prints out garbage that is a literal of the image, but not the image itself. However, if I surf to ¨somefile.jpg¨, I see the image!! Am I losing my mind?? What´s wrong here? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing My Own Script
On Thu, Apr 17, 2008 at 8:52 AM, Ben Kaplan <[EMAIL PROTECTED]> wrote: > If x and y are in the same directory, just do "import x". If not, add the > directory containing x to sys.path. Then, "import x" should work. > Well, now that´s what I thought! But no, it doesn´t work! Both scripts are in the same folder. Here´s the error: [Thu Apr 17 07:45:50 2008] [error] [client 190.166.0.245] PythonHandler mod_python.cgihandler: File "/var/www/vhosts/ livestocksling.com/httpdocs/bre/test.py", line 3, in ?\n import test2 [Thu Apr 17 07:45:50 2008] [error] [client 190.166.0.245] PythonHandler mod_python.cgihandler: ImportError: No module named test2 I´m running through Plesk, if that makes a difference. TIA, Victor > > - Original Message > From: Victor Subervi <[EMAIL PROTECTED]> > To: python-list@python.org > Sent: Thursday, April 17, 2008 9:45:10 AM > Subject: Importing My Own Script > > Hi: > How do I import my own script from a second script? That is, I have script > x and I want to import script y. How? > TIA, > Victor > > > -- > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it > now.<http://us.rd.yahoo.com/evt=51733/*http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ> > -- http://mail.python.org/mailman/listinfo/python-list
Re: More Fun With MySQL and Images
Never mind. Apparently, these tags throw it for that loop: print '\n' I´m surprised they would, but gratified I found the problem. Victor On Thu, Apr 17, 2008 at 9:42 AM, Victor Subervi <[EMAIL PROTECTED]> wrote: > Hi again: > Here is my code, an edit of Gabriel´s: > > #!/usr/local/bin/python > import cgitb; cgitb.enable() > import MySQLdb > def test(): > host = 'host' > db = 'db' > user = 'user' > passwd = 'pass' > db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) > cursor= db.cursor() > cursor.execute('select pic1 from products where id="2";') > content = cursor.fetchall()[0][0].tostring() > f = open("somefile.jpg", "w") > f.write(content) > f.close() > print 'Content-Type: image/jpeg\r\nContent-Length: %d\n' % len(content) > print '\n' > print content > print '\n' > cursor.close() > > test() > Now, when I surf to the url of this script, it prints out garbage that is > a literal of the image, but not the image itself. However, if I surf to > ¨somefile.jpg¨, I see the image!! Am I losing my mind?? What´s wrong here? > TIA, > Victor > -- http://mail.python.org/mailman/listinfo/python-list
Re: More Fun With MySQL and Images
Yeah, I figured that out between posts ;) On Thu, Apr 17, 2008 at 10:39 AM, J. Cliff Dyer <[EMAIL PROTECTED]> wrote: > On Thu, 2008-04-17 at 09:52 -0500, Victor Subervi wrote: > > Never mind. Apparently, these tags throw it for that loop: > > print '\n' > > I´m surprised they would, but gratified I found the problem. > > Victor > > > > > > Why does that surprise you? A jpeg has a well-defined header that tells > whatever application is rendering it what to look for. By putting those > tags at the beginning of the data sent to your browser, you're no longer > getting a well-formed jpeg. The header is wrong. > > As an experiment, if you're on *nix, or have access to a decent shell, > try this: > > $ echo '' > newfile.jpg > $ cat /path/to/any_normal_jpeg >> newfile.jpg > $ echo '' >> newfile.jpg > > If you don't have access to a shell, open a JPEG with your favorite text > editor, and manually add "" to the beginning, and save it > out. > > Then try to open newfile in any piece of software of your choosing. > It's no longer a well-formed jpeg, so it won't work. That's exactly > what you're asking the browser to do. > > I guess this isn't really python related, so my apologies for that. > > Cheers, > Cliff > > > > > -- > Oook, > J. Cliff Dyer > Carolina Digital Library and Archives > UNC Chapel Hill > > -- http://mail.python.org/mailman/listinfo/python-list
Prob. w/ Script Posting Last Value
Hi; Gabriel provided a lovely script for showing images which I am modifying for my needs. I have the following line: print '\n' % (d, y) where the correct values are entered for the variables, and those values increment (already tested). Here is the slightly modified script it calls: #!/usr/local/bin/python import cgitb; cgitb.enable() import MySQLdb import cgi form = cgi.FieldStorage() picid = int(form["id"].value) x = int(form["x"].value) pic = str(x) print 'Content-Type: text/html' db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) cursor= db.cursor() sql = "select " + pic + " from products where id='" + str(picid) + "';" cursor.execute(sql) content = cursor.fetchall()[0][0].tostring() cursor.close() print 'Content-Type: image/jpeg\r\nContent-Length: %s\n' % len(content) print content I need to make it so that it will show all my images, not just the last one. Suggestions, please. TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Prob. w/ Script Posting Last Value
On Thu, Apr 17, 2008 at 1:07 PM, Steve Holden <[EMAIL PROTECTED]> wrote: > Victor Subervi wrote: > > > Hi; > > Gabriel provided a lovely script for showing images which I am modifying > > for my needs. I have the following line: > > print '\n' % (d, y) > > where the correct values are entered for the variables, and those values > > increment (already tested). Here is the slightly modified script it calls: > > #!/usr/local/bin/python > > import cgitb; cgitb.enable() > > import MySQLdb > > import cgi > > form = cgi.FieldStorage() > > picid = int(form["id"].value) > > x = int(form["x"].value) > > pic = str(x) > > print 'Content-Type: text/html' > > db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) > > cursor= db.cursor() > > sql = "select " + pic + " from products where id='" + str(picid) + "';" > > cursor.execute(sql) > > content = cursor.fetchall()[0][0].tostring() > > cursor.close() > > print 'Content-Type: image/jpeg\r\nContent-Length: %s\n' % len(content) > > print content > > I need to make it so that it will show all my images, not just the last > > one. Suggestions, please. > > TIA, > > Victor > > > > In your "page generator" page, replace > > print '\n' % (d, y) > > by > > for d, y in (results of some DB query to get d and y for each image): > print '\n' % (d, y) > Well, I just tried this: #! /usr/bin/python print """Content-type: text/html """ y = 1 for d in 2, 12: while y < 12: print '\n' % (d, y) y += 1 print""" """ and it printed the same image over and over again :( Now, I could write a generator function that writes and then executes a new program for each image "getpic" + i + "py?... but that is ugly. Victor -- http://mail.python.org/mailman/listinfo/python-list
Error Handling
Hi; I have the following code: try: cursor.execute(sql) print '¡Exito en introducir!' print 'Esta página va a regresar a la página principal del carrito de compras en 10 segundos.' except IntegrityError: print 'Lo siento, pero el ID que entraste está usado actualmente por otra entrada. Favor de dar para atráz y escojer otro número.' except OperationalError: print 'Lo siento, pero has añadido un carácter extraño a un número (o en "ID", "precio", "recámaras" o "baños". Favor de dar para atráz y escojer otro número.' except: print 'Lo siento, pero hay un error. Favor de dar para atráz y averiguar donde está el error, y reintentar.' When I enter and ID that is not a number, it should trigger the IntegrityError. Instead, I get this in the error log: [Thu Apr 17 12:06:37 2008] [error] [client 190.166.0.245] PythonHandler mod_python.cgihandler: NameError: global name 'IntegrityError' is not defined, referer: http://livestocksling.com/bre/iud.py When I enter a non-digit in a float, I should get an OperationalError. Instead, I get more garbage: [Thu Apr 17 12:10:38 2008] [error] [client 190.166.0.245] PythonHandler mod_python.cgihandler: NameError: global name 'OperationalError' is not defined, referer: http://livestocksling.com/bre/iud.py What do? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing My Own Script
That worked. Thanks. Victor On Thu, Apr 17, 2008 at 2:18 PM, Raúl Gómez C. <[EMAIL PROTECTED]> wrote: > Victor, you can do this in order to load your own modules: > > import sys,os > sys.path.append(os.getcwd()) > > import your_module > > > > On Fri, Apr 18, 2008 at 12:34 PM, Ben Kaplan <[EMAIL PROTECTED]> > wrote: > > >It might be something in mod python. Try asking on their mailing > > list. > > > > - Original Message > > From: Victor Subervi <[EMAIL PROTECTED]> > > To: Ben Kaplan <[EMAIL PROTECTED]> > > Cc: python-list@python.org > > Sent: Thursday, April 17, 2008 10:47:34 AM > > Subject: Re: Importing My Own Script > > > > On Thu, Apr 17, 2008 at 8:52 AM, Ben Kaplan <[EMAIL PROTECTED]> > > wrote: > > > > > If x and y are in the same directory, just do "import x". If not, add > > > the directory containing x to sys.path. Then, "import x" should work. > > > > > > > Well, now that´s what I thought! But no, it doesn´t work! Both scripts > > are in the same folder. Here´s the error: > > > > [Thu Apr 17 07:45:50 2008] [error] [client 190.166.0.245] PythonHandler > > mod_python.cgihandler: File "/var/www/vhosts/ > > livestocksling.com/httpdocs/bre/test.py", line 3, in ?\n import test2 > > [Thu Apr 17 07:45:50 2008] [error] [client 190.166.0.245] PythonHandler > > mod_python.cgihandler: ImportError: No module named test2 > > I´m running through Plesk, if that makes a difference. > > TIA, > > Victor > > > > > > > > > > - Original Message > > > From: Victor Subervi <[EMAIL PROTECTED]> > > > To: python-list@python.org > > > Sent: Thursday, April 17, 2008 9:45:10 AM > > > Subject: Importing My Own Script > > > > > > Hi: > > > How do I import my own script from a second script? That is, I have > > > script x and I want to import script y. How? > > > TIA, > > > Victor > > > > > > > > > -- > > > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try > > > it > > > now.<http://us.rd.yahoo.com/evt=51733/*http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ> > > > > > > > > > > > -- > > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try > > it > > now.<http://us.rd.yahoo.com/evt=51733/*http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ> > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > Nacho > Linux Counter #156439 > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Another MySQL Images Question
Hi; If I grab an image in the database thus: sql = "select pic1 from products where id='" + str(id) + "';" cursor.execute(sql) pic1 = cursor.fetchall()[0][0].tostring() # pic1 = cursor.fetchall()[0][0] // either this or the above line and try and re-insert it thus: cursor.execute('update products set pic1="%s" where id="%s", ;', (pic1, id)) it tells me I have an error in my MySQL syntax. What is the error? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Another MySQL Images Question
Thank you. That worked. Victor On Fri, Apr 18, 2008 at 10:48 AM, J. Cliff Dyer <[EMAIL PROTECTED]> wrote: > There are several problems with your SQL, but not all of them would be > caught by the computer. Your SELECT statement is not parameterized. > This is a security problem. *Always* parameterize your variables. Your > UPDATE statement has an extraneous comma at the end, and it also has > quotes around the "%s"es that you don't need, because you already > parameterized that query. Your dbapi interface will provide appropriate > quoting for whatever type of data you pass it. > > Cheers, > Cliff > > > On Fri, 2008-04-18 at 10:13 -0500, Victor Subervi wrote: > > Hi; > > If I grab an image in the database thus: > > > > sql = "select pic1 from products where id='" + str(id) + "';" > > cursor.execute(sql) > > pic1 = cursor.fetchall()[0][0].tostring() > > # pic1 = cursor.fetchall()[0][0] // either this or the above > > line > > > > and try and re-insert it thus: > > > > cursor.execute('update products set pic1="%s" where id="%s", ;', > > (pic1, id)) > > > > it tells me I have an error in my MySQL syntax. What is the error? > > TIA, > > Victor > -- > Oook, > J. Cliff Dyer > Carolina Digital Library and Archives > UNC Chapel Hill > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Error Handling
That worked. Thanks! Victor On Sun, Apr 20, 2008 at 11:02 PM, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > En Thu, 17 Apr 2008 16:19:12 -0300, Victor Subervi < > [EMAIL PROTECTED]> escribió: > > > try: > > cursor.execute(sql) > > print '¡Exito en introducir!' > > print 'Esta página va a regresar a la página principal del > carrito > > de compras en 10 segundos.' > > except IntegrityError: > > print 'Lo siento, pero el ID que entraste está usado actualmente > por > > otra entrada. Favor de dar para atráz y escojer otro número.' > > except OperationalError: > > print 'Lo siento, pero has añadido un carácter extraño a un número > (o > > en "ID", "precio", "recámaras" o "baños". Favor de dar para atráz y > escojer > > otro número.' > > except: > > print 'Lo siento, pero hay un error. Favor de dar para atráz y > > averiguar donde está el error, y reintentar.' > > When I enter and ID that is not a number, it should trigger the > > IntegrityError. Instead, I get this in the error log: > > > > [Thu Apr 17 12:06:37 2008] [error] [client 190.166.0.245] PythonHandler > > mod_python.cgihandler: NameError: global name 'IntegrityError' is not > > defined, referer: http://livestocksling.com/bre/iud.py > > Looks like IntegrityError and OperationalError are defined inside your > database module. Either use: > > from my_database_module import IntegrityError, OperationalError > > try > ... > except OperationalError: ... > except IntegrityError: ... > except Exception: ... > > or else: > > import my_database_module > > try > ... > except my_database_module.OperationalError: ... > except my_database_module.IntegrityError: ... > except Exception: ... > > It's the same as any other symbol, like math.sqrt or os.rename > > Note that I've not used a bare except: clause; it's not a good idea. > sys.exit() raises the SystemExit exception, and pressing Ctrl-C raises > KeyboardInterrupt; a bare except: will catch them, effectively nullifying > the intended purpose. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Goodbying Spaces
Hi; Whenever I call a field from the preceeding form using cgi.FieldStorage() I get a space on either side. I end up writing code like this to get rid of that space: try: if id[0] == ' ': id = id[1:len(id)] except: pass try: if id[len(id) - 1] == ' ': id = id[0:len(id) - 1] except: pass which is a nuisance. Is there a better way to do this? I have tried id.strip() with no luck. What do? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Goodbying Spaces
On Fri, Apr 25, 2008 at 4:29 PM, Luis Zarrabeitia <[EMAIL PROTECTED]> wrote: > > Whats the result of using id.strip()?: > > In [1]: " asdfasdf ".strip() > Out[1]: 'asdfasdf' > > It should work, I guess... It didn´t for some reason. That was the first thing I tried. > > > Btw, you can write your code without using len in a cleaner way: > > try: > if id[0] == ' ': >id = id[1:] # Note this slice notation... > except: > pass > > try: > if id[-1] == ' ': # id[-1] would be the last character >id = id[:-1] # Again, a slice with only one argument > except: > pass Oh, yeah. Forgot about that. Thanks! Victor -- http://mail.python.org/mailman/listinfo/python-list
Colors for Rows
Hi; why doesn't this work? z = 3 for d in id: z += 1 if z % 4 == 0: bg = '#ff' elif z % 4 == 1: bg = '#d2d2d2' elif z % 4 == 2: bg = '#F6E5DF' else: bg = '#EAF8D5' try: print '\n' % bg except: print '\n' It never increments z! Yet, if I print z, it will increment and change the bgcolor! Why?! Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Colors for Rows
On Tue, Apr 29, 2008 at 11:11 AM, D'Arcy J.M. Cain <[EMAIL PROTECTED]> wrote: > On Tue, 29 Apr 2008 09:33:32 -0500 > "Victor Subervi" <[EMAIL PROTECTED]> wrote: > > why doesn't this work? > > First, let me remove some blank lines to reduce scrolling. > > > z = 3 > > > > for d in (1,2,3,4,5,6): > > I changed id to a sequence so that the example actually runs. Please > run your examples first and cut and paste them into the message after > you are sure that it runs. Not sure what you mean here. The example runs. It prints out every time. > > > > z += 1 > > > > if z % 4 == 0: > > bg = '#ff' > > elif z % 4 == 1: > > bg = '#d2d2d2' > > elif z % 4 == 2: > > bg = '#F6E5DF' > > else: > > bg = '#EAF8D5' > > > > try: > > print '\n' % bg > > except: > > print '\n' > > > > It never increments z! Yet, if I print z, it will increment and change > the > > bgcolor! Why?! > > I am not entirely sure what you are trying to do here. First, what > error condition are you expecting in your try statement. Second, don't > you want the print clause, with or without the try/except, in the > loop. I assume that you want to print a line for each member of your > sequence in alternating colours but this only prints for the last one. > Try this: > > z = 3 > > for d in (1,2,3,4,5,6): > z += 1 > > if z % 4 == 0: >bg = '#ff' > elif z % 4 == 1: >bg = '#d2d2d2' > elif z % 4 == 2: >bg = '#F6E5DF' > else: >bg = '#EAF8D5' > > print '' % bg, d Huh? You´re asking for one variable, then giving two! How´s that work? > > > Or, tell us what you are trying to do. I think you understand. I want the row color to alternate, every fourth row color being the same (or a series of 4) > > > In fact, you can replace all the tests and the print statement with > this after defining bg as a list of the four colours: > > print '' % bg[z % 4], d I tried that just for fun. It gave a bg of ´f´. Again, how are you incorporating d? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Colors for Rows
Thank you all. You helped clean up my code. The stupid mistake was in where I set the initial value of the variable z. Victor On Tue, Apr 29, 2008 at 3:20 PM, J. Cliff Dyer <[EMAIL PROTECTED]> wrote: > On Tue, 2008-04-29 at 15:39 -0400, D'Arcy J.M. Cain wrote: > > On Tue, 29 Apr 2008 15:03:23 -0400 > > "J. Cliff Dyer" <[EMAIL PROTECTED]> wrote: > > > Or, if you aren't sure how many colors you'll be using, try the more > > > robust: > > > > > > bg[z % len(bg)] > > > > Good point although I would have calculated the length once at the > > start rather than each time through the loop. > > > > Good catch. Thanks. What's that they say about eyes and bugs? > > Cheers, > Cliff > > > -- http://mail.python.org/mailman/listinfo/python-list
Custom Classes?
Hi; I have the following code which produces a file every time I need to display an image from MySQL. What garbage! Surely, python is capable of better than this, but the last time I asked for help on it, I got no responses. Is this only possible with custom classes? Please, give me some guidance here! try: w += 1 getpic = "getpic" + str(w) + ".py" try: os.remove(getpic) except: pass code = """ #!/usr/local/bin/python import cgitb; cgitb.enable() import MySQLdb import cgi import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() form = cgi.FieldStorage() picid = int(form["id"].value) x = int(form["x"].value) pics = {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\ 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'} pic = pics[x] print 'Content-Type: text/html' db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) cursor= db.cursor() sql = "select " + pic + " from products where id='" + str(picid) + "';" cursor.execute(sql) content = cursor.fetchall()[0][0].tostring() cursor.close() print 'Content-Type: image/jpeg' print print content """ script = open(getpic, "w") script.write(code) print '' % pic print '\n' % (getpic, d, y) TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Colors for Rows
The problem was that z was not incrementing. It kept getting reset to 3, then incremented to 4 immediately, and reset back to 3. Stupid :/ On Wed, Apr 30, 2008 at 11:01 AM, D'Arcy J.M. Cain <[EMAIL PROTECTED]> wrote: > On Wed, 30 Apr 2008 10:57:44 -0500 > "Victor Subervi" <[EMAIL PROTECTED]> wrote: > > Thank you all. You helped clean up my code. The stupid mistake was in > where > > I set the initial value of the variable z. > > Really? I thought that it was odd to start in the middle of your > colour list but it didn't seem like it was an error. What do you think > was wrong with it? > > -- > D'Arcy J.M. Cain <[EMAIL PROTECTED]> | Democracy is three wolves > http://www.druid.net/darcy/| and a sheep voting on > +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. > -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom Classes?
On Wed, Apr 30, 2008 at 12:35 PM, J. Cliff Dyer <[EMAIL PROTECTED]> wrote: > Post working code, and I'll answer your actual question. Good grief! The code is *not* double spaced! Take a look. Click to the end of the first line and hit the right arrow key, and see for yourself. As for not initializing w, well, I did in my code and just forgot to cut and paste that. Same with the except. Sorry on those. And yes, I pull out try clauses when I need to look at stacks. Here: w = 0 try: w += 1 getpic = "getpic" + str(w) + ".py" try: os.remove(getpic) except: pass code = """ #!/usr/local/bin/python import cgitb; cgitb.enable() import MySQLdb import cgi import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() form = cgi.FieldStorage() picid = int(form["id"].value) x = int(form["x"].value) pics = {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\ 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'} pic = pics[x] print 'Content-Type: text/html' db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) cursor= db.cursor() sql = "select " + pic + " from products where id='" + str(picid) + "';" cursor.execute(sql) content = cursor.fetchall()[0][0].tostring() cursor.close() print 'Content-Type: image/jpeg' print print content """ script = open(getpic, "w") script.write(code) print '' % pic print '\n' % (getpic, d, y) except: pass TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom Classes?
Thank you for your patience. I apologize for so many errors. Also, apparently your email client renders those double-spaces whereas mine does not. Hopefully the below is better: #!/usr/bin/python import MySQLdb import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() pic = "pic1" w = 20 x = 0 d = 6 y = 1 getpic = "getpic" + str(w) + ".py" try: os.remove(getpic) except: pass code = """ #!/usr/local/bin/python import cgitb; cgitb.enable() import MySQLdb import cgi import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() form = cgi.FieldStorage() picid = int(form["id"].value) x = int(form["x"].value) pics = {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\ 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'} pic = pics[x] db = MySQLdb.connect(host, user, passwd, db) cursor= db.cursor() sql = "select %s from products where id='%s';" % (pic, str(picid)) cursor.execute(sql) content = cursor.fetchall()[0][0].tostring() cursor.close() print 'Content-Type: image/jpeg' print print content """ script = open(getpic, "w") script.write(code) # print '' % (str(x), pic) # print '\n' % (getpic, d, y) print '\n' Now, on those last 3 lines, I am having trouble with this error being thrown that I don´t understand: ValueError: unpack list of wrong size If I surf to the given url, the image appears! So what gives?? Furthermore, the code works just fine from where it was lifted. TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom Classes?
Okay, trying this again with everything working and no ValueError or any other errors, here we go: Load this code. Unless you use a similar login() script, you will want to edit your own values into the user, passwd, db and host: #!/usr/bin/python import MySQLdb import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() pic = "pic1" w = 20 x = 0 d = 6 y = 1 getpic = "getpic" + str(w) + ".py" try: os.remove(getpic) except: pass code = """ #!/usr/local/bin/python import cgitb; cgitb.enable() import MySQLdb import cgi import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() form = cgi.FieldStorage() picid = int(form["id"].value) x = int(form["x"].value) pics = {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\ 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'} pic = pics[x] db = MySQLdb.connect(host, user, passwd, db) cursor= db.cursor() sql = "select %s from products where id='%s';" % (pic, str(picid)) cursor.execute(sql) content = cursor.fetchall()[0][0].tostring() cursor.close() print 'Content-Type: image/jpeg' print print content """ script = open(getpic, "w") script.write(code) script.close() and then surf to: http://whatever.url/getpic20.py?id=6&x=1 Also, please re-send the link on how to post good questions to the list. I cannot find it. TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't Encode Pic
On Thu, Nov 26, 2009 at 5:08 PM, Dennis Lee Bieber wrote: > On Thu, 26 Nov 2009 13:32:12 -0500, Victor Subervi > declaimed the following in > gmane.comp.python.general: > > > > A problem occurred in a Python script. Here is the sequence of function > > calls leading up to the error, in the order they occurred. > > /var/www/html/angrynates.com/cart/addEdit.py > >87 print '\n' > >88 db.commit() > >89 cursor.close() > >90 > >91 addEdit() > > addEdit = > > /var/www/html/angrynates.com/cart/addEdit.py in addEdit() > >71 for pic in pics: > >72 sql = 'update %s set %s=%s where ID=%s;' % (t, > > colNamesPics[i], '%s', str(id)) > >73 cursor.execute(sql, (MySQLdb.Binary(pics[id]),)) > > Please study the Python language documents... AND the DB-API PEP... > I have read them from cover to cover many times. I just wish everything stuck :( > >sql = "update %s set %s=%%s where ID = %%s" % (t, colNamesPics[i]) >#sets the table/field names, escapes the %s on the DB-API > placeholders [MySQLdb, internally, uses string interpolation, which is > why the placeholder is the same %s, which confuses many] > >cursor.execute(sql, (MysQLdb.Binary(pics[id]), id)) ># you don't have to use str(id) since that is the MEANING of %s as a > placeholder -- generate a normal string representation of whatever the > supplied parameter is (and the nature of MySQLdb is such that it WILL be > a string with any internal quotes escaped, and wrapped in SQL quotes > before getting to the replacement point). > > The following complained that there weren't enough arguments: for pic in pics: sql = 'update %s set %s=%%s where ID=%s;' % (t, colNamesPics[i], '%s', str(id)) cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),), ) Thus, it appears that using a % to escape a % is not what is called for here! Did I miss something again? So I changed it to: for pic in pics: sql = 'update %s set %s=%s where ID=%s;' % (t, colNamesPics[i], '%s', str(id)) cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),), ) (diff: %s=%s) That states that everything worked fine, and it does work fine when I insert one image. However, when I go to update (the same code is used for the pics for both insert and update), and try to insert a second image, it doesn't insert even though it throws no error! If I try to print out all the variables, including the actual image that is being updated, everything prints out just fine! Why would the above statements work for inserting one image but not a second?? >Oh, and finally -- since you generate the SQL statement from scratch > on each pass of the loop, why even bother with a variable named sql? > >cursor.execute("""update %s > set %s=%%s >where ID=%%s""" > % (t, > colNamesPics[i]), >(MySQLdb.Binary(pics[id]), id) ) > > Puts everything in one place, formats it in a somewhat more legible way > (to me, at least, where the "where" clause is on a line by itself, the > various "set" parameters are on lines, etc.; the Python string > interpolation parameters are on one line, and the MySQLdb parameters are > on another line) > I tried combining the two statements and that didn't work either. Same problems as above. > > >I'm not going to look for the other problem -- this thread has shown > a tendency of: > >It doesn't work, what's wrong? > > > >I tried that, now it does this, why? > > > >etc. > > There has been no evidence of one ever referencing documentation in the > attempt to resolve the matter on one's own. It is becoming clear to me that utilizing the docs is an art. At least I (perhaps because I am less adept at the art of programming than many) must study the docs cover to cover many times, over many years (as my skills improve), to get to the point where I know what to look for where and when I need it, to know how to formulate the right questions and thus seek the right answers on my own. It has taken me many years just to get to the point of realizing that. And you have helped me to realize that now in your post (as you have helped me many times with other issues). Nothing hinting at having > opened an interactive Python console and typing statements into it as an > experiment to see what may work, or w
Re: Can't Encode Pic
On Fri, Nov 27, 2009 at 9:02 AM, Rami Chowdhury wrote: > On Fri, Nov 27, 2009 at 02:59, Victor Subervi > wrote: > > On Thu, Nov 26, 2009 at 5:08 PM, Dennis Lee Bieber < > wlfr...@ix.netcom.com> > > wrote: > >> Nothing hinting at having > >> opened an interactive Python console and typing statements into it as an > >> experiment to see what may work, or what changes may break something. > > > > Please explain how this makes a difference. If I have the error in hand > from > > trying to run the code through the Web--either printed to screen or > gathered > > from the errors log--what need of opening the python interpreter > > If you are content to run your code through the Web, and iterate > through versions of it there, then that's up to you. I'd suggest using > the interactive interpreter when you can, though -- most Python > programmers that I have encountered find it extremely helpful. In > particular, it can be invaluable in examining short snippets of code > -- such as the segments that are giving you trouble -- without > rerunning the whole program. > I usually do. I'm in a peculiar situation now, broke and rebuilding, borrowing other people's computers, etc. Won't last too much longer :) > > When I am debugging errors such as this, what I typically do is snip > out the particular bit that is causing the problem and run it in the > interactive interpreter, experimenting with changes to it until it > works as I want it to. Perhaps such a method would help you in > debugging as well? Certainly it would enable you to give the list a > little more information about what you have and haven't tried when > coming here with a problem... > How should I do that in this instance? Here's the problem: the form on the previous page supplies an uploaded image to the second page which is then inserted into a MySQL table. The difficulty I am having is that for some reason it's not inserting. The form inserts the first image but not the second. When I print out the sql query I am submitting, less the image itself, it prints correctly. When I print out the image itself, it also prints correctly. So I don't understand where the problem could possibly be. I appreciate your help as always :) V -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't Encode Pic
On Fri, Nov 27, 2009 at 12:13 PM, Carsten Haese 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 '\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: 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! 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? Is there a way around that? TIA, V -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't Encode Pic
On Fri, Nov 27, 2009 at 1:43 PM, Dennis Lee Bieber wrote: > On Fri, 27 Nov 2009 05:59:39 -0500, Victor Subervi > declaimed the following in > gmane.comp.python.general: > > > > > > > > The following complained that there weren't enough arguments: > > > > for pic in pics: > > sql = 'update %s set %s=%%s where ID=%s;' % (t, colNamesPics[i], > > '%s', str(id)) > > cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),), ) > > >I'm pretty sure that isn't what I had typed too... Count the % > >sql = "update %s set %s=%%s where ID = %%s" % (t, colNamesPics[i]) > Thank you, Dennis. This problem is resolved. Since our posts most likely crossed, and since yours has inadvertently appeared below mine with the latest problem, I'm reposting it here: Now, I have this line of code on another page that calls the images once the database is populated: print '\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: 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! 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? Is there a way around that? TIA, V -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't Encode Pic
> > > > > > > > > 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=2&id=1, I get an image, but > when I go to http://www.angrynates.com/cart/getpic.py?pic=1&id=2, I get > an error message. I am guessing that you have your pic and id parameter > switched around. > Yes. Sorry. Thanks. V -- http://mail.python.org/mailman/listinfo/python-list
Exec Statement Question
Hi; I have the following line of code: exec('%s()' % table) where 'table' is a variable in a for loop that calls variables from another script. I've made it so that it only calls one variable. I know for a fact that it's calling that variable in the script because it found errors in that script. I've tried to have it return the following: print 'hi' return 'hi' It doesn't return anything. No errors are thrown because the code evaluates. I don't know how to capture the output. I would like to do something like: print exec(...) or var = exec(...) but of course those options don't work. Suggestions? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Exec Statement Question
On Sun, Nov 29, 2009 at 10:23 PM, Dave Angel wrote: > exec is a statement, and statements don't have "return values." It's not > a function, so there are no parentheses in its syntax, either. exec is also > a technique of last resort; there's nearly always a better/safer/faster way > to accomplish what you might want, but of course you don't say what that is. > > As for "returning" values, exec by default uses the same global space as > your app, so you can just modify a global variable in your "called" code and > use it afterwards. > > abc = 42 > value = 12 > exec "abc = %d" % value > print abc > 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 The following is from 'options.py': def jewelry(which=''): code = [] names = [] meanings = [] code.append(['5', '5½', '6', '6½', '7', '7½', '8', '8½', '9', '9½', '10', '10½', '11', '11½', '12', '12½', '13', '13½']) meanings.append('The standard ring sizes.') names.append('ringSizes') code.append(['Petite (7")', 'Average (7½")', 'Large (8")', 'Extra-large (8½")']) meanings.append('The standard bracelet sizes.') names.append('braceletSizes') code.append(['16"', '18"', '20"', '22"', '24"']) meanings.append('The standard necklace sizes.') names.append('necklaceSizes') code.append(['14K gold', '18K gold', 'silver', '14K white gold', '18K white gold', 'platinum', 'tungsten', 'titanium']) meanings.append('The standard jewelry metals.') names.append('metals') code.append(['diamond', 'emerald', 'ruby', 'sapphire', 'pearl', 'opal', 'topaz', 'onyx', 'lapiz lazuli', 'tanzanite', 'garnet', 'quartz', 'rose quartz', 'amethyst', 'alexandrite', 'peridot', 'tourmaline', 'citrine', 'turquoise']) meanings.append('The standard jewelry stones.') names.append('stones') if which == '': i = 0 all = '' while i < len(meanings): table = '%s\n' % meanings[i] table += "\n \n %s\n " % names[i] j = 0 for elt in code: if (j + 8) % 8 == 0: table += ' \n' table += ' %s\n' % code[i] if (j + 8) % 8 == 0: table += ' \n' j += 1 if table[-6:] != '\n': table += ' \n' table += '\n' all += table + '' i += 1 print all This all works fine; however, if there is a better way of doing it, please let me know. Thanks, V -- http://mail.python.org/mailman/listinfo/python-list
Completely OT
Hi; I need a recommendation. I want to print out data like this: blue red and enable the user to select the various colors he wants to add to a list that would populate itself on the same page where the selections are, and then, once he's selected all the colors he wants, click to add them all at once to a table in a database, and move on to the next page. I believe this is achieved through JSON and AJAX; however, I haven't been able to google any demonstrations of this sort. Am I correct, or should I use some other sort of technology? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Exec Statement Question
On Mon, Nov 30, 2009 at 12:25 PM, Carsten Haese wrote: > 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 > <> to the resulting function object. > > 3) I call that function using the local name <>. > > Thanks. This is good. Thanks Jean-Michelle for the suggestion on better naming. Thanks Marco for the lxml builder, but I'm happy with just plain old html. V -- http://mail.python.org/mailman/listinfo/python-list
Re: Completely OT
On Mon, Nov 30, 2009 at 1:15 PM, Rami Chowdhury wrote: > On Mon, Nov 30, 2009 at 04:26, Victor Subervi > wrote: > > Hi; > > I need a recommendation. I want to print out data like this: > > > > blue > > red > > > > and enable the user to select the various colors he wants to add to a > list > > that would populate itself on the same page where the selections are, and > > then, once he's selected all the colors he wants, click to add them all > at > > once to a table in a database, and move on to the next page. I believe > this > > is achieved through JSON and AJAX; however, I haven't been able to google > > any demonstrations of this sort. Am I correct, or should I use some other > > sort of technology? > > TIA, > > Victor > > There are a huge number of different ways to do this, including all on > the server-side, all on the client side, and a mixture of both as you > suggested. What kind of behavior are you actually looking for? > Definitely client-side. I just want to enable the client to select all the fields he wants to include, then update to the server once. TIA, V -- http://mail.python.org/mailman/listinfo/python-list
Re: Exec Statement Question
On Mon, Nov 30, 2009 at 1:12 PM, Dave Angel wrote: > Victor Subervi wrote: > >> On Sun, Nov 29, 2009 at 10:23 PM, Dave Angel wrote: >> >> >> >>> exec is a statement, and statements don't have "return values." It's >>> not >>> a function, so there are no parentheses in its syntax, either. exec is >>> also >>> a technique of last resort; there's nearly always a better/safer/faster >>> way >>> to accomplish what you might want, but of course you don't say what that >>> is. >>> >>> As for "returning" values, exec by default uses the same global space as >>> your app, so you can just modify a global variable in your "called" code >>> and >>> use it afterwards. >>> >>> abc = 42 >>> value = 12 >>> exec "abc = %d" % value >>> print abc >>> >>> >>> >> >> 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 >> >> >> The following is from 'options.py': >> >> def jewelry(which=''): >> code = [] >> names = [] >> meanings = [] >> code.append(['5', '5½', '6', '6½', '7', '7½', '8', >> '8½', '9', '9½', '10', '10½', '11', '11½', >> '12', >> '12½', '13', '13½']) >> meanings.append('The standard ring sizes.') >> names.append('ringSizes') >> code.append(['Petite (7")', 'Average (7½")', 'Large >> (8")', 'Extra-large (8½")']) >> meanings.append('The standard bracelet sizes.') >> names.append('braceletSizes') >> code.append(['16"', '18"', '20"', '22"', '24"']) >> meanings.append('The standard necklace sizes.') >> names.append('necklaceSizes') >> code.append(['14K gold', '18K gold', 'silver', '14K white gold', '18K >> white gold', 'platinum', 'tungsten', 'titanium']) >> meanings.append('The standard jewelry metals.') >> names.append('metals') >> code.append(['diamond', 'emerald', 'ruby', 'sapphire', 'pearl', 'opal', >> 'topaz', 'onyx', 'lapiz lazuli', 'tanzanite', 'garnet', 'quartz', 'rose >> quartz', 'amethyst', 'alexandrite', 'peridot', 'tourmaline', 'citrine', >> 'turquoise']) >> meanings.append('The standard jewelry stones.') >> names.append('stones') >> if which == '': >>i = 0 >>all = '' >>while i < len(meanings): >> table = '%s\n' % meanings[i] >> table += "\n \n %s\n >> " % names[i] >> j = 0 >> for elt in code: >>if (j + 8) % 8 == 0: >> table += ' \n' >>table += ' %s\n' % code[i] >>if (j + 8) % 8 == 0: >> table += ' \n' >>j += 1 >> if table[-6:] != '\n': >>table += ' \n' >> table += '\n' >> all += table + '' >> i += 1 >>print all >> >> This all works fine; however, if there is a better way of doing it, please >> >> > > let me know. >> Thanks, >> V >> >> >> > The parentheses can't do any harm for that particular expression, so that > wasn't your problem. But I'm glad you fixed whatever else was your problem. > I mentioned it because sometimes they can cause problems, and you shouldn't > get in bad habits. (things like if, return, and exec are all statements > that take an expression, but do n
Re: Completely OT
On Mon, Nov 30, 2009 at 1:39 PM, inhahe wrote: > i'm pretty new to javascript programming, but i'm pretty sure you just > need ajax, which AFAIK is a highly technical way of saying "using > javascript in a way that makes web pages interactive" > JSON afaik is a way of data to and from the server that allows for > lists and more variable types and such, but also requires the user > download a third-party js file that implements JSON. i don't think > you'd technically need JSON, because you could simply send the server > a string of all the colors selected delimited by a space or | or > something. > javascript also probably has inherent functions for generating xml, > considering that the object you use to communicate with the server is > an xmlhttprequst. but i think xml might be overkill in this case. > > the javascript would populate the list for the colors the user selects > (the easiest way would probably be to give the list an id and use > getElementByID()), and then when he's done it would create an > xmlhttprequest object to send the data to the server. > If I'm not mistaken, that won't help me actually print to screen the user's choices as he selects them, which in my application, is important. Please advise. TIA, V > > On Mon, Nov 30, 2009 at 7:26 AM, Victor Subervi > wrote: > > Hi; > > I need a recommendation. I want to print out data like this: > > > > blue > > red > > > > and enable the user to select the various colors he wants to add to a > list > > that would populate itself on the same page where the selections are, and > > then, once he's selected all the colors he wants, click to add them all > at > > once to a table in a database, and move on to the next page. I believe > this > > is achieved through JSON and AJAX; however, I haven't been able to google > > any demonstrations of this sort. Am I correct, or should I use some other > > sort of technology? > > TIA, > > Victor > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- http://mail.python.org/mailman/listinfo/python-list