如何防止 PYTHON-DJANGO 中的 SQL 注入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20468143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I prevent SQL injection in PYTHON-DJANGO?
提问by Jayron Soares
If a lamer input is inserted into an SQL query directly, the application becomes vulnerable to SQL injection, like in the following example:
如果将 lamer 输入直接插入到 SQL 查询中,应用程序就容易受到 SQL 注入的攻击,如下例所示:
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?
可以做些什么来防止这种情况发生?
回答by cstrutton
From the Django Docs:
来自Django 文档:
SQL injection protection
SQL injection is a type of attack where a malicious user is able to execute arbitrary SQL code on a database. This can result in records being deleted or data leakage.
By using Django's querysets, the resulting SQL will be properly escaped by the underlying database driver. However, Django also gives developers power to write raw queries or execute custom sql. These capabilities should be used sparingly and you should always be careful to properly escape any parameters that the user can control. In addition, you should exercise caution when using extra().
SQL注入保护
SQL 注入是一种攻击,恶意用户能够在数据库上执行任意 SQL 代码。这可能导致记录被删除或数据泄露。
通过使用 Django 的查询集,生成的 SQL 将被底层数据库驱动程序正确转义。但是,Django 还赋予开发人员编写原始查询或执行自定义 sql 的能力。这些功能应该谨慎使用,并且您应该始终小心正确地转义用户可以控制的任何参数。此外,在使用 extra() 时应小心谨慎。
回答by Suor
First, you probably should just use Django ORM, it will prevent any possibility of SQL injection.
首先,您可能应该只使用Django ORM,它会防止任何 SQL 注入的可能性。
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:
如果出于任何原因您不能或不想,那么您应该使用Python Database API。以下是您通常在 Django 中执行此操作的方式:
from django.db import connection
cursor = connection.cursor()
cursor.execute('insert into table (column) values (%s)', (dinosaur,))
cursor.close()
You can also use handypython package to reduce the boilerplate:
您还可以使用方便的python 包来减少样板:
from handy.db import do_sql
do_sql('insert into table (column) values (%s)', (dinosaur,))
回答by Chris
If you are using .extra()the syntax is:
如果您使用.extra()的语法是:
YourModel.objects.extra(where=['title LIKE %s'], params=['%123%321%'])
Repeating here from this answeras this is hard to find, and the docsthat say "you should always be careful to properly escape any parameters"do not go on to say howto properly escape them!
从这个答案在这里重复,因为这很难找到,并且说的文档"you should always be careful to properly escape any parameters"没有继续说如何正确地逃避它们!

