繁体   English   中英

表单不会永久保存数据

[英]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])

https://docs.python.org/3.8/library/sqlite3.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM