模型类
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class CategoryModel(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), comment="分类名")
icon = db.Column(db.String(100), comment="图标")
good = db.relationship("GoodsModel", backref="cate")
class GoodsModel(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), comment="商品名")
price = db.Column(db.DECIMAL(10, 2), comment="价格")
img = db.Column(db.String(100), comment="图片地址")
cate_id = db.Column(db.Integer, db.ForeignKey("category_model.id"), comment="分类标题")
展示
class GoodView(Resource):
def get(self):
req = reqparse.RequestParser()
req.add_argument("cate_id")
args = req.parse_args()
cate_id = args["cate_id"]
cate = CategoryModel.query.get(cate_id)
if not cate:
return jsonify({
"code": 400,
"msg": "分类标题不存在"
})
if cate_id:
good_list = GoodsModel.query.filter(GoodsModel.cate_id == id).all()
else:
good_list = GoodsModel.query.all()
temp = []
for i in good_list:
temp_dict = {
"id": i.id,
"name": i.name,
"price": str(i.price),
"img": 'http://127.0.0.1:5000' + i.img,
"cate": i.cate.name
}
temp.append(temp_dict)
return jsonify({
"code": 200,
"msg": "数据展示成功",
"data": temp
})
添加
def post(self):
req = reqparse.RequestParser()
req.add_argument("name")
req.add_argument("price")
req.add_argument("img")
req.add_argument("cate_id")
args = req.parse_args()
name = args["name"]
price = args["price"]
img = args["img"]
cate_id = args["cate_id"]
if not all([name, price, img]):
return jsonify({
"code": 400,
"msg": "数据不能为空"
})
cate = CategoryModel.query.get(cate_id)
if not cate:
return jsonify({
"code": 400,
"msg": "分类标题不存在"
})
# 三种写法
# 1.
good = GoodsModel(name=name, price=price, img=img, cate_id=cate_id)
# 2.
# good = GoodsModel(name=name, price=price, img=img, cate=cate)
# 3.
# good = GoodsModel(**args)
db.session.add(good)
db.session.commit()
return jsonify({
"code": 200,
"msg": "添加成功"
})
修改
class OneGoodView(Resource):
def put(self, id):
req = reqparse.RequestParser()
req.add_argument("name")
req.add_argument("price")
req.add_argument("img")
req.add_argument("cate_id")
args = req.parse_args()
name = args["name"]
price = args["price"]
img = args["img"]
cate_id = args["cate_id"]
cate = CategoryModel.query.get(cate_id)
if not cate:
return jsonify({
"code": 400,
"msg": "分类标题不存在"
})
good = GoodsModel.query.get(id)
if not good:
return jsonify({
"code": 400,
"msg": "商品不存在"
})
if name:
good.name = name
if price:
good.price = price
if img:
good.img = img
if cate_id:
good.cate_id = cate_id
db.session.commit()
return jsonify({
"code": 200,
"msg": "修改成功"
})
删除
def delete(self, id):
good = GoodsModel.query.get(id)
if not good:
return jsonify({
"code": 400,
"msg": "商品不存在"
})
GoodsModel.query.filter(GoodsModel.id == id).delete()
db.session.commit()
return jsonify({
"code": 200,
"msg": "商品删除成功"
})
api.add_resource(GoodView, "/good")
api.add_resource(OneGoodView, "/good/<int:id>")