How can I prevent SQL injection in PYTHON-DJANGO?

Jayron Soares picture Jayron Soares · Dec 9, 2013 · Viewed 24.6k times · Source

If a lamer input is inserted into an SQL query directly, the application becomes vulnerable to SQL injection, like in the following example:

dinossauro = request.GET['username']

sql = "SELECT * FROM user_contacts WHERE username = '%s';" % username

To drop the tables or anything -- making the query:

INSERT INTO table (column) VALUES('`**`value'); DROP TABLE table;--`**`')

What may one do to prevent this?

Answer

Suor picture Suor · Dec 9, 2013

First, you probably should just use Django ORM, it will prevent any possibility of SQL injection.

If for any reason you can't or don't want to then you should use Python Database API. Here is the way you usually do that in Django:

from django.db import connection

cursor = connection.cursor()
cursor.execute('insert into table (column) values (%s)', (dinosaur,))
cursor.close()

You can also use handy python package to reduce the boilerplate:

from handy.db import do_sql

do_sql('insert into table (column) values (%s)', (dinosaur,))