如何将烧瓶应用程序连接到SQLite3数据库?

时间:2019-01-27 18:48:35

标签: python database flask sqlite

嗨,我正在尝试创建客户反馈表;我已经成功创建了所需的页面,但是在将应用程序连接到SQLite3数据库时遇到了困难。

因此,在我的代码python代码中,我试图从客户反馈表单中收集数据并将其保存在数据库中。

在反馈表单中,系统将提示他们输入姓名,从下拉列表框中选择一些答案,并在最后写评论。

答案将存储在数据库中(以供将来参考,例如报告等),并且用户将被重定向回首页,在此他们将能够看到其姓名和评论(取自反馈表)。

我看过关于sqlite3的教程,该教程易于理解和执行(对我而言,比MySQL容易得多),但我缺少一些东西,因为它无法连接到我的数据库。

我的python烧瓶代码:

from flask import Flask, render_template, redirect, url_for, request, session, flash, g
from functools import wraps
import sqlite3

app = Flask(__name__)
app.secret_key = "random_character_generator" # this would be random or anything the developer wants
app.database = "gymdatabase.db"

conn = sqlite3.connect(app.database)
c = conn.cursor()

def connect_db():
    return sqlite3.connect(app.database)

@app.route('/')
def home():
    g.db = connect_db()
    cur = g.db.execute('select * from posts')
    posts = [dict(name=row[0], welcome=row[1], equipment=row[2], cleanliness=row[3], interaction=row[4], comments=row[5], contact=row[6]) for row in cur.fetchall()]
    g.db.close()
    return render_template('gym_index.html', posts=posts)

@app.route('/feedback', methods=['POST'])
def feedback():
    return render_template('gym_feedback.html')

@app.route('/process', methods=['GET', 'POST'])
def process():
    g.db = connect_db()
    name = request.form['name']
    welcome = request.form['welcome']
    equipment = request.form['equipment']
    cleanliness = request.form['cleanliness']
    interaction = request.form['interaction']
    comment = request.form['comment']
    contact = request.form['yes_no']
    conn.commit()
    cur = g.db.execute(select * from posts)
    posts = [dict(name=row[0], welcome=row[1], equipment=row[2], cleanliness=row[3], interaction=row[4], comments=row[5], contact=row[6]) for row in cur.fetchall()]
    g.db.close()
    return redirect(url_for('home', posts=posts))   

当我尝试提交反馈表时,我得到: sqlite3.ProgrammingError:在线程中创建的SQLite对象只能在同一线程中使用。

我可以根据要求上传html文件;我不太确定我是否有空间与python文件一起使用。

1 个答案:

答案 0 :(得分:1)

我认为这是由于您的conn.commit()函数中的第process()行所致。您在Flask首次启动时声明了conn = sqlite3.connect(app.database),但是使用@app.route(...)函数装饰器定义的每个函数都会在不同的线程中被调用,以响应HTTP请求(如上述函数装饰器中所定义)。您可能想要执行以下操作:

@app.route('/process', methods=['GET', 'POST'])
def process():
    ...
    db = connect_db()
    cur = db.cursor()
    cur.execute("select * from posts")
    results = cur.fetchall()
    ...

您可以看到此链接以获取更多文档:https://docs.python.org/2/library/sqlite3.html

如果您提供有关代码失败位置的更多上下文,我可以编辑我的答案。