sqlite3.OperationalError:没有这样的表:todo

时间:2019-08-02 03:45:27

标签: python flask flask-sqlalchemy

我想使用Flask模块创建一个Web框架。但是,我的代码中有一个我无法解决的错误。这是我的代码:

from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(200), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

def __repr__(self):
    return '<Task %r>' % self.id

@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
    task_content = request.form['content']
    new_task = Todo(content=task_content)

    try:
        db.session.add(new_task)
        db.session.commit()
        return redirect('/')
    except:
        return 'There was an issue adding your task'
else:
    tasks = Todo.query.order_by(Todo.date_created).all()
    return render_template('index.html', tasks=tasks)

@app.route('/delete/<int:id>')
def delete(id):
    task_to_delete = Todo.query.get_or_404(id)

try:
    db.session.delete(task_to_delete)
    db.session.commit()
    return redirect('/')
except:
    return 'There was a problem deleting that task'

@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    task = Todo.query.get_or_404(id)
if request.method == 'POST':
    task.content = request.form['content']

    try:
        db.session.commit()
        return redirect('/')
    except: 
        return 'There was an issue updating your task' 
else:
    return render_template('update.html', task=task)

if __name__ == "__main__":
    app.run(debug=True)

此代码显示的错误是

sqlite3.OperationalError: no such table: todo

我期望的Web框架是我可以更新和删除任务列上的任何任务。我期望的Web框架是:

    Task        Added   Action
Wash dishes   2/8/2019  Delete
                        Update 

有关信息,“删除”和“更新”操作是删除或更新特定任务的选项。有人可以帮助我解决此错误吗?谢谢大家。

1 个答案:

答案 0 :(得分:0)

您必须在文件$Mrespone = $this->Tracking->getTracking(); return view('tracking/index'['respon'=>$Mrespone]); 中创建表todo

test.db不会自动创建它,因此您必须在代码中使用(在类Flask/SQLAlchemy之后)

Todo

但是只能使用一次,以后再删除。

请参见official documentation for flask_sqlalchemy