preamble
Partners who have used Django know that Django's ORM is self-contained, more specific, and integrated with many features, such as database migration...
What is ORM, personal opinion, simplify the writing of sql statements, relational database table into a python class, the biggest benefit is to simplify the learning cost, will not be able to sql statements programmers can also smooth the use of the database, and inherent anti-sql injection. flask can use SQLAlchemy, package named flask- sqlalchemy. As for the specific use of the official documentation of the translation is clear enough. As for the specific usage of the translation of the official document is clear enough. You can directly Google to follow the document will be able to handle, this article mainly about how to carry out database migration.
Widgets for flask
One of the most obvious differences between people moving from Django to Flask is that flask starts the service by running it directly, and Django uses a runserver to do so. As for the good and the bad, you can decide for yourself. Here to mention a plug-in. flask-script. pip installation can be.
from flask_script import Manager ...... manager = Manager(app) ...... #() #Comment this ()
This changes the startup to python runserver
This may seem like a bit of a red herring, but it's not, and it's very much related to database migration, which we'll talk about below.
Database migration
Required plugins flask-migrate
installed
from flask import Flask from flask_script import Manager from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate,MigrateCommand app = Flask(__name__) ['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////opt/' #Use sqlite3 database db = SQLAlchemy(app) #ORM migrate = Migrate(app,db) manager = Manager(app) manager.add_comman('db',MigrateCommand) #add db commands (runserver usage) # A user table class User(): ... ... an omission if __name__ == '__main__': ()
In this way, the preparations are in place.
Run python db init to create the data table. And it will generate the migrations/ directory under your project to save the contents of each change to your database.
Modify the User class.
python db migrate commit changes
python db upgrade executes the changes
Look at the User table again, it has changed.
python db downgrade fallback modification
One note: SQLite3 can't delete columns with values... so, you shouldn't delete columns...
This is the whole content of this article.