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": })
① 通过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'{\t\n\t"courseid":1,"policyid":2\n\t\n}'
request.data===> {'courseid': , 'policyid': }
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': [''], 'k2': ['']}>
request.post===> <QueryDict: {'k1': [''], 'k2': ['']}>
这些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("***"*)
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': [''], 'k2': ['']}> restframework的request
request.post===> <QueryDict: {'k1': [''], 'k2': ['']}>
******************************
django's request b'k1=&k2='
django's request <QueryDict: {'k1': [''], 'k2': ['']}>
发送Application/json数据格式
request.body===> b'{\t\n\t"courseid":1,"policyid":2\n\t\n}'
request.data===> {'courseid': , 'policyid': }
request.post===> <QueryDict: {}>
******************************
django's request b'{\t\n\t"courseid":,"policyid":\n\t\n}'
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): # . 接收用户选中的课程ID和价格策略ID
course_id = request.data.get("courseid")
policy_id = request.data.get("policyid") # .判断数据是否合法
# -课程是否合法
# - 价格策略是否合法 #2.1 课程是否合法
course= models.Course.objects.filter(id =course_id).first()
print(course)
if not course:
return Response({"code":,"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":,"error":"价格策略你别瞎改"})
return Response({"code": })
构建数据类型
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("**"*)
print(price_policy_dict)
print(("**"*))
print(item.id ,item.price,item.valid_period,item.get_valid_period_display)
结果:
[{'id': , 'price': 100.0, 'valid_period': , 'valid_period_display': '1周'}]
****************************************
{: {'id': , 'price': 100.0, 'valid_period': , 'valid_period_display': '1周'}}
****************************************
100.0 <bound method curry.<locals>._curried of <PricePolicy: MySQL入门(付费)(1周)100.0>>
[{'id': , 'price': 100.0, 'valid_period': , 'valid_period_display': '1周'}, {'id': , 'price': 20000000.0, 'valid_period': , 'valid_period_display': '2个月'}]
****************************************
{: {'id': , 'price': 100.0, 'valid_period': , 'valid_period_display': '1周'}, : {'id': , 'price': 20000000.0, 'valid_period': , 'valid_period_display': '2个月'}}
****************************************
20000000.0 <bound method curry.<locals>._curried of <PricePolicy: MySQL入门(付费)(2个月)20000000.0>>
[/Aug/ ::] "POST /api/v1/shoppingcar/ HTTP/1.1"
赋值测试:
三、把商品和价格放入购物车:
1. 添加到购物车 create
#.把商品和价格侧率信息放入购物车shoppingcar """ 购物车中要放: 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 redis不支持字典套字典需要dumps出来 { :{ 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 } :{ 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 } } { shopping_car_用户ID_课程ID:{ id:课程ID name:课程名称 img: 课程图片 default:... price_list:所有价格策略 } } """ key ="shopping_car_%s_%s"%(,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({"已经成功加入购物车"})
#.把商品和价格侧率信息放入购物车shoppingcar """ 购物车中要放: 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 redis不支持字典套字典需要dumps出来 { 1:{ 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 } 2:{ 课程ID 课程名称 课程图片 默认选中的价格侧率 所有价格策略 } } { shopping_car_用户ID_课程ID:{ id:课程ID name:课程名称 img: 课程图片 default:... price_list:所有价格策略 } } """ key ="shopping_car_%s_%s"%(,course_id)
# 可以定义为变量 USER_ID = 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="")
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'] {'': {'id': , 'price': 100.0, 'valid_period': , 'valid_period_display': '1周'}, '': {'id': , 'price': 20000000.0, 'valid_period': , 'valid_period_display': '2个月'}}
2. 查看购物车 list
def list(self,request,*args,**kwargs):
ret ={"code":,"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"]=
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 =
respone.error ="删除失败"
return Response("删除成功")
===================购物车逻辑=========================