run.py
db = SQLAlchemy()
migrate = Migrate()
def create_app():
app = Flask(__name__)
db.app = app
db.init_app(app)
migrate.init_app(app, db)
return app
if __name__ == '__main__':
application = create_app()
application.run()
manage.py
from flask_migrate import MigrateCommand, Manager
from run import create_app
manager = Manager(create_app())
manager.add_command('db', MigrateCommand)
当我运行时:python manage.py db init
Traceback (most recent call last):
File "manage.py", line 6, in <module>
manager = Manager(create_app())
TypeError: 'NoneType' object is not callable
当我跑:flask db init
Usage: flask db init [OPTIONS]
Error: Could not locate Flask application. You did not provide the FLASK_APP environment variable.
For more information see http://flask.pocoo.org/docs/latest/quickstart/
我尝试将FLASK_APP导出为run,run.py,run.create_app,run:create_app(),但我仍然收到上面显示的错误。导致此错误的原因是什么?
答案 0 :(得分:2)
flask_migrate
会尝试使用flask-script
中的管理员,但仅在安装了flask-script
时才会使用。
简单地做,它应该工作。您也可以直接从flask_script
导入。
pip install flask_script
<强> manage.py 强>
from flask_migrate import MigrateCommand
from flask_script import Manager
from run import create_app
app = create_app()
manager = Manager(app)
manager.add_command('db', MigrateCommand)
答案 1 :(得分:2)
运行Flask-Migrate命令有两种方法。较新的方法使用Flask CLI,较旧的方法使用Flask-Script。由于您似乎没有安装Flask-Script,我将假设您打算使用Flask CLI。
所以你需要扔掉manage.py
因为那只适用于Flask-Script。然后将application
变量移动到全局范围:
db = SQLAlchemy()
migrate = Migrate()
def create_app():
app = Flask(__name__)
db.app = app
db.init_app(app)
migrate.init_app(app, db)
return app
application = create_app()
if __name__ == '__main__':
application.run()
然后设置FLASK_APP
变量:
$ export FLASK_APP=run.py
现在您应该可以使用flask run
运行应用程序,使用flask db <command>
运行数据库命令。