python - 即使调用 Flask-SQLAlchemy create_all,表也不可用

标签 python flask flask-sqlalchemy

我正在尝试从数据库中获取记录,但我得到了

OperationalError: (sqlite3.OperationalError) no such table: driver

即使我定义了模型并调用了db.create_all()。为什么这不起作用?

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

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

class Driver(db.Model):
    id = db.Column(db.Integer, primary_key=True)

@app.route('/')
def index():
    result = Driver.query.all()
    return render_template('index.html', result=result)

最佳答案

您在定义模型之前调用 create_all。定义或导入所有模型后,将 create_all 移至此处。

class Driver(db.Model):
    ...

db.create_all()

关于python - 即使调用 Flask-SQLAlchemy create_all,表也不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42351003/

相关文章:

python - $.ajax 函数 : send json data : parse at serverside function

python - 分组依据这个或那个

python - pytest `AssertionError: View function mapping is overwriting an existing endpoint function:` 注册蓝图时 flask 休息

python - Elastic Beanstalk 不适用于 SQLite

python - 在 Flask 和非 Flask 程序中使用相同的数据库抽象

python - python中对象没有属性错误

python - 在插入行之前将行添加到另一个表

python - pip 不存在或无法在 virtualenv 中执行

sql-server - 如何使用经典映射在 SQLAlchemy 中重新定义同名表

python - TypeError : sqlalchemy. orm.attributes.InstrumentedAttribute 对象位于 0x7f86789f9bf8 不可 JSON 序列化