Flask框架使模型和数据同步的方法?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!

使用ORM时,需要执行迁移操作以便在模型和持久化数据之间保持同步。我们使用Flask-Migrate这个扩展来完成该任务。

首先安装:

$pipinstallflask-migrate$pipinstallflask_script

然后在代码中引入:

fromflask_scriptimportManagerfromflask_migrateimportMigrate,MigrateCommand

进行必要的配置:

migrate=Migrate(app,db)manager=Manager(app)manager.add_command('db',MigrateCommand)

运行管理器:

if__name__=='__main__':manager.run()

完整的代码如下:

fromflaskimportFlaskfromflask_sqlalchemyimportSQLAlchemyfromflask_scriptimportManagerfromflask_migrateimportMigrate,MigrateCommandapp=Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI']='postgresql://localhost/appdb'db=SQLAlchemy(app)migrate=Migrate(app,db)manager=Manager(app)manager.add_command('db',MigrateCommand)classPost(db.Model):id=db.Column(db.Integer(),primary_key=True)title=db.Column(db.String(80),unique=True)post_text=db.Column(db.String(255))def__init__(self,title,post_text):self.title=titleself.post_text=post_text@app.route('/')defindex():return"HelloWorld"if__name__=="__main__":manager.run()

使用如下的命令初始化Alembic:

$pythonapp.pydbinitCreatingdirectory/Users/Vihar/Desktop/flask-databases/migrations...done.........Generating/Users/Vihar/Desktop/flask-databases/migrations/alembic.ini...done

执行第一个迁移任务:

$pythonapp.pydbmigrateINFO[alembic.runtime.migration]ContextimplPostgresqlImpl.INFO[alembic.runtime.migration]WillassumetransactionalDDL.INFO[alembic.autogenerate.compare]Detectedaddedtable'post'Generating/Users/Vihar/Desktop/flask-databases/migrations/versions/ed3b3a028447_.py...done

一旦上述命令执行完毕,我们的数据表就会创建成功。现在更新数据库:

$pythonapp.pydbupgrade

感谢各位的阅读!看完上述内容,你们对Flask框架使模型和数据同步的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。