我具有以下项目结构:
项目/ __ 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()
manage.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并未检测到要添加的任何表。
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.
为什么Flask-Migrate with Alembic无法检测模型并因此创建表?这是我尝试过的:
编辑:
这是models.py文件的示例
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))
答案 0 :(得分:2)
解决方案是将模型导入__init__.py文件,如下所示:
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
答案 1 :(得分:0)
我有同样的问题。该解决方案与@joe的解决方案非常相似
在路线文件中
from models import User
api_user = Namespace('user', description='user related operations')
在项目中/ __ init __。py
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)
blueprint = Blueprint('api', __name__, url_prefix=url_prefix)
api = Api(blueprint, doc='/documentation') # ,doc=False
app.register_blueprint(blueprint)
api.add_namespace(api_user)
return app
在create_app flask_migrate检测到的模型中添加api_user命名空间时