redis购物车与订单关联的实现代码
时间: 2023-08-21 18:06:35 浏览: 53
以下是一个简单的实现代码,使用 Redis 存储购物车和订单信息:
```python
import redis
# 连接 Redis
r = redis.Redis(host='localhost', port=6379, db=0)
# 购物车键名格式:cart:{user_id}
# 订单键名格式:order:{user_id}:{order_id}
# 添加商品到购物车
def add_to_cart(user_id, item_id, quantity):
r.hset(f"cart:{user_id}", item_id, quantity)
# 从购物车中移除商品
def remove_from_cart(user_id, item_id):
r.hdel(f"cart:{user_id}", item_id)
# 清空购物车
def clear_cart(user_id):
r.delete(f"cart:{user_id}")
# 创建订单
def create_order(user_id, order_id, items):
order_key = f"order:{user_id}:{order_id}"
for item in items:
r.hset(order_key, item['id'], item['quantity'])
# 将订单信息保存到 Redis 中,设置过期时间为 30 分钟
r.expire(order_key, 30 * 60)
```
在上述代码中,`add_to_cart` 函数将商品添加到用户的购物车中,`remove_from_cart` 函数从购物车中移除商品,`clear_cart` 函数清空用户的购物车,`create_order` 函数创建订单并将订单信息保存到 Redis 中。注意,购物车和订单信息都使用 Redis 的 Hash 类型进行存储,其中键名包含了用户 ID 和商品/订单 ID,方便进行快速的查找和管理。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)