Django,如果使用原始SQL,应采取哪些步骤来避免SQL注入攻击? [英] Django,if using raw SQL, what steps should I take to avoid SQL injection attacks?

查看:44
本文介绍了Django,如果使用原始SQL,应采取哪些步骤来避免SQL注入攻击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读到ORM应该将SQL注入攻击的可能性降到最低.但是在Django中,有时ORM受到一定限制,我需要使用原始SQL.我应该采取什么步骤来避免SQL注入攻击?

I have read that ORM's should minimise the possibilities of SQL injection attacks. However in Django, sometimes the ORM is somewhat limited, and I need to use raw SQL. What steps should I take to avoid SQL injection attacks?

目前,我想检查一下查询字符串中的分号,但没有其他内容.如果我使用参数化查询,是否可以解决问题?是否有任何库可以将该字符串传递给我,以便我对其进行检查?

Currently I would know to check for semicolons in the query string, but not much else. If I use parametrised queries, will this solve the problem? Are there any libraries to pass the string to, that will check it for me?

推荐答案

文档说明以下内容:

如果需要执行参数化查询,则可以使用参数 raw()的参数:

>>> lname = 'Doe'
>>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])

params 是参数的列表或字典.您将使用%s 列表的查询字符串中的占位符,或%(key)s 占位符对于字典(其中的键由字典的键替换,当然),无论您的数据库引擎是什么.此类占位符将是替换为params参数中的参数.

params is a list or dictionary of parameters. You’ll use %s placeholders in the query string for a list, or %(key)s placeholders for a dictionary (where key is replaced by a dictionary key, of course), regardless of your database engine. Such placeholders will be replaced with parameters from the params argument.

这也是使用Python的DB-API传递参数的标准方法,可以正确清理查询.

This is also the standard way to pass parameters using Python's DB-API, which will sanitize your queries correctly.

无论您做什么,都不要进行字符串插值.

Whatever you do, don't do string interpolation.

这篇关于Django,如果使用原始SQL,应采取哪些步骤来避免SQL注入攻击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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