Flask sqlite3 INSERT失败,没有错误信息?

时间:2017-03-07 23:50:51

标签: python-3.x flask sqlite

使用virtualenv与python3,Flask和sqlite3从一个非常基本的网页查询数据库。我无法插入输入主页上字段的数据。 /what_the_f页面一直显示"失败"。我究竟做错了什么?我怀疑是try: cursor.excecute,但我不知道为什么这不起作用以及如何修复它以便将home.html页面中输入的文本和整数插入到数据库中。

数据库初始化文件:

import sqlite3
connection = sqlite3.connect('database.db')
connection.execute('CREATE TABLE movies (title TEXT, rating INTEGER)')
connection.close()

手动创建数据库:

(venv) Tue Mar 07 18:42:38$ python initdb.py

python脚本:

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

/templates/home.html文件:

<!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>

我刚收到Flask服务器的这份报告:

127.0.0.1 - - [07/Mar/2017 18:53:02] "POST /what_the_f HTTP/1.1" 200 -

在调试模式下运行Flask,当我从服务器退出时,我得到了这个:

OSError: [Errno 9] Bad file descriptor

1 个答案:

答案 0 :(得分:1)

哦,我的......找到了。我有 cursor = connection.cursor它应该 - 当然 - 应该是 cursor = connection.cursor()

......我现在会羞于羞辱。请不要看我。