如何解决使用psycopg2在PostgreSQL中创建带有密码的用户时出现错误
我正在尝试创建受保护的代码,该代码不会对SQL Injection攻击开放。目前,我想创建3个使用不同密码的用户。如下所示:
import psycopg2
from psycopg2 import connect,extensions,sql
# Importing a 0 integer so the process can pass without bothering w/ extensions
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
user1 = "jimmy"
user2 = "ray"
user3 = "billy"
secret1 = "gelatto"
secret3 = "cookies"
secret2 = "vanilla"
cursor.execute(sql.SQL("CREATE USER {users} WITH PASSWORD {password}")
.format(users=sql.Identifier(user1),password=sql.Identifier(secret1)))
cursor.execute(sql.SQL("CREATE USER {users} WITH PASSWORD {password}")
.format(users=sql.Identifier(user2),password=sql.Identifier(secret2)))
cursor.execute(sql.SQL("CREATE USER {users} WITH PASSWORD {password}")
.format(users=sql.Identifier(user3),password=sql.Identifier(secret3)))
cursor.execute(sql.SQL("GRANT {role} TO {user}")
.format(role=sql.Identifier(readWrite),user=sql.Identifier(user1)))
cursor.execute(sql.SQL("GRANT {role} TO {user}")
.format(role=sql.Identifier(readWrite),user=sql.Identifier(user2)))
cursor.execute(sql.SQL("GRANT {role} TO {user}")
.format(role=sql.Identifier(readOnly),user=sql.Identifier(user3)))
但是,由于密码在“”中需要为“”时被关闭,因此我收到一条错误消息。有人可以帮助我解决他们的想法吗?
LINE 1: CREATE USER "jimmy" WITH PASSWORD "gelatto"
解决方法
如果您正在寻找指针,我会像这样编写此脚本:
import collections
import psycopg2
from psycopg2 import connect,extensions,sql
# Importing a 0 integer so the process can pass without bothering w/ extensions
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
NewUser = collections.namedtuple('NewUser','username password access')
users = [
NewUser('jimmy','gelatto','readwrite'),NewUser('ray','cookies',NewUser('billy','vanilla','readonly')
]
with psycopg2.connect('dbname=morganek') as conn:
cur: psycopg2.extensions.cursor = conn.cursor()
for user in users:
cur.execute(
sql.SQL("create user {username} with password %s")
.format(username=sql.Identifier(user.username)),(user.password,)
)
cur.execute(
sql.SQL("grant {access} to {username}")
.format(
access=sql.Identifier(user.access),username=sql.Identifier(user.username)
)
)
conn.commit()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。