如何防止PYTHON-DJANGO中的SQL注入? [英] How can I prevent SQL injection in PYTHON-DJANGO?

查看:373
本文介绍了如何防止PYTHON-DJANGO中的SQL注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果将直接输入插入到SQL查询中,则应用程序容易受到SQL注入的攻击,如下例所示:

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;--`**`')

如何防止这种情况?

推荐答案

首先,您可能应该只使用 Django ORM ,它将防止SQL注入的任何可能性。

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

如果出于任何原因您不能或不想这样做,您应该使用 Python数据库API 。这是在Django中通常使用的方法:

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()

您还可以使用方便的 python软件包以减少样板:

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,))

这篇关于如何防止PYTHON-DJANGO中的SQL注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆