模型类
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# 分类
class Nan(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment="分类ID")
name = db.Column(db.String(32), comment="分类名称")
goods = db.relationship("Goods", backref="nan")
# 商品
class Goods(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment="商品ID")
name = db.Column(db.String(32), comment="商品名称")
price = db.Column(db.Integer, comment="商品价格")
img = db.Column(db.String(300), comment="图片")
nan_id = db.Column(db.Integer, db.ForeignKey("nan.id"))
1.增
def post(self):
# 获取参数 && 校验参数
# 1.实例化请求器对象
req = reqparse.RequestParser()
# 2.添加你要获取的参数
req.add_argument("name", required=True)
# 校验参数
args = req.parse_args() # 它的返回的值是所有的参数 例如:{'name': '文'}
# 插入数据
# args['name']为获取name参数的值
c1 = Nan(name=args["name"])
# c1 = Nan(name=args.name)
db.session.add(c1)
# 提交事物
db.session.commit()
return jsonify({
"code": 200,
"msg": "添加成功"
})
2.查
# 分类查看
def get(self):
nanlist = Nan.query.all() # 是一个对象列表
# 序列化器
# data = marshal(nanlist,{
# "id": fields.Integer,
# "name":fields.String
# })
# 手动序列化器
data = []
for i in nanlist:
lists = {
"id": i.id,
"name": i.name
}
data.append(lists)
return jsonify({
"code": 200,
"msg": "获取成功",
"data": data
})
3.改
# 分类修改
def put(self):
# 实例化请求器的对象
req = reqparse.RequestParser()
# 接收参数
req.add_argument("id", type=int, required=True)
req.add_argument("name", required=True)
# 校验参数
args = req.parse_args()
# 先拿出数据
cate_info = Nan.query.get(args['id'])
if not cate_info:
return jsonify({
"code": 400,
"msg": "分类不存在"
})
# 修改属性
cate_info.name = args["name"]
# 提交事物
db.session.commit()
return jsonify({
"code": 200,
"msg": "修改成功",
})
4.删
# 分类删除
def delete(self):
# 实例化请求器的对象
req = reqparse.RequestParser()
# 接收参数
req.add_argument("id", type=int, required=True, help="ID必填")
# 校验参数
args = req.parse_args()
# 先拿出数据
cate_info = Nan.query.get(args['id'])
if not cate_info:
return jsonify({
"code": 400,
"msg": "分类不存在"
})
Nan.query.filter(Nan.id == args["id"]).delete()
# 提交事物
db.session.commit()
return jsonify({
"code": 200,
"msg": "删除成功"
})
第二张表
from flask_restful import Api, Resource, marshal, fields, reqparse
from models.model import Goods, Nan,db
goods_bp = Blueprint("goods_bp", __name__)
api = Api(goods_bp)
class GoodsView(Resource):
# 商品添加
def post(self):
# 获取参数
req = reqparse.RequestParser() # 实例化请求器对象
req.add_argument("name", required=True)
req.add_argument("price", required=True)
req.add_argument("nan_id", type=int, required=True) # 添加参数
# request.files.get("img") # 获取图片
# img.save("./static/img/")
# 校验参数
args = req.parse_args()
# 获取分类的ID
cate_info = Nan.query.get(args["nan_id"])
print(cate_info)
# 判断有没有当前的id
if not cate_info:
return jsonify({
"code": 400,
"msg": "分类不存在"
})
# 插入数据
# 实例化Goods
goods = Goods(
name=args["name"],
price=args["price"],
nan_id=cate_info.id
)
db.session.add(goods)
# db.session.commit()
# 返回
return jsonify({
"code": 200,
"msg": "商品添加成功 - {%s}" % goods.name
# 'msg': f'{goods.name}'
})
# 商品查看
def get(self):
# 获取到的分类ID
req = reqparse.RequestParser()
req.add_argument("nan_id", type=int, required=True)
# 校验参数
args = req.parse_args()
# 查询出分类的对象
nan_info = Nan.query.get(args["nan_id"])
print(nan_info)
if not nan_info:
return jsonify({
"code": 400,
"msg": "分类不存在"
})
# 根据分类对象,正向查询出相关联的商品信息
goods_list = nan_info.goods
print(goods_list)
# 序列化
goods_all = []
for i in goods_list:
d1 = {
"id": i.id,
"name": i.name,
"price": i.price,
"nan_name": i.nan.name, # 反向查询出分类的名字
# "img": i.img
}
goods_all.append(d1)
print(goods_all)
# 返回
return jsonify({
"code": 200,
"msg": "商品获取成功",
"data": goods_all
})
# 商品修改
def put(self):
# 实例化请求器的对象
req = reqparse.RequestParser()
# 接收参数
req.add_argument("id", type=int, required=True)
req.add_argument("name")
req.add_argument("price")
req.add_argument("nan_id", type=int)
# 校验参数
args = req.parse_args()
print(args)
# 先拿出数据
goods_info = Goods.query.get(args['id'])
if not goods_info:
return jsonify({
"code": 400,
"msg": "商品不存在"
})
# 修改属性
if args["name"]:
goods_info.name = args["name"]
if args["price"]:
goods_info.price = args["price"]
if args["nan_id"]:
# 先判断以下分类是否存在
nan_info = Nan.query.get(args["nan_id"])
if not nan_info:
return jsonify({
"code": 400,
"msg": "分类不存在"
})
goods_info.nan_id = args["nan_id"]
# 提交事物
db.session.commit()
return jsonify({
"code": 200,
"msg": "修改成功",
})
def delete(self):
# 实例化请求器的对象
req = reqparse.RequestParser()
# 接收参数
req.add_argument("id", type=int, required=True, help="ID必填")
# 校验参数
args = req.parse_args()
Goods.query.filter(Goods.id == args["id"]).delete()
db.session.commit()
return jsonify({
"code":200,
"msg": "删除成功"
})
api.add_resource(GoodsView, "/goods")