【问题标题】:Flask sqlite3 INSERT failure, no error message?Flask sqlite3 INSERT 失败,没有错误信息?
【发布时间】:2017-03-07 23:50:50
【问题描述】:

使用带有 python3、Flask 和 sqlite3 的 virtualenv 从一个非常基本的网页查询数据库。我无法插入输入到主页字段中的数据。 /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

【问题讨论】:

    标签: python-3.x flask sqlite


    【解决方案1】:

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

    ...我现在要羞愧地躲起来了。请不要看我。

    【讨论】:

    • 只是做了同样的事情,拍了拍额头
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2020-12-25
    • 2021-10-08
    • 2016-10-12
    • 1970-01-01
    相关资源
    最近更新 更多