python - 尽管在数据库中添加了行,但 SQL 查询在点击后退按钮后不会返回新添加的行
问题描述
我有一个烧瓶应用程序,它有一个注册表单,将数据添加到将数据添加到 SQLite 数据库POST
的视图中。registration.py
每次注册时,都会在数据库中插入一个新行。
预计会发生什么:
提交表单后,如果用户点击浏览器中的后退按钮并尝试再次提交表单,下面的代码应该是
try
检查电子邮件是否存在- 如果
exception
(电子邮件不存在)插入数据
问题:
当用户点击后退按钮并再次提交表单时,try
块中的代码无法识别先前(在点击后退按钮之前)添加的行。选择查询失败。
甚至更奇怪的事情:
但是,当我只是在try
块之前打印出数据库中的所有行时,这显示了email
刚刚添加的行。选择查询虽然没有看到它。
Registration.py
问题块:
db = get_db()
# Dumping to log to check if the db actually has the row
cur_e = db.execute('SELECT user_id, user_email FROM cld_user')
ie = cur_e.fetchall()
for i in ie:
print "ID: {} | Email: {}".format(i[0], i[1])
print "end of ID dump"
print user_email
# The above code does print out the row (even after hitting the back button)
try:
# This block however, fails when user submits the form after hitting the back button
print "Trying"
cur_ps = db.execute('SELECT user_id, user_uid FROM cld_user \
WHERE user_email = ?', [user_email])
user_id = cur_ps.fetchone()[0]
user_uid = cur_ps.fetchone()[1]
print "Row exists"
flash(user_id, "success")
except Exception:
print "Exception"
cur_p = db.execute('INSERT OR IGNORE INTO cld_user \
(user_uid, user_name, user_email, user_contact) \
VALUES (?, ?, ?, ?)', [user_uid, user_name,
user_email, user_contact])
user_id = cur_p.lastrowid
print "No row exists"
flash(user_id, "success")
解决方案
try
块总是失败。user_uid = cur_ps.fetchone()[0]
如果查询没有返回任何行,它将在这一行失败。user_uid = cur_ps.fetchone()[1]
如果查询返回一行,它将在这一行失败。
fetchone
一次返回一行。此行user_id = cur_ps.fetchone()[0]
正在查找返回的列表中的元素 0 fetchone
。如果没有匹配 user_email 的行,它会失败并显示“None type object not subscriptable”,因此执行except
块
如果返回一行,则控制移至该行user_uid = cur_ps.fetchone()[1]
。如果查询返回 2 行或更多行,则此行将成功。如果它只返回 1 行,则该行将失败,因为结果fetchone
为 None,它会给出“None type object is not subscriptable”。
关于可能的更正:将一个变量设置为 的结果fetchone
,例如row = cur_ps.fetchone()
,然后将其他变量分别设置为row[0]
和row[1]
。
推荐阅读
- git - 如何忽略git中的文件
- java - 为什么我在存储库上收到错误“未找到属性”?
- nginx - Next js 和 google 分析在 nginx 反向代理后面不起作用
- javascript - Bootstrap-vue 导航栏未按预期呈现
- websocket - 如何在不暂停jmeter websocket的情况下回答传入的ping?
- r - 按列分组,然后自动计算以相同字母开头的多列
- javascript - 如何在网站中进行共享元素转换
- typescript - 打字稿:使用正则表达式作为类型键
- php - GET http://localhost/bootstrap.min.css net::ERR_ABORTED 404(未找到)
- javascript - 如何使用 javascript 从节点应用程序引用 Azure 配置应用程序设置