


Introduction 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
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()
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!

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment