购物车接口:实现购物车的添加、删除、修改、查询等功能代码
时间: 2023-07-10 07:18:43 浏览: 44
好的,以下是购物车接口的示意代码,仅供参考:
```python
# 导入必要的库和模块
from flask import Flask, request, jsonify
# 初始化Flask应用
app = Flask(__name__)
# 模拟购物车数据,使用字典存储
cart = {}
# 添加商品到购物车
@app.route('/cart/items', methods=['POST'])
def add_item():
# 从请求体中获取商品信息
item = request.get_json()
# 将商品添加到购物车中
cart[item['id']] = item
return jsonify({'message': 'Item added to cart successfully!'})
# 删除购物车中的商品
@app.route('/cart/items/<item_id>', methods=['DELETE'])
def delete_item(item_id):
# 检查购物车中是否存在要删除的商品
if item_id not in cart:
return jsonify({'error': 'Item not found in cart!'}), 404
# 从购物车中删除商品
del cart[item_id]
return jsonify({'message': 'Item deleted from cart successfully!'})
# 修改购物车中的商品数量
@app.route('/cart/items/<item_id>', methods=['PUT'])
def update_quantity(item_id):
# 检查购物车中是否存在要修改数量的商品
if item_id not in cart:
return jsonify({'error': 'Item not found in cart!'}), 404
# 从请求体中获取新的商品数量
new_quantity = request.get_json()['quantity']
# 更新购物车中商品的数量
cart[item_id]['quantity'] = new_quantity
return jsonify({'message': 'Item quantity updated successfully!'})
# 查询购物车中的商品列表
@app.route('/cart/items', methods=['GET'])
def get_items():
# 返回购物车中的所有商品信息
return jsonify(list(cart.values()))
# 查询购物车中的商品总价
@app.route('/cart/totalPrice', methods=['GET'])
def get_total_price():
# 计算购物车中所有商品的总价
total_price = sum([item['price'] * item['quantity'] for item in cart.values()])
return jsonify({'totalPrice': total_price})
# 启动Flask应用
if __name__ == '__main__':
app.run()
```
以上代码仅供参考,实际应用中还需根据具体情况进行适当调整。