Reputation: 3785
Using virtualenv with python3, Flask and sqlite3 to query a DB from a very basic web page. I am unable to INSERT the data entered into the fields on the home page. The /what_the_f
page keeps displaying "failure". What am I doing wrong? I suspect the try: cursor.excecute
but I am at a loss as to understand why this is not working and how to fix it so that the text and integer entered in the home.html pages are inserted into the DB.
The database initialization file:
import sqlite3
connection = sqlite3.connect('database.db')
connection.execute('CREATE TABLE movies (title TEXT, rating INTEGER)')
connection.close()
Database created manually:
(venv) Tue Mar 07 18:42:38$ python initdb.py
The python script:
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/what_the_f', methods = ['POST'])
def movie():
connection = sqlite3.connect('database.db')
cursor = connection.cursor # <-------------- LOOKIE THERE!
title = request.form['title']
rating = request.form['rating']
try:
cursor.execute('INSERT INTO movies (title,rating) VALUES (?,?)', (title,rating))
connection.commit()
message = "success"
except:
connection.rollback()
message = "failure"
finally:
connection.close()
return message
The /templates/home.html file:
<!DOCTYPE html>
<html>
<head>
<title>WTF? TEST</title>
</head>
<body>
<h1>WTactualF??</h1>
<form action="/what_the_f" method="POST">
<input name="title" />
<input name="rating" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I am just left with this report from the Flask server:
127.0.0.1 - - [07/Mar/2017 18:53:02] "POST /what_the_f HTTP/1.1" 200 -
Running Flask in debug mode, I get this when I exit from the server:
OSError: [Errno 9] Bad file descriptor
Upvotes: 2
Views: 1264
Reputation: 3785
Oh my... found it. I had
cursor = connection.cursor
and it should - of course - be
cursor = connection.cursor()
...I will go hide in shame now. Please don't look at me.
Upvotes: 2