【发布时间】:2019-01-27 18:48:35
【问题描述】:
您好,我正在尝试创建客户反馈表;我已经设法创建了我需要的页面,但是我在将我的应用程序连接到我的 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 文件一起这样做。
【问题讨论】:
-
你是什么意思,“它不会连接”?发生什么了?你得到什么错误? (注意,在这段代码中,您实际上没有向数据库中插入任何内容。)
标签: python database flask sqlite