Flask-SQLAlchemy - 何时创建和销毁表/数据库? [英] Flask-SQLAlchemy - When are the tables/databases created and destroyed?
问题描述
SQLALCHEMY_DATABASE_URI
,在我的情况下,MySQL数据库。那么,它是否创建表,如果他们不存在已经? 如果数据库编程到 如果这些表格都存在,该怎么办?他们被擦除和重新创建?我试图了解整个过程是如何工作的,以便我(1)在更改时不要丢失数据库信息(2)可以编写必要的代码,以完全管理SQLAlchemy如何以及何时与实际数据库进行交谈。 解决方案 SQLALCHEMY_DATABASE_URI $ c $如果这个数据库存在,那么只有一个数据库存在,如果这个数据库不存在,很少有这些表格(在SQLAlchemy代码中有更多的表格比实际的MySQL数据库中存在更多的表格)?它擦除这些表,然后用当前的规格创建新的表?
表格不是自动创建的;您需要调用 SQLAlchemy .create_all()
方法来显式地为你创建表格:
db = SQLAlchemy(app)
db.create_all()
你可以用命令例如,在线应用程序。或者,如果您部署到PaaS,例如Google App Engine,则为专用管理员视图。
这同样适用于数据库表破坏;使用 SQLAlchemy.drop_all( )
方法。
请参阅创建和删除文档的表格章节,或者查看。
I am a little confused with the topic alluded to in the title.
So, when a Flask app is started, does the SQLAlchemy search theSQLALCHEMY_DATABASE_URI
for the correct, in my case, MySQL database. Then, does it create the tables if they do not exist already?
What if the database that is programmed into theSQLALCHEMY_DATABASE_URI
variable in the config.py
file does not exist?
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)? 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.
Tables are not created automatically; you need to call the SQLAlchemy.create_all()
method to explicitly to have it create tables for you:
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.
The same applies for database table destruction; use the SQLAlchemy.drop_all()
method.
See the Creating and Dropping tables chapter of the documentation, or take a look at the database chapter of the Mega Flask Tutorial.
这篇关于Flask-SQLAlchemy - 何时创建和销毁表/数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!