Flask-Migrate 不检测表 [英] Flask-Migrate not detecting tables

查看:96
本文介绍了Flask-Migrate 不检测表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下项目结构:

project/__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

db = SQLAlchemy()
migrate = Migrate()

def create_app():
    app = Flask(__name__)
    app.config.from_object(os.environ['APP_SETTINGS'])

    db.init_app(app)
    migrate.init_app(app, db)

    return app

run.py

from project import create_app
app = create_app()

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

ma​​nage.py

from flask_script import Manager
from flask_migrate import MigrateCommand
from project.models import *
from project import create_app


manager = Manager(create_app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()

然而,当我运行以下命令时,Flask-Migrate 没有检测到任何要添加的表.

Yet when I run the following commands, Flask-Migrate is not detecting any tables to be added.

python manage.py db init

输出:

Creating directory $HOME/Project/migrations ... done
Creating directory $HOME/Project/migrations/versions ... done
Generating $HOME/Project/migrations/script.py.mako ... done
Generating $HOME/Project/migrations/env.py ... done
Generating $HOME/Project/migrations/README ... done
Generating $HOME/Project/migrations/alembic.ini ... done
Please edit configuration/connection/logging settings in
'$HOME/Project/migrations/alembic.ini' before proceeding.

python manage.py db migrate

只输出:

INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.

为什么带有 Alembic 的 Flask-Migrate 不检测模型并因此创建表?这是我尝试过的:

Why is Flask-Migrate with Alembic not detecting the Models and therefore creating the tables? Here's what I've tried:

  • 删除数据库,从无到有
  • 在 manage.py 文件中创建自定义 db 类,但未检测到
  • 谷歌搜索这个问题的每一个答案,发现了很多类似的问题,但他们的解决方案都不适合我.

这是一个models.py文件的例子

Here is an example of the models.py file

from flask import current_app
from project import db
from flask_login import UserMixin

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

推荐答案

解决方案是像这样导入 __init__.py 文件中的模型:

The solution was to import the models in the __init__.py file like so:

def create_app():
    app = Flask(__name__)
    app.config.from_object(os.environ['APP_SETTINGS'])

    from project import models

    db.init_app(app)
    migrate.init_app(app, db)

    return app

这篇关于Flask-Migrate 不检测表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆