[英]Form doesn't save data permanently
嘗試使用 flask 和 sqlite3 創建一個簡單的 web 表單,我遇到了以下問題:
我運行了 flask,輸入了一些測試名稱和電子郵件,看到它們顯示在索引頁面上,但是當我 go 檢查數據庫中的最新行時,新數據沒有顯示。 目錄中又出現了一個新的 Lecture.db-journal 文件。
我不知道是什么導致了這種行為,所以希望這里的人能給我一些關於我做錯了什么的見解。 這是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
提前感謝您的關注。 歡迎任何評論。
你忘記了commit()
之后:
sql_command = "INSERT INTO registrants (name, email) VALUES (?, ?);"
db.execute(sql_command, [name, email])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.