Django,if using raw SQL, what steps should I take to avoid SQL injection attacks?

牧云@^-^@ 提交于 2019-12-07 05:24:10

问题


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?


回答1:


The documentation states the following:

If you need to perform parameterized queries, you can use the params argument to raw():

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

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.

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.




回答2:


You have to bind your parameters! A complete guide with examples and solutions you can find here:

http://www.djangobook.com/en/2.0/chapter20.html



来源:https://stackoverflow.com/questions/24753605/django-if-using-raw-sql-what-steps-should-i-take-to-avoid-sql-injection-attacks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!