简体   繁体   English

Flask 新手查询 sqlite3.OperationalError

[英]Flask Newbie Query sqlite3.OperationalError

I am newbie trying to learn flask by creating a simple todo app for this is below the python code i ham trying to execute but when i run i am getting sqlite3.OperationalError: no such column: todo.task i am unsure what i am missing here kindly assist我是新手,试图通过创建一个简单的 todo 应用程序来学习烧瓶,因为它低于我试图执行的 python 代码,但是当我运行时,我得到sqlite3.OperationalError: no such column: todo.task我不确定我错过了什么在这里请协助

import os
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy


project_dir = os.path.dirname(os.path.abspath(__file__))
# sqlite: // / prefix to tell SQLAlchemy which database engine we're using.
database_file = "sqlite:///{}".format(
    os.path.join(project_dir, "mydatabase.db"))

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)


class Todo(db.Model):
    
    id = db.Column(db.Integer, primary_key=True)
    task = db.Column(db.String(100))


@app.route('/', methods=["GET", "POST"])
def samplehome():
    todo_list = Todo.query.all()
    print(todo_list)

    
    return render_template("index.html", todo_list=todo_list)

    # if request.form:
    #     print(request.form)
    #     submitted = Todo(id=request.form.get("id"),task=request.form.get("task"))
    #     try:
    #         db.session.add(submitted)
    #         db.session.commit()
    #     except Exception as e:
    #         print(e)
    #         db.session.rollback()
    



if __name__ == "__main__":
    db.create_all()
    app.run(host='0.0.0.0', debug=True)

I think problem is you are not committing changes after db.create_all() function.我认为问题是你没有在 db.create_all() 函数之后提交更改。 You can try like this.你可以这样试试。

if __name__ == "__main__":
    db.create_all()
    db.session.commit()
    app.run(host='0.0.0.0', debug=True)

There is a similar question : SQLAlchemy create_all() does not create tables有一个类似的问题: SQLAlchemy create_all() 不创建表

Apart from your question, i dont suggest directly return your db class.除了你的问题,我不建议直接返回你的数据库类。 You can checkout MVC design pattern.您可以查看 MVC 设计模式。

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

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