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