简体   繁体   English

我的 Flask 应用程序如何检查 SQLite3 事务是否正在进行中?

[英]How can my Flask app check whether a SQLite3 transaction is in progress?

I am trying to build some smart error messages using the @app.errorhandler (500) feature.我正在尝试使用 @app.errorhandler (500) 功能构建一些智能错误消息。 For example, my route includes an INSERT command to the database:例如,我的路由包含一个到数据库的 INSERT 命令:

if request.method == "POST":
   userID = int(request.form.get("userID"))
   topicID = int(request.form.get("topicID"))
   db.execute("BEGIN TRANSACTION")
   db.execute("INSERT INTO UserToTopic (userID,topicID) VALUES (?,?)", userID, topicID)
   db.execute("COMMIT")

If that transaction violates a constraint, such as UNIQUE or FOREIGN_KEY, I want to catch the error and display a user-friendly message.如果该事务违反约束,例如 UNIQUE 或 FOREIGN_KEY,我想捕获错误并显示用户友好的消息。 To do this, I'm using the Flask @app.errorhandler as follows:为此,我使用 Flask @app.errorhandler 如下:

@app.errorhandler(500)
def internal_error(error):
    db.execute("ROLLBACK")
    return render_template('500.html'), 500

The "ROLLBACK" command works fine if I'm in the middle of a database transaction.如果我处于数据库事务的中间,“ROLLBACK”命令可以正常工作。 But sometimes the 500 error is not related to the db, and in those cases the ROLLBACK statement itself causes an error, because you can't rollback a transaction that never started.但有时 500 错误与数据库无关,在这些情况下,ROLLBACK 语句本身会导致错误,因为您无法回滚从未启动的事务。 So I'm looking for a method that returns a Boolean value that would be true if a db transaction is under way, and false if not, so I can use it to make the ROLLBACK conditional.因此,我正在寻找一种方法,该方法返回一个布尔值,如果 db 事务正在进行,则该值将为 true,否则为 false,因此我可以使用它来使 ROLLBACK 成为有条件的。 The only one I can find in the SQLite3 documentation is for a C interface , and I can't get it to work with my Python code.我可以在SQLite3 文档中找到的唯一一个是 C interface ,我无法让它与我的 Python 代码一起工作。 Any suggestions?有什么建议么?

I know that if I'm careful enough with my forms and routes, I can prevent 99% of potential violations of db rules.我知道如果我对表单和路由足够小心,我可以防止 99% 的潜在违反数据库规则的行为。 But I would still like a smart error catcher to protect me for the other 1%.但我仍然想要一个聪明的错误捕捉器来保护我剩下的 1%。

I don't know how transaction works in sqlite but what you are trying to do, you can achieve it by try/except statements我不知道 sqlite 中的事务是如何工作的,但是你想要做什么,你可以通过 try/except 语句来实现它

  1. use try/except within the function在函数中使用 try/except
try:
    db.execute("ROLLBACK")
except:
    pass
return render_template('500.html'), 500
  1. Use try/except when inserting data.插入数据时使用try/except。
from flask import abort
try:
    userID = int(request.form.get("userID"))
    [...]
except:
    db.rollback()
    abort(500)

I am not familiar with sqlite errors, if you know what specific error occurs except for that specific error.我不熟悉 sqlite 错误,如果您知道除了该特定错误之外会发生什么特定错误。

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

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