[Tutor] Python CGI Script
I Have a CGI Script Which is working perfectly when run from the python interpreter, i m using the Content-type: application/x-www-url-form-encoded , i use it to send data from flash apps to python script. i checked the script with content-type: text/html , and browsers printed the output perfectly, but when i use the application content type, it gives the error, normally , firefox just prints everything, so i dont know whats wrong. heres the script, i m using the M ySQLdb for the Database Connection. Why isnt it Working? import MySQLdb as sql import cgi,cgitb cgitb.enable() class Listing: def __init__(self): form = cgi.FieldStorage() self.DBid = form.getvalue("DBid") self.tableid = form.getvalue("tableid") self.rangeid1 = form.getvalue("StartRange") self.rangeid2 = form.getvalue("EndRange") conn = sql.connect('localhost','root','xxx',db=self.DBid) self.cursor = conn.cursor() self.conn = conn self.list1 = [] self.list2 = [] self.list3 = [] self.list4 = [] self.list5 = [] self.list6 = [] self.outputstring = "" def listquery(self): query1 = """SELECT ABC FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) query2 = """SELECT DEF FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) query3 = """SELECT GHI FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) query4 = """SELECT JKL FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) query5 = """SELECT MNO FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) query6 = """SELECT PQR FROM %s limit %s,%s"""\ % (self.tableid,self.rangeid1,self.rangeid2) self.list1 = self.queryexecute(query1) self.list2 = self.queryexecute(query2) self.list3 = self.queryexecute(query3) self.list4 = self.queryexecute(query4) self.listt5 = self.queryexecute(query5) self.list6 = self.queryexecute(query6) def queryexecute(self,query): templist = [] self.cursor.execute(query,) for a in self.cursor.fetchall(): templist.extend(a) return templist def outputappend(self,listtoappend,appname): tempstring = "" for a in range(0,len(listtoappend)): tempstring += appname + str(a+1) + "x" + "=" +\ listtoappend[a] + "&" return tempstring def output(self): self.outputstring += self.outputappend(self.list1,"list1") self.outputstring += self.outputappend(self.list2,"list2") self.outputstring += self.outputappend(self.list3,"list3") self.outputstring += self.outputappend(self.list4,"list4") self.outputstring += self.outputappend(self.list5,"list5") self.outputstring += self.outputappend(self.list6,"list6") print """Content-type: application/x-www-url-form-encoded\n""" print """%s""" % (self.outputstring) def clear(self): self.cursor.close() self.conn.close() x = Listing() x.listquery() x.output() x.clear() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python CGI Script
Faran wrote: > I Have a CGI Script Which is working perfectly when run from the python > interpreter, i m using the Content-type: > application/x-www-url-form-encoded , i use it to send data from flash > apps to python script. i checked the script with content-type: text/html > , and browsers printed the output perfectly, but when i use the > application content type, it gives the error, normally , firefox just > prints everything, so i dont know whats wrong. heres the script, i m > using the M ySQLdb for the Database Connection. Why isnt it Working? It seems a bit unusual to use that content type to return data to the browser, it is usually used for form submissions. I'm not sure why it doesn't work but I have a couple of note below. > > import MySQLdb as sql > import cgi,cgitb > > cgitb.enable() > > class Listing: > def __init__(self): > > form = cgi.FieldStorage() > self.DBid = form.getvalue("DBid") > self.tableid = form.getvalue("tableid") > self.rangeid1 = form.getvalue("StartRange") > self.rangeid2 = form.getvalue("EndRange") > > conn = sql.connect('localhost','root','xxx',db=self.DBid) > self.cursor = conn.cursor() > self.conn = conn > self.list1 = [] > self.list2 = [] > self.list3 = [] > self.list4 = [] > self.list5 = [] > self.list6 = [] > self.outputstring = "" > > def listquery(self): > query1 = """SELECT ABC FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > query2 = """SELECT DEF FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > query3 = """SELECT GHI FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > query4 = """SELECT JKL FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > query5 = """SELECT MNO FROM %s limit %s,%s"""\ >% (self.tableid,self.rangeid1,self.rangeid2) > query6 = """SELECT PQR FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) > > self.list1 = self.queryexecute(query1) > self.list2 = self.queryexecute(query2) > self.list3 = self.queryexecute(query3) > self.list4 = self.queryexecute(query4) > self.listt5 = self.queryexecute(query5) > self.list6 = self.queryexecute(query6) > > def queryexecute(self,query): > templist = [] > self.cursor.execute(query,) > for a in self.cursor.fetchall(): > templist.extend(a) > > return templist > def outputappend(self,listtoappend,appname): > tempstring = "" > for a in range(0,len(listtoappend)): > tempstring += appname + str(a+1) + "x" + "=" +\ > listtoappend[a] + "&" You should call urllib.quote_plus(listtoappend[a]) to make sure special characters are correctly escaped. > return tempstring > > def output(self): > > self.outputstring += self.outputappend(self.list1,"list1") > self.outputstring += self.outputappend(self.list2,"list2") > self.outputstring += self.outputappend(self.list3,"list3") > self.outputstring += self.outputappend(self.list4,"list4") > self.outputstring += self.outputappend(self.list5,"list5") > self.outputstring += self.outputappend(self.list6,"list6") > print """Content-type: application/x-www-url-form-encoded\n""" You should have '\r\n\r\n' after the header, not just '\n'. > print """%s""" % (self.outputstring) Could just be print self.outputstring HTH, Kent > > def clear(self): > self.cursor.close() > self.conn.close() > > x = Listing() > x.listquery() > x.output() > x.clear() > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python and Gecko
Hello All! I am not a Python expert at all but I am learning when I have time. I am currently working my way through 'wxPython in Action' and really liking it, I have been using Learning to Program as my central text. Anyway, I was wondering if there is anyway to use the Mozilla Gecko engine in Python? Or the KHTML engine would be okay as well. Basically I would like to be able to fully render web pages inside a wxPython application. I wrote a brutally simple web browser using wxPython (25 lines, not including imported modules) and after I posted it on my blog I was slammed with traffic (36,000+ hits in 48 hours, my hosting company was very, very upset). The rendering this browser acheives is just HTML with no support for CSS or any other fancy stuff, this is why I would like to try it with a proper rendering engine. I put the browser up on Google Code to save my bandwidth: http://code.google.com/p/the-bonsai-python-project/ Any advice or help from the pyGuru's would be greatly appreciated. There does seem to be some interest in this sort of thing (which surprised me). Thank you all, Ben. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to convert a decimal integer into binary
> I came across some code, which uses bit operator. I could not understand how > the logic of that code. If anyone knows to convert the decimal into binary > using BIT OPERATOR, then please help me. please reply to the list, not just me. since this is your homework assignment, i cannot give you the answer, but i will tell you that there are six bit operators (not one): - << left shift - >> right shirt - & bitwise AND - | bitwise OR - ^ bitwise XOR (eXclusive OR) - ~ bit inversion your solution will likely include (at least) one of the shifters and (at least) one of the bitwise operators. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python CGI Script
>query1 = """SELECT ABC FROM %s limit %s,%s"""\ > % (self.tableid,self.rangeid1,self.rangeid2) Just as a note: please don't do this! *grin* Don't build query strings up like this: this is very prone to an SQL injection attack. See: http://mail.python.org/pipermail/tutor/2003-April/022010.html which talks about this a bit more. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Overloading the assignment operator in a class
Greetings: I have a class that implements a die (singular or dice). Here is the class definition: >>> class Die(object): """Implements a gaming die. Attributes: n: the number of sides Must correspond to the number of sides on a physical die. value: The die face currently facing up. Guaranteed to be in the range 1 <= value <= n. Methods: init: instantiate a die roll: roll the die; set and return the new value set:set the die's value to an arbitrary, in range, value __repr__ __lt__ __le__ __eq__ __ne__ __gt__ __ge__ __cmp__ """ def __init__(self, nsides = 6, firstval = 'r'): """create a die usage: x = die(n, firstval) -> an 'n'-sided die with value='firstval' Arguments: nsides: the number of sides valid: 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 30, 50, 100 default:6 Must correspond to the number of sides on a physical die. Using an invalid value causes an exception. firstval: the die's initial value; valid: 'r' - random value between 1 and n n - specified value; must be between 1 and n Using an invalid value causes an exception. default:'r' """ validn = (3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 30, 50, 100) if nsides not in validn: errmsg = "No die has %s sides. Valid values are: %s." raise ValueError(errmsg % (nsides, validn)) self.n = nsides if firstval == 'r': self.value = randint(1, self.n) elif isinstance(firstval, int): if 1 <= firstval <= self.n: self.value = firstval else: errmsg = "%s is not between 1 and %s." raise ValueError (errmsg % (firstval, self.n)) else: errmsg = "%s is invalid. Valid entries are '%s' " \ "or an integer between 1 and %s." raise ValueError(errmsg % (firstval, 'r', self.n)) def roll(self): """roll the die; set and return the new value""" self.value = randint(1, self.n) return self.value def set(self, newval): """set the die's new value IF between 1 and n; else raise exception """ if isinstance(newval, int): if 1 <= newval <= self.n: self.value = newval else: errmsg = "%s is not between 1 and %s." raise ValueError (errmsg % (newval, self.n)) else: errmsg = "%s is invalid. Valid entries are ' " \ "integers between 1 and %s." raise ValueError(errmsg % (newval, self.n)) # special methods def __cast(self, other): if isinstance(other, Die): return other.value else: return other def __repr__(self): return repr(self.value) def __lt__(self, other): return self.value < self.__cast(other) def __le__(self, other): return self.value <= self.__cast(other) def __eq__(self, other): return self.value == self.__cast(other) def __ne__(self, other): return self.value != self.__cast(other) def __gt__(self, other): return self.value > self.__cast(other) def __ge__(self, other): return self.value >= self.__cast(other) def __cmp__(self, other): return cmp(self.value, self.__cast(other)) >>> This all seems to work okay. I want the assignment operator ('=') to call the set method transparently on Die instances, as in this fictitious example: ### @BCARROLL[Python]|2> mydie = Die(6,3) @BCARROLL[Python]|3> mydie.n <3> 6 @BCARROLL[Python]|4> mydie.value <4> 3 @BCARROLL[Python]|5> mydie <5> 3 @BCARROLL[Python]|6> mydie = 5 @BCARROLL[Python]|7> mydie <7> 5 @BCARROLL[Python]|8> mydie.value 8> 5 @BCARROLL[Python]|9> ### Above, the statement "mydie = 5" resets mydie.value and preserves mydie as a Die instance. The actual (undesired) behavior rebinds the mydie to the int object, and the Die instance is lost: >>> @BCARROLL[Python]|2> mydie = Die(6,3) @BCARROLL[Python]|3> mydie.n <3> 6 @BCARROLL[Python]|4> mydie.value <4> 3 @BCARROLL[Python]|5> mydie <5> 3 @BCARROLL[Python]|6> mydie = 5 @BCARROLL[Python]|7> mydie <7> 5 @BCARROLL[Python]|8> mydie.value --- exceptions.AttributeError Traceback (most recent call last) \\psc.pscnet.com\shares\home\bgcarroll\My Documents\My Projects\study\Py
Re: [Tutor] Overloading the assignment operator in a class
> This all seems to work okay. > > I want the assignment operator ('=') There is no assignment operator in Python, assignment is a binding of an object to a name. > to call the > set method transparently on Die instances, > as in this fictitious example: @BCARROLL[Python]|6> mydie = 5 @BCARROLL[Python]|7> mydie <7> 5 But you can fake this by coercing the integer into a new Die object. As if you had actually done mydie = Die(mydie.n,5) And I believe you can do that by implementing the __coerce__ method. - but I've never tried it... HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Overloading the assignment operator in a class
Carroll, Barry wrote: > Greetings: > > I have a class that implements a die (singular or dice). Here is the class > definition: > How do I overload the '=' operator to give the desired behavior? > > Regards, > > Barry AFAIK, you can't. Unlike, say, Java or C++, the assignment operator is not operating on an object, but instead a name. Consider: in C++ we define variables to a type: int myInt; Die myDie; etc, etc. We don't do this is python. Instead we assign an *object* to an *name* myInt=5 myDie=Die(6, 3) so that myDie is a name for the Die object you've just created. But you can also do this in python: myDie="Some string" Its not assigning to the myDie object, just the name myDie, so that now myDie is a name for a string containing "Some String" In other languages, its reasonable to think of variables as containers. That thinking isn't valid in Python. In Python, what you'd think of as 'variables' are just names for objects. (If you know C++, think pointers, sort of. myDie isn't the Die Object, its just a reference as to where the object is. Assigning to a pointer doesn't change the object, but what the pointer is pointing to.) Hope this helps, Jordan Greenberg ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Overloading the assignment operator in a class
Alan Gauld wrote: >> This all seems to work okay. >> >> I want the assignment operator ('=') > > There is no assignment operator in Python, assignment is a > binding of an object to a name. > >> to call the >> set method transparently on Die instances, >> as in this fictitious example: > > @BCARROLL[Python]|6> mydie = 5 > @BCARROLL[Python]|7> mydie > <7> 5 > > But you can fake this by coercing the integer into a new > Die object. As if you had actually done > > > mydie = Die(mydie.n,5) > > And I believe you can do that by implementing the __coerce__ > method. - but I've never tried it... > > HTH, > > Alan G. > If you can do that with __coerce__, I'm not clever enough to figure out how. IIRC, Python only calls __coerce__ if you're using arithmetic operators on different types, and only if the operator in question isn't overloaded to handle this case. Ex: In [1]: class coerceTest: ...: def __init__(self, val): ...: self.val=val ...: ...: def __coerce__(self, other): ...: return self.val, other In [2]: test=coerceTest(5) In [3]: test Out[3]: <__main__.coerceTest instance at 0x00E29620> In [4]: result=test+10 In [5]: result Out[5]: 15 In [6]: test=5 In [7]: test Out[7]: 5 (I could've written a test to show that __coerce__ is only called when no __add__ is defined, but I'm lazy and its time to leave work!) -Jordan Greenberg ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python CGI Script
> -Original Message- > Subject: Re: [Tutor] Python CGI Script > > >query1 = """SELECT ABC FROM %s limit %s,%s"""\ > > % (self.tableid,self.rangeid1,self.rangeid2) > > Just as a note: please don't do this! *grin* > > Don't build query strings up like this: this is very prone to an SQL > injection attack. See: > > http://mail.python.org/pipermail/tutor/2003-April/022010.html > > which talks about this a bit more. > ___ > I just wanted to verify what I believe to be correct way of doing this. sql_statement = "INSERT INTO images (image) VALUES (%s)" cur.execute(sql_statement, (data_obj, )) Is it just moving the variable substitution to the execute statement as a tuple, so it will perform the proper quoting? Thanks, Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python CGI Script
On Wed, 2006-09-20 at 15:46 -0600, Mike Hansen wrote: > > > -Original Message- > > Subject: Re: [Tutor] Python CGI Script > > > > >query1 = """SELECT ABC FROM %s limit %s,%s"""\ > > > % (self.tableid,self.rangeid1,self.rangeid2) > > > > Just as a note: please don't do this! *grin* > > > > Don't build query strings up like this: this is very prone to an SQL > > injection attack. See: > > > > http://mail.python.org/pipermail/tutor/2003-April/022010.html > > > > which talks about this a bit more. > > ___ > > > > I just wanted to verify what I believe to be correct way of doing this. > > sql_statement = "INSERT INTO images (image) VALUES (%s)" > cur.execute(sql_statement, (data_obj, )) > > Is it just moving the variable substitution to the execute statement as > a tuple, so it will perform the proper quoting? Yes, this looks good. (Looks like MySQL paramstyle.) > > Thanks, > > Mike > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Overloading the assignment operator in a class
On 9/20/06, Alan Gauld <[EMAIL PROTECTED]> wrote: > > This all seems to work okay. > > > > I want the assignment operator ('=') > > There is no assignment operator in Python, assignment is a > binding of an object to a name. as others have mentioned, the assignment operator is used to assign an object to a name in the current namespace... IOW, you cannot "overload the assignment operator." __coerce__() is used for arithmetic operations, so this won't work either. what you really want to do is to allow (validated) access to mydie.value (e.g., self.value). instead of "mydie = 5" -- which is taking the 'mydie' name and reassigning it to the integer object that has a value of 5 (thus losing the reference to your instance object, decrementing its reference count, etc.), you want to allow the user to do something like: mydie.value = 5 ... BUT, you want that value to be validated before it actually assigns it to the mydie.value instance attribute. here is where properties become useful. you can create a getter, setter, and even a deleter and doc string if you want. here's how you use it... add the following to your class: def get_value(self): return self.__value # pretty much your set() method def set_value(self, newval): assert isinstance(newval, int), 'must be an int!' assert 1 <= newval <= self.n, 'invalid value!' self.__value = newval value = property(get_value, set_value, doc='value of mydie') - in actuality, the value is stored in self.__value, but access is via self.value. this should give you what you need provided you are happy with using "mydie.value = ..." vs. "mydie = ...", the latter of which will never work the way you want. with the addition of the above code, you can leave __init__() and roll() alone as the self.value = ... assignment will still call your property methods to do the assigning. (also note that roll() does not have to return self.value unless that is desired.) now, even with properties, the bad news is that someone can be sneaky and do something like "mydie.set_value(200)" to try and get around doing "mydie.value = 200". in other words, you cannot restrict access to the property methods. the good news is that there is a workaround to this. i have an example in one of the newly-written sections in (the 2nd ed of) my book that was inspired by the following cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 the crux of this recipe is that it is very much like using a closure to get your cake and eat it too. you stick your getter (and perhaps setter) into another scope which is then rendered inaccessible to the instance. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Paramstyle/sql injection [was Python CGI Script]
* Danny Yoo <[EMAIL PROTECTED]> [060920 10:41]: > >query1 = """SELECT ABC FROM %s limit %s,%s"""\ > > % (self.tableid,self.rangeid1,self.rangeid2) > > Just as a note: please don't do this! *grin* > > Don't build query strings up like this: this is very prone to an SQL > injection attack. See: > > http://mail.python.org/pipermail/tutor/2003-April/022010.html I'm glad you brought this up: Was talking to my partner about this. He's a perl programmer, and he told me that (if I understood him correctly) that the programmer is required by perl to use the 'prepare' function in the perl DBI prior to sending a select statement. If not done (again, if I understood him correctly) an exception is thrown. Is this correct? Now I'm off to writting a little 'script nanny' to check my python files for usage of Paramstyle. thanks tim > which talks about this a bit more. > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson <[EMAIL PROTECTED]> http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Paramstyle/sql injection [was Python CGI Script]
> Was talking to my partner about this. He's a perl programmer, and he > told me that (if I understood him correctly) that the programmer is > required by perl to use the 'prepare' function in the perl DBI prior to > sending a select statement. Hi Tim, Yes. That being said, Perl's prepare() statement is no guarantee to safe code. It leaves one to face interpolation temptation: ## Perl my $sth = $dbh->prepare("delete from some_table where name='$field_value'"); $sth->execute(); is just as dangerous as: ## Python cursor = conn.cursor() cursor.execute("delete from some_table where name = '%s'" % field_value) The lesson is that, in the absence of some automated lint-like tool support that can tell us "no you silly, don't do that", we humans are going to have to pick up the slack. We can write bad code in pretty much any language. Programmer education is something we need to do until then. Most of the developer communities around these languages have been around long enough to understand this common risk of SQL injection. In summary: if we're going to work with databases, we should use prepared statements unless we have a very good reason not to. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Overloading the assignment operator in a class
Carroll, Barry wrote: > How do I overload the '=' operator to give the desired behavior? This classic essay talks about the meaning of assignment in Python: http://www.effbot.org/zone/python-objects.htm Also I don't think there is any need to overload __lt__, etc.; just __cmp__ is enough, it will be used if the others are omitted. Details of why you might want to use the "rich" comparison operators are here: http://www.amk.ca/python/2.1/index.html#SECTION00050 Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor