我最近开始学习Flask,下面的教程希望我使用sqlite3作为数据库来设置一个待办事项列表应用程序,以存储用户名、密码和待办事项列表本身。到目前为止,我已经像教程一样设置了模式和模型,但我的数据库文件没有更新。我的表显示在数据库文件中,但它们是空的。我做错了什么?
这是模式:
import sqlite3
connection = sqlite3.connect('to_do_list.db', check_same_thread = False)
cursor = connection.cursor()
cursor.execute(
"""CREATE TABLE users(
id INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(32),
password VARCHAR(32)
);"""
)
connection.commit()
cursor.close()
connection.close()
以下是注册模式:
def signup(username, password):
connection = sqlite3.connect('to_do_list.db', check_same_thread = False)
cursor = connection.cursor()
cursor.execute( """SELECT password FROM users WHERE username = '{username}';""".format(username = username))
exist = cursor.fetchone()
if exist is None:
cursor.execute("""INSERT INTO users(username, password)VALUES('{username}', '{password}');""".format(username = username, password = password))
connection.commit()
cursor.close()
connection.close()
else:
return ('User already exists!')
这是烧瓶路线:
@app.route('/signup', methods = ['GET', 'POST'])
def signup():
if request.method == 'GET':
message = 'Please sign up!'
return render_template('signup.html', message = message)
else:
username = request.form['username']
password = request.form['password']
return render_template('todo.html')
我决定睡一觉,想出了解决方案。教程中对一些函数并不清楚,John Gordon的上述评论帮助我弄清楚了。我不得不调用路由函数中的模型代码。我还必须"导入模型",因为我的模型在不同的.py文件中。
新路由:
@app.route('/signup', methods = ['GET', 'POST'])
def signup():
if request.method == 'GET':
message = 'Please sign up!'
return render_template('signup.html', message = message)
else:
username = request.form['username']
password = request.form['password']
db = model.signup(username, password)
return render_template('todo.html')
感谢大家的投入!健康安全,节日快乐。
此处
import sqlite3
connection = sqlite3.connect('to_do_list.db', check_same_thread = False)
curr = connection.cursor()
curr.execute(
"""CREATE TABLE users(
id INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(32),
password VARCHAR(32)
);"""
)
curr.commit()
curr.close()
您将commit()
函数添加到connection
变量,而不是添加到光标。
编辑,也在这里:
def signup(username, password):
connection = sqlite3.connect('to_do_list.db', check_same_thread = False)
curr= connection.cursor()
curr.execute( """SELECT password FROM users WHERE username = '{username}';""".format(username = username))
exist = curr.fetchone()
if exist is None:
curr.execute("""INSERT INTO users(username, password)VALUES('{username}', '{password}');""".format(username = username, password = password))
curr.commit()
curr.close()
curr.close()
else:
return ('User already exists!')
重要信息如果已经创建了to_do_list.db
,则在编辑脚本后,请记住删除该文件,以便创建新文件。