python-3.x - 将 werkzeug 库 generate_password_hash() 函数中的值插入到 postgresql 表中
问题描述
我正在尝试创建一个表格供用户注册。使用烧瓶和 Postgresql 数据库。
我写了一个简单的类,所以每次我的应用程序将某些内容写入数据库时,我都不必重复相同的 n 行:
这是代码:
数据库.py:
....
import os
import errno
import psycopg2
class DbConnect:
def __init__ (
.....
def dbconfig(self):
.....
def command(self, command:str,parameters:tuple):
connection = None
if isinstance (command,str) and isinstance(parameters,tuple):
#typecheck command and parameters
if len(self.dbsettings) > 0:
try:
connection = psycopg2.connect(**self.dbsettings)
with connection.cursor() as cur:
#creates a cursor needed to execute commands on the database
#makes sure that cursor is closed once done
cur.execute(command,parameters)
#executes the specified SQL Query
result = cur.fetchall()
#returns the result of the last execute call as a list of tuples
print("executed")
return result
except (Exception, psycopg2.DatabaseError,psycopg2.OperationalError) as error:
print(error)
return(error)
finally:
# this block gets checked at the end of try except but before it returns, thus making sure the database connection is closed
if connection != None:
connection.commit()
#writes the changes made to the database
connection.close()
print("connection closed")
else:
# returns a Type error if the variables are not a tuple and a string
raise TypeError
我现在想将来自 werkzeug 库的 generate_password_hash() 的返回值插入到该数据库的用户表中,所以我尝试了这个:
username = "username"
password = "password"
hashed_pass = generate_password_hash(password)
print(hashed_pass)
db.command("INSERT INTO users (passhash,username) VALUES %s, %s",(hashed_pass,username))
并得到以下结果:
pbkdf2:sha256:150000$pybP9g2U$bc8dce2a93a6699b312570cac9b15bf690d8cf6d8e9b22cd23b4fe604468a600
“'pbkdf2:sha256:150000$pybP9g2U$bc8dce2a93a6699b312570cac9b15bf690d8cf6d8e9b22cd23b4fe604468a600'”处或附近的 dbex 语法错误第 1 行:INSERT INTO users (passhash,username) VALUES 'pbkdf2...:
连接关闭
虽然打印出来的行是 id 所期望的,但它似乎执行它用单引号 (') 包装命令,这使我的数据库感到困惑。浏览 psycopg2 的文档时,我还没有找到一种明显的方法来改变这一点,尽管 SQL 字符串组合看起来很有希望,但我现在无法确定它的正面或反面。
这里的任何人都知道如何处理这个问题?
谢谢你。
解决方案
推荐阅读
- r - 如何更正ggplot2中的条形标签数量
- vue.js - vue-i18n 多语言路由
- python - 无法使用 PyMongo 将 MongoDB 与 Django 连接
- json - 如何将带有文本的图像编码为属性字符串
- android - 我可以为所有活动创建一个功能,播放,暂停音乐
- javascript - 我创建了两个函数:“opendoor”和“closedoor”。我试图按顺序调用它们,但只执行了最后一个
- r - 为元数据创建可变长度的样本向量
- mysql - 多次选择最近期货到期的利率 SQL
- dataframe - 当操作限制是行只能循环而不是一次全部时,如何在 Spark Data Frame lineage 上适合顺序操作?
- jsf - 将上下文传递给函数有用吗?