Luffy项目
先看练习,如下:
一. 添加购物车和查看
1. url
url(r'^shoppingcar/$', shoppingcar.ShoppingCarView.as_view({"post":"create","get":"list"})),
2. 视图
class ShoppingCarView(ViewSetMixin,APIView):
def list(self,request,*args,**kwargs): return Response("h") def create(self, request, *args, **kwargs):
print("request.body===>",request.body)
print("request.post===>",request.POST)
return Response({"code": 111})
① 通过postman发送 JSON格式请求(application/json)request.body
输出结果:
POST里面没有值
② request.data
print("request.body===>",request.body) print("request.data===>",request.data) print("request.post===>",request.POST)
打印结果:
request.body===> b'{ "courseid":1,"policyid":2 }' request.data===> {'courseid': 1, 'policyid': 2} request.post===> <QueryDict: {}>
以上是application/json格式发送请求
下面为 urlencoded格式
print("request.body===>",request.body) print("request.data===>",request.data) print("request.post===>",request.POST)
发送请求:
输出结果:
request.body===> b'k1=123&k2=456' request.data===> <QueryDict: {'k1': ['123'], 'k2': ['456']}> request.post===> <QueryDict: {'k1': ['123'], 'k2': ['456']}>
这些request 不是Django的request , 而是 restframework的request.
request._request为 Django的request
print("request.body===>",request.body) print("request.data===>",request.data) print("request.post===>",request.POST) print("***"*10) print("django's request",request._request.body) print("django's request",request._request.POST)
发送urlencode数据格式
request.body===> b'k1=123&k2=456' request.data===> <QueryDict: {'k1': ['123'], 'k2': ['456']}> restframework的request request.post===> <QueryDict: {'k1': ['123'], 'k2': ['456']}> ****************************** django's request b'k1=123&k2=456' django's request <QueryDict: {'k1': ['123'], 'k2': ['456']}>
发送Application/json数据格式
request.body===> b'{ "courseid":1,"policyid":2 }' request.data===> {'courseid': 1, 'policyid': 2} request.post===> <QueryDict: {}> ****************************** django's request b'{ "courseid":1,"policyid":2 }' django's request <QueryDict: {}>
一、路飞项目的逻辑:
1. 接收用户选中的课程id和价格策略
course_id = request.data.get("courseid") policy_id = request.data.get("policyid")
2. 判断数据的合法性
a.课程是否合法
b.价格策略是否合法
def create(self, request, *args, **kwargs): # 1. 接收用户选中的课程ID和价格策略ID course_id = request.data.get("courseid") policy_id = request.data.get("policyid") # 2.判断数据是否合法 # -课程是否合法 # - 价格策略是否合法 #2.1 课程是否合法 course= models.Course.objects.filter(id =course_id).first() print(course) if not course: return Response({"code":1001,"error":"课程不存在"}) price_policy_query_set =course.price_policy.all() price_policy_dict={} for item in price_policy_query_set: temp ={ "id" :item.id, "price" :item.price, "valid_period" :item.valid_period, "valid_period_display":item.get_valid_period_display() } price_policy_dict[item.id]=temp #2.2 价格策略是否合法 if policy_id not in price_policy_dict: return Response({"code":10002,"error":"价格策略你别瞎改"}) return Response({"code": 222})
构建数据类型
1. 列表
2. 字典 (以id作为key,)
price_policy_query_set =course.price_policy.all() price_policy_list =[] price_policy_dict={} for item in price_policy_query_set: temp ={ "id" :item.id, "price" :item.price, "valid_period" :item.valid_period, "valid_period_display":item.get_valid_period_display() } price_policy_list.append(temp) price_policy_dict[item.id] =temp print(price_policy_list) print("**"*20) print(price_policy_dict) print(("**"*20)) print(item.id ,item.price,item.valid_period,item.get_valid_period_display)
结果:
[{'id': 1, 'price': 100.0, 'valid_period': 7, 'valid_period_display': '1周'}] **************************************** {1: {'id': 1, 'price': 100.0, 'valid_period': 7, 'valid_period_display': '1周'}} **************************************** 1 100.0 7 <bound method curry.<locals>._curried of <PricePolicy: MySQL入门(付费)(1周)100.0>> [{'id': 1, 'price': 100.0, 'valid_period': 7, 'valid_period_display': '1周'}, {'id': 2, 'price': 20000000.0, 'valid_period': 60, 'valid_period_display': '2个月'}] **************************************** {1: {'id': 1, 'price': 100.0, 'valid_period': 7, 'valid_period_display': '1周'}, 2: {'id': 2, 'price': 20000000.0, 'valid_period': 60, 'valid_period_display': '2个月'}} **************************************** 2 20000000.0 60 <bound method curry.<locals>._curried of <PricePolicy: MySQL入门(付费)(2个月)20000000.0>> [10/Aug/2018 20:46:15] "POST /api/v1/shoppingcar/ HTTP/1.1" 200 12
赋值测试:
三、把商品和价格放入购物车:
1. 添加到购物车 create
#3.把商品和价格侧率信息放入购物车shoppingcar """ 购物车中要放: 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 redis不支持字典套字典需要dumps出来 { 1:{ 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 } 2:{ 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 } } { shopping_car_用户ID_课程ID:{ id:课程ID name:课程名称 img: 课程图片 default:... price_list:所有价格策略 } } """ key ="shopping_car_%s_%s"%(1,course_id)
# 1 可以定义为变量 USER_ID =1 CONN.hset(key,"id",course_id) CONN.hset(key,"name",course.name) CONN.hset(key,"name",course.course_img) CONN.hset(key,"deault_price",policy_id) CONN.hset(key,"price_policy_dict",json.dumps(price_policy_dict)) return Response({"已经成功加入购物车"})
#3.把商品和价格侧率信息放入购物车shoppingcar """ 购物车中要放: 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 redis不支持字典套字典需要dumps出来 { 1:{ 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 } 2:{ 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 } } { shopping_car_用户ID_课程ID:{ id:课程ID name:课程名称 img: 课程图片 default:... price_list:所有价格策略 } } """ key ="shopping_car_%s_%s"%(1,course_id) # 1 可以定义为变量 USER_ID =1 CONN.hset(key,"id",course_id) CONN.hset(key,"name",course.name) CONN.hset(key,"name",course.course_img) CONN.hset(key,"deault_price",policy_id) CONN.hset(key,"price_policy_dict",json.dumps(price_policy_dict)) return Response({"已经成功加入购物车"})
测试redis
postman发一个请求
另起一个文件
import json import redis conn =redis.Redis(host="127.0.0.1",port="6379") print(conn.keys()) print(conn.hget('shopping_car_1_1',"id").decode("utf-8")) print(conn.hget('shopping_car_1_1',"name").decode("utf-8")) # print(conn.hget('shopping_car_1_1',"img").decode("utf-8")) # print(conn.hget('shopping_car_1_1',"default_price_id").decode("utf-8")) print(json.loads(conn.hget('shopping_car_1_1',"price_policy_dict").decode("utf-8")))
打印结果:
[b'shopping_car_1_1'] 1 11 {'1': {'id': 1, 'price': 100.0, 'valid_period': 7, 'valid_period_display': '1周'}, '2': {'id': 2, 'price': 20000000.0, 'valid_period': 60, 'valid_period_display': '2个月'}}
2. 查看购物车 list
def list(self,request,*args,**kwargs): ret ={"code":10000,"data":None,"error":None} try: shopping_car_course_list =[] pattern ="shopping_car_%s"%(USER_ID,) user_key_list =CONN.keys(pattern) for key in user_key_list: temp ={ "id":CONN.hget(key,"id").decode("utf-8"), "name":CONN.hget(key,"name").decode("utf-8"), "img":CONN.hget(key,"img").decode("utf-8"), "default_price_id":CONN.hget(key,"default_price_id").decode("utf-8"), "price_policy_dict":json.load(CONN.hget(key,"price_policy_dict").decode("utf-8")) } shopping_car_course_list.append(temp) ret["data"]= shopping_car_course_list except Exception as e: ret["code"]=10005 ret["error"]="获取购物车数据失败" return Response(ret)
3. 购物车删除
url(r'^shoppingcar/$',shoppingcar.ShoppingCarView.as_view({"post":"create","get":"list","delete":"destroy"})),
def destory(self,request,pk,*args,**kwargs): respone= BaseResponse() try: courseid = request.GET.get("couseid") key ="shopping_car_%s_%s*"%(USER_ID,courseid) CONN.delete(key) respone.data ="删除成功" except Exception as e: respone.code =10006 respone.error ="删除失败" return Response("删除成功")
===================购物车逻辑=========================