Home Backend Development Python Tutorial Introduction to the use of flask_migrate and flask_script in python (with code)

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

Nov 15, 2018 pm 03:01 PM
mysql python windows

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()
Copy after login

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)
Copy after login

migrate main attributes

Create migration warehouse (migrations directory)

python manager.py  db init
Copy after login

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 "添加性别"
Copy after login

Has been deleted in the database;

python manager.py  db upgrade
Copy after login

Go to view the historical status of changes;

python manager.py  db history
Copy after login

Return to the specified version status;

python manager.py  db downgrade  base
Copy after login

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()
Copy after login

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, '添加用户性别'
Copy after login

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()
Copy after login

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)
Copy after login

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

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

    print('添加用户成功')
Copy after login

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('用户名为空!')
Copy after login

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()
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

See all articles