简体   繁体   English

Flask-SQLAlchemy - 何时创建和销毁表/数据库?

[英]Flask-SQLAlchemy - When are the tables/databases created and destroyed?

I am a little confused with the topic alluded to in the title. 我对标题中提到的主题感到有些困惑。

So, when a Flask app is started, does the SQLAlchemy search the SQLALCHEMY_DATABASE_URI for the correct, in my case, MySQL database. 因此,当启动Flask应用程序时,SQLAlchemy是否会在SQLALCHEMY_DATABASE_URI搜索正确的MySQL数据库。 Then, does it create the tables if they do not exist already? 然后,如果表已经不存在,它会创建表吗?

What if the database that is programmed into the SQLALCHEMY_DATABASE_URI variable in the config.py file does not exist? 如果编程到config.py文件中的SQLALCHEMY_DATABASE_URI变量的数据库不存在怎么办?

What if that database exists, and only a few of the tables exist (There are more tables coded into the SQLAlchemy code than exist in the actual MySQL database)? 如果该数据库存在,并且只存在少数几个表(SQLAlchemy代码中编码的表多于实际MySQL数据库中存在的表),该怎么办? Does it erase those tables and then create new tables with the current specs? 它会删除这些表,然后使用当前规范创建新表吗?

And what if those tables do all exist? 如果这些表全部存在怎么办? Do they get erased and re-created? 它们会被删除并重新创建吗?

I am trying to understand how the entire process works so that I (1) Don't lose database information when changes are made to the schema, and (2) can write the necessary code to completely manage how and when the SQLAlchemy talks to the actual Database. 我试图理解整个过程是如何工作的,以便我(1)在对模式进行更改时不丢失数据库信息,(2)可以编写必要的代码来完全管理SQLAlchemy如何以及何时与实际数据库。

Tables are not created automatically; 表不是自动创建的; you need to call the SQLAlchemy.create_all() method to explicitly to have it create tables for you: 您需要调用SQLAlchemy.create_all()方法以显式地为它创建表:

db = SQLAlchemy(app)
db.create_all()

You can do this with command-line utility, for example. 例如,您可以使用命令行实用程序执行此操作。 Or, if you deploy to a PaaS such as Google App Engine, a dedicated admin-only view. 或者,如果您部署到PaaS(例如Google App Engine),则会使用专用的仅限管理员的视图。

The same applies for database table destruction; 这同样适用于数据库表销毁; use the SQLAlchemy.drop_all() method . 使用SQLAlchemy.drop_all()方法

See the Creating and Dropping tables chapter of the documentation , or take a look at the database chapter of the Mega Flask Tutorial . 请参阅文档创建和删除表章节 ,或者查看Mega Flask教程数据库章节

You can also delegate this task to Flask-Migrate or similar schema versioning tools. 您还可以将此任务委派给Flask-Migrate或类似的架构版本控制工具。 These help you record and edit schema creation and migration steps; 这些可以帮助您记录和编辑模式创建和迁移步骤; the database schema of real-life projects is never static and you would want to be able to move existing data between versions or the schema. 现实项目的数据库模式永远不会是静态的,您希望能够在版本或模式之间移动现有数据。 Creating the initial schema is then just the first step. 然后,创建初始模式只是第一步。

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

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