试图用flask和sqlite3创建一个简单的Web表单,我遇到了以下问题:
我运行了烧瓶,输入了一些测试名称和电子邮件,并在索引页面上看到了它们,但是当我去检查数据库中的最新行时,没有显示新数据。反过来,目录中出现了一个新的讲课.db-新闻文件。
我不知道是什么导致了这种行为,因此希望这里的人可以让我对我做错的事情有所了解。这是 application.py :
from flask import Flask, render_template, request, redirect
import sqlite3
app = Flask(__name__)
# Connect with the lecture registrants database.
# Database structure - 'id' INTEGER | 'name' VARCHAR(255) | 'email' VARCHAR(255)
connection = sqlite3.connect("lecture.db")
# Setting row_factory property of
# connection object to sqlite3.Row(sqlite3.Row is an implementation of
# row_factory).
connection.row_factory = sqlite3.Row
# cursor
db = connection.cursor()
# Display all the people who registered on the route page.
@app.route("/")
def index():
sql_command = "SELECT * FROM registrants;"
db.execute(sql_command)
rows = db.fetchall()
# Returns a list of dictionaries, each item in list(each dictionary)
# represents a row of the table.
return render_template("index.html", rows=rows)
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "GET":
return render_template("register.html")
else:
# Update the database with the new name and email.
name = request.form.get("name")
email = request.form.get("email")
sql_command = "INSERT INTO registrants (name, email) VALUES (?, ?);"
db.execute(sql_command, [name, email])
return redirect("/")
以下是用于显示数据的 index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Registrants</title>
</head>
<body>
<h1>List of all registrants</h1>
<ul>
{% for row in rows %}
<li>{{ row["name"] }} ({{ row["email"] }})</li>
{% endfor %}
</ul>
<a href="/register">Register here.</a>
</body>
</html>
和 register.html 文件,格式为:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Register</title>
</head>
<body>
<h1>Register for the lecture</h1>
<form action="/register" method="post">
<input type="text" name="name" placeholder="Name">
<input type="text" name="email" placeholder="Email address">
<input type="submit">
</form>
</body>
</html>
http状态似乎正常:
"GET / HTTP/1.0" 200 -
"GET /register HTTP/1.0" 200 -
"POST /register HTTP/1.0" 302 -
"GET / HTTP/1.0" 200 -
"GET / HTTP/1.0" 200
谢谢您的关注!欢迎任何评论。
答案 0 :(得分:1)
您在以下时间忘记了commit()
:
sql_command = "INSERT INTO registrants (name, email) VALUES (?, ?);"
db.execute(sql_command, [name, email])