简体   繁体   English

如何加载预先存在的数据烧瓶-sqlalchemy

[英]how to load pre-existing data flask-sqlalchemy

I am writing a REST API using flask_restful and managing the mysql db using flask-sqlalchemy . 我正在使用flask_restful编写REST API并使用flask-sqlalchemy flask_restful管理mysql数据库。 I would like to know what the best practice for loading existing data into a table when the app starts is. 我想知道在应用启动时将现有数据加载到表中的最佳实践是什么。

I am currently calling the db.create_all() method withing an endpoint with the @app.before_first_request decorator. 我目前正在使用带有@app.before_first_request装饰器的端点来调用db.create_all()方法。 I would like to then fill in one of the tables created with existing data from a csv file. 然后,我想填写使用csv文件中的现有数据创建的表之一。 Should the code to push the data in a separate script or within the function? 代码应该在单独的脚本中还是在函数中推送数据?

Thanks! 谢谢!

I would separate loading initial database data from application initialization, because probably initial data from my experience would not be changed often and can take some time if file is bigger, and usually you don't need to reload it in the database each time application loads. 我会将加载初始数据库数据与应用程序初始化分开,因为根据我的经验,初始数据可能不会经常更改,并且如果文件更大,可能会花费一些时间,并且通常不需要每次加载应用程序时都将其重新加载到数据库中。

I think you will most certainly need database migrations at some point in your application development, so I would suggest setting up Flask-Migrate to handle that, and running its upgrade method on application creation ( create_app method if you are using Flask application factories pattern ) which will handle database migrations. 我认为您肯定会在应用程序开发的某个时刻需要数据库迁移,因此我建议您设置Flask-Migrate来处理该问题,并在应用程序创建时运行其升级方法(如果使用Flask 应用程序工厂模式,则使用create_app方法)它将处理数据库迁移。 I am saying this since it will save you some headache when you are introducing it later on database already populated with actual data which is initialized with db.create_all() . 我之所以这样说是因为,当您稍后在已经用db.create_all()初始化的实际数据填充的数据库上进行介绍时,它将为您节省一些头痛。

And for populating database with seed data I would go with Flask CLI or Flask-Script . 为了用种子数据填充数据库,我可以使用Flask CLIFlask-Script In one of my recent projects I used Flask-Script for this, and created separate manage.py file which amongst other application management methods contained initial data seeding method which looked something like this: 在我最近的一个项目中,我为此使用了Flask-Script,并创建了单独的manage.py文件,该文件除其他应用程序管理方法外还包含初始数据播种方法,该方法类似于以下内容:

@manager.command
def seed():
    "Load initial data into database."
    db.session.add(...)
    db.session.commit()

And it was run on demand by following command: 它是通过以下命令按需运行的:

python manage.py seed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM