Reputation: 195
Trying to create a simple web form with flask and sqlite3 I faced the following problem:
I ran flask, enter some test names and emails, see them displayed on the index page but when I go check the database for the latest rows the new data doesn't show up. In turn a new lecture.db-journal file appeared in the directory.
I don't know what is causing this behaviour so hopefully someone here can give me some insight on what I'm doing wrong. Here is the 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("/")
Here is the index.html for displaying the data:
<!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>
And the register.html file with the form:
<!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>
The http status seems normal:
"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
Thanks for your attention in advance! Any remarks are welcomed.
Upvotes: 0
Views: 258
Reputation: 828
You forgot to commit()
after :
sql_command = "INSERT INTO registrants (name, email) VALUES (?, ?);"
db.execute(sql_command, [name, email])
https://docs.python.org/3.8/library/sqlite3.html
Upvotes: 1