On Tue, Mar 3, 2009 at 2:04 PM, Tim Allen <screwt...@froup.com> wrote:
> On Tue, Mar 03, 2009 at 01:17:48PM +0100, Pet wrote: > > what is a proper way to escape user input in database query strings? > > I've used quote from twisted.enterprise.util, but it is deprecated now. > > Is there any other module for this purpose? > > The correct way to escape user input is not to do it at all, but rather > to leave it up to the DB-API module you're using: > > from twisted.enterprise.adbapi import ConnectionPool > > pool = ConnectionPool("psycopg2") > d = pool.runQuery(""" > SELECT * > FROM students > WHERE name = %s > """, "Robert '); DROP TABLE students;--") > > Note that although I've used "%s" in the query, this is not normal > Python string-formatting, the "%s" is just tells the DB-API module I'm > using (in this case, psycopg2 for PostgreSQL) to quote one of the extra > parameters and insert in that spot. Look up "paramstyle" in the DB-API > spec[1] and the documentation for the DB-API module you're using for > more details. > > [1] http://www.python.org/dev/peps/pep-0249/ > > _______________________________________________ > Twisted-Python mailing list > Twisted-Python@twistedmatrix.com > http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python > Thanks for all your answers! It works fine in that way. But what, if I compose my query? For example: def getData(self, type=''): id = 1 if type: str = " AND mytype = %s " % type str = '' query = "SELECT * FROM table WHERE id = %s %s " % (id,str) cur.execute(query) I mean, str part is not always there and I need escape it only if type is passed to function Thanks, Pet
_______________________________________________ Twisted-Python mailing list Twisted-Python@twistedmatrix.com http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python