当前位置:网站首页>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
边栏推荐
- D1-H 开发板——哪吒 开发入门
- BGP选路,MPLS
- TAP 系列文章9 | 应用开发加速器
- (CVPR-2022)BiCnet
- [ CTF ]天格战队WriteUp-首届数字空间安全攻防大赛(初赛)
- openEuler 资源利用率提升之道 01:概论
- strncat() strncmp()
- Video Number strengthens the fight against vulgar content: the content that violates public order and good customs must be eliminated
- Software architecture
- Absl tutorial (4): strings Library
猜你喜欢

Redis pipeline technology / partition

【Error】TypeError: expected str, bytes or os. PathLike object, not int

Upgrade unity visual studio 2019 to 2022 (throw away pirated red slag)

1000个Okaleido Tiger首发上线Binance NFT,引发抢购热潮

Smart IOT source code with configuration IOT source code industrial IOT source code: support sensor analysis services, real-time data collection and remote control

ES6 other syntax and extended syntax summary

Three network modes of VMware virtual machine

砺夏行动 2022|源启数字化圆桌论坛即将上线

1000 okaleido tiger launched binance NFT, triggering a rush to buy
![Is the height of binary tree [log2n]+1 equal to log2 (n+1)](/img/64/381376190218d5b2cdfd8b1197e8f6.png)
Is the height of binary tree [log2n]+1 equal to log2 (n+1)
随机推荐
Tap series article 5 | cloud native build service
FreeRTOS personal notes - create / delete dynamic tasks, start scheduler
Tap series article 9 | application development accelerator
Build your own target detection environment, model configuration, data configuration mmdetection
Redis pipeline technology / partition
SecureCRT garbled
[tensorflow] check whether tensorflow GPU is available
13. Roman to integer
Interface test
strncat() strncmp()
[web vulnerability exploration] SQL injection vulnerability
史上最全的2022年版Android面试题
None and Nan, Nan, Nan
Sql156 average completion rate of each video
Analysis of video capability and future development trend based on NVR Technology
Mongodb database + graphical tools download, installation and use
浅析基于NVR技术的视频能力与未来发展趋势
[leetcode ladder] the penultimate node in the 022 linked list
[laser principle and Application-8]: EMC design of laser circuit
Getting started database days2