当前位置:网站首页>How to migrate databases in the flask framework
How to migrate databases in the flask framework
2022-07-23 23:23:00 【Cerebellar axe AI eats meat】
Flask How to migrate databases in the framework
Flask Data migration in the framework requires installation Flask-Migrate plug-in unit
Installation command :pip install flask-migrate
Definition ORM Model
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
# Configuration variables of the database
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'zzh_flask'
USERNAME = 'root'
PASSWORD = 'root'
DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
# The defined database connection string DB_URI, adopt `SQLALCHEMY_DATABASE_URI` This key Name configuration to `app.config` in .
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
# Set whether to track every database modification
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# Use `flask_sqlalchemy.SQLAlchemy` This class defines an object , And will `app` Put it in .
db = SQLAlchemy(app)
# Create a migrate object
migrate = Migrate(app, db)
# Definition ORM Model
class User(db.Model):
__talblename__ = 'user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(200), nullable=False)
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(200), nullable=False)
content = db.Column(db.Text, nullable=False)
# Foreign keys
# 1. The data type of the foreign key must depend on , The type of the field being referenced
# 2.db.ForeignKey(" Table name . Field name ")
# 3. Foreign keys belong to the database level , It's not recommended to go directly to ORM Use in
# db.ForeignKey Declare that this field is a foreign key
author_id = db.Column(db.Integer, db.ForeignKey("user.id"))
# relationship
# 1. The first parameter is the name of the model , Must be consistent with the name of the model
# 2.backref(back reference): Represents a reverse reference ,"articles" Field name when accessing me on behalf of the other party , The premise is that a foreign key has been associated in the front
# The function here is to access all his articles through the author , for example user.articles
author = db.relationship("User", backref="articles")
class UserExtension(db.Model):
__tablename__ = 'user_extension'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
school = db.Column(db.String(100))
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
# db.backref
# 1. In reverse application, you need to pass some other parameters , Then you need to use this function , If you don't need to use , As long as relationship Of backref Parameter , Just set the name of the back reference
# 2.uselist=False When it stands for back reference , It's not a list , It's an object , Only one can be found , one-on-one
user = db.relationship("User", backref=db.backref("extension", uselist=False))
if __name__ == '__main__':
app.run()
Perform model migration
①flask db init
②flask db migrate
③flask db upgrade
The second step flask db migrate Can be written as flask db migrate -m "first commit", In this way, you can indicate what has been modified when migrating the script . The added comments will be reflected in the migration script 
When ORM After the model is modified , For example, I give User Added a password Field , So how to migrate
, Don't... At this time init 了 , direct flask db migrate -m "add password",flask db upgrade that will do
Reference resources :https://www.zlkt.net/book/detail/10/297
边栏推荐
- FreeRTOS personal notes - suspend / unhook tasks
- A great open source micro community light forum source code
- EasyNVR平台如何关闭匿名登录?
- Extract any page number in PDF file with itextpdf
- SOLIDWORK learning notes: Sketch geometric relationships and editing
- 汇编语言伪指令详解(附实例)
- FreeRTOS personal notes - delay function
- SecureCRT garbled
- FreeRTOS personal notes - create / delete dynamic tasks, start scheduler
- [leetcode ladder] the penultimate node in the 022 linked list
猜你喜欢
![[web vulnerability exploration] SQL injection vulnerability](/img/94/dc84d7790d5a1823e4b73d513e86be.png)
[web vulnerability exploration] SQL injection vulnerability

YOLOv4: Optimal Speed and Accuracy of Object Detection
![[leetcode ladder] the penultimate node in the 022 linked list](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
[leetcode ladder] the penultimate node in the 022 linked list

系列文章|云原生时代下微服务架构进阶之路 - 微服务拆分的最佳实践

TAP 系列文章5 | 云原生构建服务

USB转CAN设备在核酸提取仪 高性能USB接口CAN卡

Android金九银十的面试你准备的怎么样了?最新Android面试真题汇总助你备战

Entropy weight method to optimize TOPSIS (matlab)

Principal component analysis (matlab)

Light up the LED light of little bear patting learning
随机推荐
SecureCRT garbled
Contemporary inspirational "women"
Open source embedded sig in the openeuler community. Let's talk about its multi OS hybrid deployment framework
Is the height of binary tree [log2n]+1 equal to log2 (n+1)
1000个Okaleido Tiger首发上线Binance NFT,引发抢购热潮
Analytic hierarchy process (matlab)
Basic operations of AutoCAD
Mobile, telecom and Unicom: fancy solution of 5g to B
None和nan、NaN、NAN
Stm32f4 check the frequency of each part of the system
Diabetes genetic risk testing challenge baseline
Tap series article 6 | application model of tap
Utilisation des fonctions fléchées es6
Lixia action | Yuanqi Digitalization: existing mode or open source innovation?
SOLIDWORK learning notes: Sketch geometric relationships and editing
Mongodb - Introduction to the use of $exists and the combination of $ne, $nin, $nor, $not in query statements
Sql156 average completion rate of each video
Mongodb - Introduction to the usage of logical operators not, and, or, nor in query statements
Resolved (selenium operation Firefox Firefox browser error) attributeerror: 'webdriver' object has no attribute 'execute_ cdp_ cmd’
2、 Digital logic functional unit