简体   繁体   English

Python psycopg2字符串插值格式与%

[英]Python psycopg2 string interpolation format vs %

According to the psycopg2 documentation ( http://initd.org/psycopg/docs/connection.html ) it states: 根据psycopg2文档( http://initd.org/psycopg/docs/connection.html )指出:

Warning Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.

In the warning it specifically references not doing something like this: 在警告中,它特别引用了不执行以下操作:

cur.execute(SQL % data)

Does this warning also apply to the following using format? 此警告是否也适用于以下使用格式?

cur.execute(SQL.format(data))

I do not know the internals of format, but I am assuming it is using % string interop underneath which would make it's usage unadvisable 我不知道format的内部原理,但是我假设它在下面使用%string interop,这将使它的用法不建议使用

SQL.format() (where SQL is a regular ol' Python string) doesn't actually use % interpolation under the hood, but it has the same pitfall: the values you substitute in are not properly escaped for SQL (how could they be; Python has no idea that SQL is a SQL statement) and your SQL statement could then be subject to injection attacks. SQL.format() (其中SQL是常规的SQL.format()字符串)实际上并未在SQL.format()使用%插值,但存在相同的陷阱:您替换的值无法正确地转义为SQL(怎么可能是; Python不知道SQL是SQL语句),然后您的SQL语句可能会受到注入攻击。

Your various SQL modules have methods to prevent this issue and you should use them instead. 您的各种SQL模块都有防止此问题的方法,应改为使用它们。

Yes, it does. 是的,它确实。 String interpolation methods are fragile because they allow SQL injection attack. 字符串插值方法很脆弱,因为它们允许SQL注入攻击。 Using external (user-provided) data as a parameters in parametrised queries (instead of building query string) makes this kind of attack impossible. 在参数化查询中使用外部(用户提供)数据作为参数(而不是构建查询字符串)使这种攻击变得不可能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM