Django 购物车模板
2024-09-07 07:52:38
url
from django.contrib import admin
from django.urls import path, re_path
from django.urls import include urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path('^api/(?P<version>[v1|v2]\w+)/', include('app01.urls')),
]
from django.urls import path, re_path
from django.urls import include
from app01.views import account, coursehost, newspapers, shoppingcar urlpatterns = [
re_path('login/$', account.LoginView.as_view()), re_path('course/$', coursehost.CourseView.as_view({"get": "list"})),
re_path('course/(?P<pk>\d+)/$', coursehost.CourseView.as_view({"get": "retrieve"})),
re_path(r'coursecategory/$', coursehost.CourseCategoryView.as_view({'get': 'list'})), re_path(r'shoppingcar/$', shoppingcar.ShoppingCarViewSet.as_view()), ]
视图:
"""
* coding: utf-8 CreateTime:2019/12/20
Version: v1
DocName: shoppingcar.py
Edit: Riven Effect: shoppingcar data SourceStorageLocation: RivenShop / app01 / views / Shoppingcar.py
Modify and add function record:
ModifyTime:
1.
2.
Add function Time :
1.
2. """
from app01 import models
from utils.response import TokenAuth
from utils.response import BaseResponse
from utils.exception import PricePolicyIncalid
from rivenshop import settings import json from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
from django.core.exceptions import ObjectDoesNotExist class ShoppingCarViewSet(APIView):
authentication_classes = [TokenAuth, ]
conn = get_redis_connection('default') def post(self, request, *args, **kwargs):
"""
add course the ShoppingCar
:param request:
:param args:
:param kwargs:
:return:
"""
ret = BaseResponse()
try:
# 1. acquire user submit Course ID with PriceTactics ID
course_id = int(request.data.get('courseid'))
policy_id = int(request.data.get('policyid')) # 2. acquire course ID
course = models.Course.objects.get(id=course_id) # 3.acquire course all PriceTactics
price_policy_list = course.price_policy.all() price_policy_dict = {}
for item in price_policy_list:
price_policy_dict[item.id] = {
"period": item.valid_period,
"period_display": item.get_valid_period_display(),
"price": item.price,
}
print(price_policy_dict)
# 4. estimate submit data whether legitimate
if policy_id not in price_policy_dict:
# return error PriceTactics illegal
raise PricePolicyIncalid("价格策略不合法") # 5.ShoppingCar msg add redis
car_key = settings.SHOPPING_CAR_KEY % (request.auth.user_id, course_id)
car_dict = {
"titile": course.name,
"img": course.course_img,
"default_policy": policy_id,
"policy": json.dumps(price_policy_dict) }
self.conn.hmset(car_key, car_dict)
ret.data = "添加成功" except PricePolicyIncalid as e:
ret.code = 2001
ret.error = e.msg except ObjectDoesNotExist as e:
ret.code = 2001
ret.error = "课程不存在" except Exception as e:
ret.code = 1001
ret.error = "获取购物车失败"
return Response(ret.dict) def delete(self, request, *args, **kwargs):
"""
Delete ShoppingCar course
:param request:
:param args:
:param kwargs:
:return:
""" ret = BaseResponse()
try:
course_id_list = request.data.get("courseids")
key_list = [settings.SHOPPING_CAR_KEY % (request.auth.user_id, course_id,) for course_id in course_id_list]
self.conn.delete(*key_list)
except Exception as e:
ret.code = 1002
ret.error = "删除失败" return Response(ret.dict) def patch(self, request, *args, **kwargs):
"""
Modification PriceTactics for course
:param request:
:param args:
:param kwargs:
:return:
"""
ret = BaseResponse()
try:
# 1.acquire PriceTactics ID with course ID
course_id = int(request.data.get("courseid"))
policy_id = str(request.data.get("policyid")) # 2.joint the course key
key = settings.SHOPPING_CAR_KEY % (request.auth.user_id, course_id,) if not self.conn.exists(key):
ret.code = 1002
ret.error = "购物车中不存在此课程"
return Response(ret.dict)
# 3. Acquire PriceTactics data all for redis
policy_dict = json.loads(str(self.conn.hget(key, "policy"), encoding='utf-8')) if policy_id not in policy_dict:
ret.code = 1003
ret.error = "价格策略不合法"
return Response(ret.dict)
print(key)
# 4.Modification ShoppingCar Course PriceTactics
self.conn.hset(key, 'default_policy', policy_id) ret.data = "修改成功"
print(456464165) except Exception as e:
ret.code = 1004
ret.error = "修改失败" return Response(ret.dict) def get(self, request, *args, **kwargs):
"""
see ShoppingCar all data
:param request:
:param args:
:param kwargs:
:return:
"""
ret = BaseResponse()
try:
key_match = settings.SHOPPING_CAR_KEY % (request.auth.user_id, "*")
course_list = [] for key in self.conn.scan_iter(key_match, count=10):
print(key)
info = {
"title": self.conn.hget(key, 'titile').decode('utf-8'),
"img": self.conn.hget(key, 'img').decode('utf-8'),
"policy": json.loads(self.conn.hget(key, 'policy').decode('utf-8')),
"default_policy": self.conn.hget(key, 'default_policy').decode('utf-8')
} course_list.append(info) ret.data = course_list except Exception as e:
ret.code = 1002
ret.error = "获取失败"
return Response(ret.dict)
最新文章
- Java设计模式(七) 模板模式
- IE6和IE7中<;a>;标签宽高设置无效的问题
- Hadoop 面试题 之Hive
- C/C++运算符优先级
- java web 下实现文件下载
- 用Eclipse 开发Dynamic Web Project应用程序 【转】
- 图解 Monad
- Web前端文件上传进度的显示
- C++智能指针剖析(上)std::auto_ptr与boost::scoped_ptr
- 42_redux_counter应用_redux异步版本
- c++ 简单静态链表
- 利用IntelliJ IDEA 创建第一个项目
- 获取解码字符串指定位置的数值 Decoded String at Index
- Java 根据出生日期计算年龄
- [转]OkHttp使用完全教程
- 线性DP总结(LIS,LCS,LCIS,最长子段和)
- MySQL(安装,服务,创建用户及授权)
- sql2000-text类型数据只能看到256个字节
- MongoDB的固定集合
- 【Python】python和json数据相互转换,json读取和写入,repr和eval()使用
热门文章
- 打造个人专属网盘nextcloud
- java web开发入门十二(idea创建maven SSM项目需要解决的问题)基于intellig idea(2019-11-09 11:23)
- 强烈推荐一个和朋友远程桌面的软件teamviewer
- 【网络知识之六】UDP
- Python2.x升级python3.x【升级步骤和错误总结】
- What IS MPI
- java跳出循环break;return;continue使用
- hibernate中many-to-one的not-found属性和@notfound注解
- 如何在 ubuntu 下使用 Windows 里面的字体
- VMWare 下安装 Windows XP