search
HomeBackend DevelopmentPython TutorialIntroduction to the use of flask_migrate and flask_script in python (with code)

This article brings you an introduction to the use of flask_migrate and flask_script in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

flask_migrate

When using falsk_sqlalchemy, using 'db.create_all' to modify the database table fields later will not be automatically mapped to the database and must be deleted. Table,

Then re-run 'db.create_all' to remap. This does not meet our requirements, so flask-migrate is to solve
this problem. It can map the modified fields to the database after each modification of the model (class)

from flask_sqlalchemy import SQLAlchemy
from flask import Flask
import pymysql
from sqlalchemy import desc
from flask_bootstrap import Bootstrap


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:sheen@localhost/migrate_sql'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = 'SHEEN'
bootstrap = Bootstrap(app)

class User(db.Model):
    id = db.Column(db.INTEGER,autoincrement=True,primary_key=True)
    # 用户名唯一且不能为空
    name = db.Column(db.String(30),unique=True,nullable=False)
    # 测试:添加gender属性
    gender = db.Column(db.BOOLEAN,default=True)
    todos = db.relationship('Todo',backref='user')

class Todo(db.Model):
    id = db.Column(db.INTEGER, autoincrement=True, primary_key=True)
    # unique: 指定该列信息是唯一的;
    name = db.Column(db.String(50))
    user_id = db.Column(db.INTEGER,db.ForeignKey('user.id'))
if __name__ == '__main__':
    db.create_all()

When the database tables user and todo have been generated, and the tables contain data. At this time, we are required to add attributes (user gender) to the database table without affecting user usage. We use database migration to handle it, and add the code to generate attributes in the original database operation file model

 # 测试:添加gender属性
    gender = db.Column(db.BOOLEAN,default=True)

migrate main attributes

Create migration warehouse (migrations directory)

python manager.py  db init

Read the content of the class and generate the version file, without actually adding or deleting it in the database;

python manager.py  db migrate -m "添加性别"

Has been deleted in the database;

python manager.py  db upgrade

Go to view the historical status of changes;

python manager.py  db history

Return to the specified version status;

python manager.py  db downgrade  base

Introduction to the use of flask_migrate and flask_script in python (with code)

Manage database changes

Create a new manage.py file to manage database changes

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from models import app,db
migrate = Migrate(app,db)
manager = Manager(app)
manager.add_command('db',MigrateCommand)

if __name__ == '__main__':
    manager.run()

Steps:

1. 初始化(自动生成migrations目录)
python manager.py db init

2. 生成最初的迁移
python manager.py db migrate -m '添加用户性别'
出现语句:Detected added column 'user.gender',表明对model有所改动

3.数据库升级
python manager.py db upgrade
生成数据库历史版本的py文件:Running upgrade  -> 202a710ebeb6, '添加用户性别'

flask_script

Flask Script extension provides the function of inserting external scripts into Flask, which separates the script from the system

Overall framework

First, create a The Python template runs the command script, which can be named script.py
In this file, there must be a Manager instance. The Manager class tracks the calling and running status of all commands and processing procedures called on the command line.
Manager only has One parameter - Flask instance

from flask_script import Command,Manager
from flask import Flask

app = Flask(__name__)

manager = Manager(app)
if __name__ == '__main__':
    manager.run()

Create command

Secondly, create and add the command.
There are three ways to create commands, namely creating a Command subclass, using the @command modifier, and using the @option modifier

The first one--Creating a Command subclass
The subclass must define a run method
Create the Hello command and add the Hello command to the Manager instance

class  Hello(Command):
    """欢迎信息"""
    def run(self):
        print('hello,sheen')

manager.add_command('hello',Hello)

The second type - use the @command modifier of the Command instance

@manager.command
def add_user():
    """添加用户信息"""

    print('添加用户成功')

The third type - use Command The @option modifier of the instance
It is recommended to use @option;, multiple parameters can be passed in

@manager.option('-n','--name',help='删除用户')
def del_user(name):
    """删除用户信息"""

    if name:
        print('删除用户%s成功' %(name))
    else:
        print('用户名为空!')

Complete example

# script.py
from flask_script import Command,Manager
from flask import Flask

app = Flask(__name__)

manager = Manager(app)

class  Hello(Command):
    """欢迎信息"""
    def run(self):
        print('hello,sheen')

manager.add_command('hello',Hello)

@manager.command
def add_user():
    """添加用户信息"""

    print('添加用户成功')

@manager.option('-n','--name',help='删除用户')
def del_user(name):
    """删除用户信息"""

    if name:
        print('删除用户%s成功' %(name))
    else:
        print('用户名为空!')
if __name__ == '__main__':
    manager.run()

Introduction to the use of flask_migrate and flask_script in python (with code)

The above is the detailed content of Introduction to the use of flask_migrate and flask_script in python (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.