Flask webhook Python代码无法更新SQLite数据库表问题求助
问题复现
尝试通过Flask webhook更新SQLite数据库,手动在Python控制台输入相关命令可正常运行,但Flask webhook触发时无法更新SQLite数据库,程序似乎执行到cursor.execute()行就出现异常。
相关代码
Webhook接口代码
@app.route('/trendanalyser', methods=['POST']) def trendanalyser(): data = json.loads(request.data) if data['passphrase'] == config.WEBHOOK_PASSPHRASE: # Init update variables tastate = data['TrendAnalyser'] date_format = datetime.today() date_update = date_format.strftime("%d/%m/%Y %H:%M:%S") update_data = ((tastate), (date_update)) # Database connection connection = sqlite3.connect('TAState15min.db') cursor = connection.cursor() # Database Update update_query = """Update TrendAnalyser set state = ?, date = ? where id = 1""" cursor.execute(update_query, update_data) connection.commit() return("Record Updated successfully") cursor.close() else: return {"invalide passphrase"}
数据库创建代码
# Database connection conn = sqlite3.connect("TAState15min.db") cursor = conn.cursor() # Create table sql_query = """ CREATE TABLE TrendAnalyser ( id integer PRIMARY KEY, state text, date text )""" cursor.execute(sql_query) # Create empty row with ID at 1 insert_query = """INSERT INTO TrendAnalyser (id, state, date) VALUES (1, 'Null', 'Null');""" cursor.execute(insert_query) conn.commit() # Close database connexion cursor.close()
问题根因与修复方案
1. 核心问题:数据库相对路径错误
Flask应用运行时的工作目录和手动执行Python控制台的工作目录通常不一致,使用相对路径TAState15min.db连接数据库时,Flask进程会在自身工作目录下查找数据库文件,找不到就会自动新建一个空白数据库,空白库没有对应的TrendAnalyser表,执行SQL时就会抛出异常。
修复方法:使用绝对路径定位数据库文件,示例如下:
import os # 取当前脚本所在目录作为基准目录 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 拼接生成数据库绝对路径 db_path = os.path.join(BASE_DIR, 'TAState15min.db') # 用绝对路径连接数据库 connection = sqlite3.connect(db_path)
2. 其他需要修正的代码问题
- 游标关闭逻辑位置错误:
cursor.close()写在了return语句之后,永远不会执行,建议调整到return之前,或者使用上下文管理器自动管理数据库连接、自动提交、自动关闭资源:
with sqlite3.connect(db_path) as connection: cursor = connection.cursor() update_query = """Update TrendAnalyser set state = ?, date = ? where id = 1""" cursor.execute(update_query, update_data) # 退出with块时自动提交并关闭连接,不需要手动写commit和close逻辑
- 返回值格式错误:校验失败分支返回的是集合
{"invalide passphrase"},不符合Flask返回规范,应改为字典并搭配对应HTTP状态码:
else: return {"error": "invalid passphrase"}, 403
- 缺少异常捕获:建议增加try-except块捕获数据库操作异常并打印日志,方便后续排查问题。
内容的提问来源于stack exchange,提问作者Florian Huon
相关产品推荐
相关产品推荐

