在 python 中使用字典更新 mysql 表条目的安全方法(防止 SQL 注入)
P粉627427202
P粉627427202 2023-09-08 20:06:07
0
1
602

我正在为我的 web 应用程序编写一个辅助函数,该函数根据从外部 API(不是用户输入的)获取的一些信息来更新数据库。我有以下代码,但它被 Bandit python 包标记为“不安全”。

理想情况下,我可以以硬编码要更新的列的方式编写一个函数,但我认为它也应该可以动态实现。

这是更新表的安全方法(不可能进行 SQL 注入)吗?

import mysql.connector as database

def update_message_by_uid(uid: str, update_dict: dict) -> None:

    # Fetches the previous entry from the database using the unique identifier
    message_info_dict = get_message_by_uid(uid)

    # check that all the keys of the update dict are also in the original dict
    assert set(update_dict.keys()) <= set(
        message_info_dict.keys()
    ), "Some of the keys in the dictionary passed are not valid database columns"

    # We update the entry for all entries in the dictionary containing the updates
    statement = 'UPDATE messages SET {}  WHERE uid = %s'.format(", ".join('{}=%s'.format(k) for k in update_dict))


    # Concatenates the values of the dict with the unique identifier to pass it to the execution method as one variable
    data = list(update_dict.values()) + [uid]

    cursor.execute(statement, data)

P粉627427202
P粉627427202

全部回复(1)
P粉926174288

您应该将列名放在反引号中,以防列名是 SQL 保留关键字 或包含空格、标点符号或国际字符。还要确保列名称中的反引号字符替换为两个反引号。

assignments = ", ".join(f"`{k.replace('`', '``')}`=%s" for k in update_dict)
statement = f"UPDATE messages SET {assignments}  WHERE uid = %s"

我更喜欢使用 f 字符串而不是 format()。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!