Flask-SQLAlchemy - 何时创建和销毁表/数据库? [英] Flask-SQLAlchemy - When are the tables/databases created and destroyed?

查看:411
本文介绍了Flask-SQLAlchemy - 何时创建和销毁表/数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对标题中提到的话题有些困惑。所以,当一个Flask应用程序启动时,SQLAlchemy是否正确搜索 SQLALCHEMY_DATABASE_URI ,在我的情况下,MySQL数据库。那么,它是否创建表,如果他们不存在已经?

如果数据库编程到 SQLALCHEMY_DATABASE_URI

如果这些表格都存在,该怎么办?他们被擦除和重新创建?我试图了解整个过程是如何工作的,以便我(1)在更改时不要丢失数据库信息(2)可以编写必要的代码,以完全管理SQLAlchemy如何以及何时与实际数据库进行交谈。 解决方案

表格不是自动创建的;您需要调用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆