1.概述
由于一个商品可能存在多个图片,多个参数,所以,这里的添加商品接口需要关联到多张表。并且,根据前端传递的数据,多个图片和多级参数,需要去转成列表形式去遍历,具体描述请看代码展示
2.代码展示
# restful发送请求
class Goods(Resource):
# 商品添加接口
def post(self):
try:
attr_dynamic = request.form.get('attr_dynamic')
attr_static = request.form.get('attr_static')
cid_one = request.form.get('cid_one')
cid_two = request.form.get('cid_two')
cid_three = request.form.get('cid_three')
introduce = request.form.get('introduce')
name = request.form.get('name')
number = request.form.get('number')
pics = request.form.get('pics')
price = request.form.get('price')
weight = request.form.get('weight')
goods = models.Goods(name=name, number=number, price=price, weight=weight, introduce=introduce,
cid_one=cid_one, cid_two=cid_two, cid_three=cid_three)
db.session.add(goods)
db.session.commit()
# 由于我们下面遍历时需要id,id又是自动生成的,所以先提交了这些内容得到id
# pics是字符串,所以先用eval()把他转成列表的形式去遍历他;并且他是多个的,所以需要单独model去保存
for p in eval(pics):
tp = models.Picture(gid=goods.id, path= p )
db.session.add(tp)
for s in eval(attr_static):
temp_s = models.GoodsAttr(gid = goods.id, aid=s.get('id'), val=s.get('val'), _type='static')
db.session.add(temp_s)
for d in eval(attr_dynamic):
temp_d = models.GoodsAttr(gid = goods.id, aid=d.get('id'), val=d.get('val'), _type='dynamic')
db.session.add(temp_d)
db.session.commit()
return to_dict_msg(200, msg='增加商品成功!!!')
except Exception as e:
return to_dict_msg(20000)
goods_api.add_resource(Goods, '/goods')
3.测试接口
由于这的字段过多,所以就放在下一篇文章去前端测试