Flask
项目文件介绍
# 由于 Flask 过于灵活, 项目文件可*搭配
Flask_project # 项目名称
app01 # app 文件夹
views.py # 视图文件
models.py # 模型文件
app02
views.py
models.py
manager.py # 主 app 文件 :用于注册app 启动项目 等功能
setconfig.py # 主配置文件
db.py # 数据库配置
Flask 学习
manager.py
# Flask 用于创建主 app
from flask import Flask
from flask_script import Manager
from app01.views import app01
from app01.models import Book
from app02.views import app02
from flask_migrate import Migrate, MigrateCommand
from app01.models import db
from setconfig import DevelopmentConfig
# 创建主 app => django 中的 项目配置文件夹
app = Flask(__name__)
# 注册蓝图 => django 中的 注册 app01
app.register_blueprint(app01)
app.register_blueprint(app02)
# 导入配置
app.config.from_object(DevelopmentConfig)
# 数据库初始化 app
db.init_app(app)
if __name__ == '__main__':
# shell>> python manager.py runserver -h 0.0.0.0 -p 9901
# manager.run()
app.run(host='127.0.0.1', port=9909) # run(host=None, port=None, debug=None)
config.py
# 数据库配置类
class DBConfig:
"""
数据库迁移 python db.py db init
创建自动迁移脚本 python db.py db migrate
更新到数据库 python db.py db upgrade
查看历史版本 python db.py db history
"""
ENV = 'development'
DEBUG = True
HOST = "10.2.38.195"
PORT = 3306
USER = "root"
PASSWORD = "Troila12#$"
NAME = "flask"
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://{}:{}@{}:{}/{}".format(USER, PASSWORD, HOST, PORT, NAME)
SQLALCHEMY_TRACK_MODIFICATIONS = True
# 开发环境
class DevelopmentConfig(DBConfig):
ENV = 'development'
# 生产环境
class ProductionConfig(DBConfig):
ENV = 'production'
app01 文件夹 FBV: 模式
views.py
"""
app01 作为 蓝图
蓝图: 相当于Django 中的 app
"""
# Blueprint 用于创建蓝图
from flask import Blueprint
from .models import Book
from flask import views
from db import db
from flask import jsonify
from flask import request
# 创建一个蓝图 => django: python manage.py app01
app01 = Blueprint('app01', __name__)
# # 蓝图路由: 用路由绑定函数 => django: path('app01/func01', views.func_name)
# @app01.route('/app01/learn')
# def learn():
# return "app01"
class LearnDB(views.MethodView):
"""
对数据库的增删改查
"""
def get(self):
ret = Book.query.all()
print(ret)
# 查看数据
return jsonify({
"status": "get"
})
def post(self):
# 增加一条数据
book = Book(name="西游记", price=10.0)
db.session.add(book)
db.session.commit()
return jsonify({
"status": "post"
})
def delete(self):
# 删除一条数据
ret = Book.query.filter_by(id=1)[0]
print(ret, type(ret))
db.session.delete(ret)
db.session.commit()
return jsonify({
"status": "delete"
})
def put(self):
# 修改一条数据 一般从 url 中 获取主键, 从 body 中获取修改的数据
# url = http://127.0.0.1:9901/app01/learndb?pk=1
# data = { "name": "book", "price": 10.2}
#
ret = Book.query.filter_by(id=2)[0]
ret.name = "水浒传"
db.session.commit()
return jsonify({
"status": "put"
})
# 绑定路由
app01.add_url_rule('/app01/learndb', endpoint=None, view_func=LearnDB.as_view(name="learndb"))
models.py
# 引用 db 类, 用于 orm 映射
from db import db
"""
CREATE TABLE book(
id INT primary key NOT NULL AUTO_INCREMENT,
name varchar(20) NOT NULL,
price varchar(20)
)
"""
# 定义一个数据库模型类
class Book(db.Model):
__tablename__ = 'book'
# 字段名 id ; Column 列名; db.Integer 整型 ; primary_key = True 主键唯一; autoincrement:自动增长
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
# db.String(20) : 字符串; nullabel
name = db.Column(db.String(20), nullable=False)
# db.Float(10) : 浮点型
price = db.Column(db.Float(10), nullable=True)
def __init__(self, name, price):
self.name = name
self.price = price
app02 文件夹 CBV: 模式
views.py
"""
app02: flask 中的 CBV 模式
"""
from flask import Blueprint
from flask import views
from flask import jsonify
# 创建蓝图
app02 = Blueprint('app02', __name__)
# 继承 views.MethodView 类进行 cbv 模式
class CBVTest(views.MethodView):
def get(self):
response = [{
'app02': "app02",
'method': "get"
}]
return jsonify(response)
def post(self):
return "this is flask cbv post"
# 路由注册
app02.add_url_rule('/app02/cbv', endpoint=None, view_func=CBVTest.as_view(name="hello"))
models.py
#
requirements
# 安装依赖包
# pip freeze > requirements.txt
# pip install -r requirements.txt
Flask 常用工具使用
flask-migrate # 发布命令工具
flask-sqlalchemy # 实现 ORM 映射
flask-script #
数据库迁移
# 目前不用此方法
python manager.py db init
python manager.py db migrate
python manager.py db upgrade