当前位置:网站首页>Flask Framework Beginner-05-Command Management Manager and Database Use
Flask Framework Beginner-05-Command Management Manager and Database Use
2022-08-04 01:35:00 【Liu Moxin】
一、Manager使用
Flask引入了flask_script包,其中的ManagerClasses are used to manage and use related operator commands,在ManagerThere is an example of such a comment in the source code related to the classManager的典型用法,An inheritance is defined in the annotationCommand的Print类,这个类重写了Command中的run方法,实例化的manager对象使用add_commandMethod registration instantiates onePrint()类,主函数中manager调用run方法运行,最后Print()All methods in are executed.由此可见,Manager提供了一个Command类,只要继承了这个Command类,使用add_command()method to register the subclass,就可以使用manager的run()The method runs all functions in the subclass.(由于目前flask_script这个包已经被弃用,Therefore, the source code is no longer analyzed,作为了解即可,If you are interested, you can download the corresponding version to view)
""" Controller class for handling a set of commands. Typical usage:: class Print(Command): def run(self): print "hello" app = Flask(__name__) manager = Manager(app) manager.add_command("print", Print()) if __name__ == "__main__": manager.run() On command line:: python manage.py print > hello :param app: Flask instance, or callable returning a Flask instance. :param with_default_commands: load commands **runserver** and **shell** by default. :param disable_argcomplete: disable automatic loading of argcomplete. """
使用1:基础应用
步骤一:下载 flask_script 包
pip install flask_script
步骤二:使用里面的 Manager Conduct commands to be managed and used
app = create_app()
# 绑定 app
manager = Manager(app=app)
# 启动
manager.run()
步骤三:在终端使用命令
python app.py runserver
# 或者
python app.py runserver -h 0.0.0.0 -p 5001
使用2:添加自定义命令
步骤一:custom add command
@manager.command
def init():
print('初始化')
步骤二:在终端运行命令
python app.py init
example:
settings.py
class DevelopmentConfig(Config):
ENV = 'development'
class ProductConfig(Config):
ENV = 'product'
apps下的__ init __.py
from flask import Flask
import settings
def create_app():
app = Flask(__name__,template_folder='../templates',static_folder='../static')
app.config.from_object(settings.DevelopmentConfig)
return app
app.py
from apps import create_app
app = create_app()
manager = Manager(app=app)
# ._command[db] = MigrateCommand()
manager.add_command('db',MigrateCommand)
# custom add command
@manager.command
def init():
print('初始化')
if __name__ == '__main__':
# app.run()
manager.run()
运行结果:
二、数据库的使用
这里介绍ORMThe object-relational mapping design model,O代表的是object对象,R代表的是Relational关系,M表示的是Mapping映射.ORM框架采用元数据来描述对象与关系映射的细节,You can map specific models to tables in the database one-to-one,The properties of the model object correspond to the fields of the database table,We can operate on database tables and fields by manipulating models and model objects.而Flask本身是没有实现ORM的,因此需要引入一个SQLToolkits and third-party libraries for object mapping tools are implementedORM,Flask-SQLAlchemy就是一种flaskThird-party libraries frequently referenced by database operations,But there is also a problem with using this 3rd party library,That is, when it is necessary to modify the database framework,Table initialization is generally useddb.create_all()这个方法,When the table needs to be modified,Will have to first go to the database to delete the table,Only then can the table of the new table structure be regenerated.为了解决这个问题,At this time, a third-party library was introducedflask-migrate,It can migrate data,并且集成到Flask-Script中,All migration operations are done via commands.为了导出数据库迁移命令,Flask-Migrate还提供了一个MigrateCommand类,可以附加到flask-script的manager对象上.
使用:
步骤一:下载相关包
# python 连接数据库 包
pip install pymysql
# Model object properties are mapped to the database
pip install flask-sqlalchemy
# 数据库迁移
pip install flask-migrate
步骤二:The connection path to the configuration database
# mysql+pymysql: //user:[email protected]:port/databasename
SQLALCHEMY_DATABASE_URI = 'mysql://root:[email protected]:3306/'
步骤三:创建一个ext包
# 步骤一:_init__.py中添加
db = SQLAlchemy() ---->必须跟app联系
# 步骤二:apps-->__init__.py中添加
def create_app():
....
db.init_app(app)
return app
# 注:可使用[ python app.py db --help ]查看使用
步骤四:添加迁移命令到manager
app.py中添加:
manager = Manager(app=app)
migrate = Migrate(app=app,db=db)
manager.add_command('db',MigrateCommand)
运行:python app.py db 查看db的使用
步骤五:创建模型;models.py 相当于类
class User(db.Model):
id = db.Column(db.Integer,primary_key = True,autoincrement = True)
username =db.Column(db.String(15),nullable=False)
password = db.Column(db.String(12),nullable=False)
phone = db.Column(db.String(11),nullable=False)
rdatetime = db.Column(db.DateTime,default=datetime.now)
步骤六:使用命令
a.在app.py中导入模型: from apps.user.models import User
b.在终端使用命令:python app.py db init 产生一个migrations文件夹
python app.py db migrate Generate a version file(versions下)
python app.py db upgrade
c.导入相关驱动
DataBase(If not, add the plugin yourself:file-->setting--->plugins)-->'+'
注:Remember to install the database and connection before this step,打开数据库后,运行相关命令
cmd中打开数据库,Check database table generation:
show databases;
use flaskdb01;
show tables;
desc user;
Example:
项目框架
settings.py
class Config:
ENV = 'development'
DEBUG = True
# 连接数据库,格式:mysql+pymysql(驱动): //user:[email protected]:port/databasename
# SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/'
SQLALCHEMY_DATABASE_URI = 'mysql://root:[email protected]:3306/flaskdb01'
# 如果设置成True(默认情况),Flask-SQLAlchemyObject modifications will be tracked and signals will be sent,这需要消耗额外的内存
SQLALCHEMY_TRACK_MODIFICATIONS = False
# 调试设置为True
SQLALCHEMY_ECHO = True
class DevelopmentConfig(Config):
ENV = 'development'
class ProductConfig(Config):
ENV = 'product'
ext下的__ init __.py
# 创建一个映射对象
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()
db = SQLAlchemy()
apps.user.view.py
from flask import Blueprint, url_for
user_bp = Blueprint('user',__name__)
@user_bp.route('/')
def user_center():
# 反向解析 Find the route by the function name
print(url_for('user.register'))
return '用户中心'
@user_bp.route('/register')
def register():
return '用户注册'
apps下的__ init __.py
from flask import Flask
import settings
from apps.user.view import user_bp
from ext import db
def create_app():
app = Flask(__name__,template_folder='../templates',static_folder='../static')
app.config.from_object(settings.DevelopmentConfig)
# 将db与app关联
db.init_app(app)
# 注册一个蓝图
app.register_blueprint(blueprint=user_bp)
return app
app.py
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager
from apps.user.models import User,UserInfo
from apps import create_app
from ext import db
app = create_app()
manager = Manager(app=app)
# 命令工具
migrate = Migrate(app=app,db=db)
# ._command[db] = MigrateCommand()
manager.add_command('db',MigrateCommand)
# custom add command
@manager.command
def init():
print('初始化')
if __name__ == '__main__':
# app.run()
manager.run()
models.py
# ORM 类---》 表
# 类对象 ---》 表中的记录
from datetime import datetime
from ext import db
# create table user(id int primary key auto_increment,username varchar(20) not null,....
class User(db.Model):
# db.Column(类型,约束) 映射表中的列
''' 类型: db.Integer int db.String varchar(15) db.DateTime datatime '''
id = db.Column(db.Integer,primary_key = True,autoincrement = True)
username =db.Column(db.String(15),nullable=False)
passwords = db.Column(db.String(12),nullable=False)
phone = db.Column(db.String(11),nullable=False)
email = db.Column(db.String(20))
rdatetime = db.Column(db.DateTime,default=datetime.now)
def __str__(self):
return self.username
class UserInfo(db.Model):
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
realname = db.Column(db.String(20))
gender = db.Column(db.Boolean,default=False)
def __str__(self):
return self.realname
终端运行db的init命令,将会产生一个migrations文件夹
python app.py db init
终端运行db的migrate命令,A version file will be generated(versions下)
python app.py db migrate
终端运行db的upgrade命令,The data structure will be updated
python app.py db upgrade
补充:
|----apps
|----ext
|----migrations
|----versions 版本文件夹
|----c1ad2ea8b56f_.py --->python app.py migrate 生成版本信息
|----90c023e77fdb_.py
---> python app.py upgrade 升级版本
--->python app.py downgrade 降级版本
三、简单应用
项目框架
settings.py
class Config:
Debug = True
SQLALCHEMY_DATABASE_URI = 'mysql://root:[email protected]:3306/flaskdb02'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = True
class DevelopmentConfig(Config):
ENV = 'development'
Debug = True
class ProductionConfig(Config):
ENV = 'production'
Debug = True
ext下的 __ init __.py
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()
# 实例化一个SQLAlchemy对象db
db = SQLAlchemy()
apps下的 __ init __.py
from flask import Flask
import settings
from apps.user.view import user_bp
from exts import db
def create_app():
app = Flask(__name__,template_folder='../templates',static_folder='../static')
app.config.from_object(settings.DevelopmentConfig)
# 初始化配置db
db.init_app(app = app)
# 绑定view中的蓝图
app.register_blueprint(user_bp)
return app
app.py
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager
from apps.user.models import User
from apps import create_app
from exts import db
app = create_app()
manager = Manager(app = app)
#
migrate = Migrate(app=app,db=db)
# Added data migration command._command中
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
models.py
from datetime import datetime
from exts import db
# Create a model corresponding to the tables and fields in the database
class User(db.Model):
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
username = db.Column(db.String(15),nullable=False)
password = db.Column(db.String(12),nullable=False)
phone = db.Column(db.String(11),unique=True)
rdatetime = db.Column(db.DateTime,default=datetime.now())
def __str__(self):
return self.username
view.py
from flask import Blueprint, request, render_template
from apps.user.models import User
from exts import db
user_bp = Blueprint('user',__name__)
@user_bp.route('/register',methods=['GET','POST'])
def register():
if request.method =='POST':
username = request.form.get('username')
password = request.form.get('password')
repassword = request.form.get('repassword')
phone = request.form.get('phone')
if password == repassword:
# 创建对象
user = User()
# 对象赋值
user.username = username
user.password = password
user.phone = phone
# Add the object to the cache
db.session.add(user)
db.session.commit()
return '用户注册成功!'
return render_template('user/register.html')
终端运行
python app.py db init
python app.py db migrate
python app.py db upgrade
终端运行
python app.py runserver
访问 http://127.0.0.1:5000/register
查看数据库:
边栏推荐
- esp32发布机器人电池电压到ros2(micro-ros+CoCube)
- typescript55 - generic constraints
- LDO investigation
- Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
- ThreadLocal
- HBuilderX的下载安装和创建/运行项目
- LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之三:两次优化
- Sticker Spelling - Memory Search / Shape Pressure DP
- 有没有jdbc 链接优炫数据库文档及示例?
- nodejs+npm的安装与配置
猜你喜欢
The 600MHz band is here, will it be the new golden band?
循环绕过问题
快速入门EasyX图形编程
[store mall project 01] environment preparation and testing
What warehouse management problems can WMS warehouse management system solve in the electronics industry?
jmeter distributed stress test
esp32发布机器人电池电压到ros2(micro-ros+CoCube)
Slipper - virtual point, shortest path
GraphQL背后处理及执行过程是什么
持续投入商品研发,叮咚买菜赢在了供应链投入上
随机推荐
持续投入商品研发,叮咚买菜赢在了供应链投入上
Sticker Spelling - Memory Search / Shape Pressure DP
nodejs install multi-version version switching
【虚拟户生态平台】虚拟化平台安装时遇到的坑
LDO investigation
网络带宽监控,带宽监控工具哪个好
C 学生管理系统_添加学生
持续投入商品研发,叮咚买菜赢在了供应链投入上
2022 China Computing Power Conference released the excellent results of "Innovation Pioneer"
Use nodejs switch version (no need to uninstall and reinstall)
可变字符串
Google Earth Engine - Calculates the effective width of rivers using publicly available river data
600MHz频段来了,它会是新的黄金频段吗?
HBuilderX的下载安装和创建/运行项目
【OpenCV】-重映射
持续投入商品研发,叮咚买菜赢在了供应链投入上
XSS - Bypass for loop filtering
C 学生管理系统 显示链表信息、删除链表
快速入门EasyX图形编程
Array_Sliding window | leecode brushing notes