```python
import redis
import json
from rest_framework.viewsimport APIView
from rest_framework.viewsetsimport ViewSetMixin
from rest_framework.responseimport Response
from api.unilt.Bresponseimport Beasresponse
from app01import models
from api.unilt.Bresponseimport Beasresponse
CONN= redis.Redis(host="192.168.11.141",port=6379)
USERID= 1
class Shoppingcar(ViewSetMixin, APIView):
def list(self,request,*args,**kwargs):
"""
使用redis获取数据,构建购物车操作
:param request: redis数据
:param args:
:param kwargs:
:return: 返回判断后的数据
"""
ret= Beasresponse()
try:
shopping_car_all= []
# 获取购物车中的所有数据
shopping_car= "shopping_%s_*" % (USERID,)
pull_shopping_car= CONN.keys(shopping_car)
for keyin pull_shopping_car:
temp= {
'id':CONN.hget(key,"id").decode('utf8'),
'name':CONN.hget(key,"name").decode('utf8'),
'img':CONN.hget(key,"img").decode('utf8'),
'policy_id':CONN.hget(key,"policy_id").decode('utf8'),
'policy_dict':json.loads(CONN.hget(key,"policy_dict").decode('utf8')),
}
shopping_car_all.append(temp)
ret.data= shopping_car_all
ret.code= 10000
except Exception as e:
print(e)
ret.code= 500
ret.error= '获取数据失败'
return Response(ret.dict)
def create(self, request,*args,**kwargs):
"""
接受用户选中的id数据,并且进行校验
:param request:
:param args:
:param kwargs:
:return:
"""
'''
使用到解析器,
a.如果让你编写一个API程序,需要先做什么?
- 业务需求
- 统一数据传输格式
- 表结构设计
- 程序开发
b.django restful framework的解析器的parser_classes的作用?
根据请求中content_type请求头的值,选择指定解析对请求体中的的数据进行解析。
如:
c.支持多个解析器,一般只是用JSON就足够
'''
ret= Beasresponse()
# 1.获取传输过来的数据
coures_id= request.data.get('couresid')
policy_id= request.data.get("policyid")
# print(coures_id,policy_id)
# 2.对数据进行校验,
# 2.1 数据时存在
course= models.Course.objects.filter(id=coures_id).first()
if not course:
ret.code= 500
ret.error= '没有找到此商品'
return Response(ret.dict)
# 2.2 数据是否合法
# 判断合法是寻找策略内容,对策略进行匹配判断
find_policy= course.price_policy.all()
verification= {}
for itemin find_policy:
temp= {
"id": item.id,
"price": item.price,
"period_id": item.valid_period,
"period": item.get_valid_period_display(),
},
verification[item.id] = temp
# 装载该商品的所有策略内容
if policy_idnot in verification:
ret.code= 501
ret.error= '此商品策略有误!!'
return Response(ret.dict)
# 3.把商品数据放入购物车中
shoppingcar= "shopping_%s_%s" % (USERID, coures_id)
# 购物车的数量限制!
keys= CONN.keys(shoppingcar)
if keysand len(keys) > 1000:
ret.error= '购物车商品太多了,清空购物车吧~'
ret.code= 600
return Response(ret.dict)
CONN.hset(shoppingcar,"id", coures_id)
CONN.hset(shoppingcar,"name", course.name)
CONN.hset(shoppingcar,"img", course.course_img)
CONN.hset(shoppingcar,"policy_id", policy_id)
CONN.hset(shoppingcar,"policy_dict", json.dumps(verification))
# 3.1 数据传输方式:
# shopping_用户id_商品id:{
# {商品id}:
# { 商品id
# 商品名称
# 商品img:
# 默认选中的策略id:
# 默认选中的价格:
# 商品所有策略:{
# 策略id:{price:'',天数:''}
# }
# }
# }
ret.code= 10000
ret.data= '购物车添加成功'
return Response(ret.dict)
def destroy(self,request,*args,**kwargs):
ret= Beasresponse()
try:
couresid= request.GET.get('couresid')
key= 'shopping_%s_%s' % (USERID, couresid)
CONN.delete(key)
ret.code= 10000
ret.data= '删除成功'
except Exception as e:
ret.code= 500
ret.error= '出错了'
return Response(ret.dict)
def update(self,request,pk,*args,**kwargs):
ret= Beasresponse()
try:
course_id= request.data.get("couresid")
policy_id= str(request.data.get('policyid')) if request.data.get("policyid") else None
key= "shopping_%s_%s" % (USERID,course_id)
if not CONN.exists(key):
ret.code= 10002
ret.error= "课程不存在"
return Response(ret.dict)
price_policy_dict= json.loads(CONN.hget(key,'policy_dict').decode('utf-8'))
if policy_idnot in price_policy_dict:
ret.code= 10086
ret.error= '价格不匹配'
return Response(ret.dict)
CONN.hset(key,"policy_id",policy_id)
ret.data= '修改成功'
except Exception as e:
ret.code= 10009
ret.error= '修改无效'
return Response(ret.dict)
```
-------------------------------------------
alipay
```python
import uuid
from django.shortcutsimport render
from django.shortcutsimport redirect, HttpResponse, render
from unitl.payimport AliPay
from app1import models
# Create your views here.
def index(request):
goods_list= models.Goods.objects.all()
return render(request,'index.html',{'goods_list': goods_list})
def buy(request, gid):
"""
购买且支付
:param request:
:param gid:
:return:
"""
obj= models.Goods.objects.get(pk=gid)
# 生成订单(未支付状态)
no= str(uuid.uuid4())
models.Order.objects.create(no=no,goods_id=obj.id)
# 根据阿里自带的id还有支付宝网关,使用公钥和私钥,生成要跳转的地址
# 沙箱环境地址:https://openhome.alipay.com/platform/appDaily.htm?tab=info
alipay= AliPay(
appid='2016091700528867',
app_notify_url='http://118.24.89.136:8000/check_order/',
# POST,发送支付状态
return_url='http://118.24.89.136:8000/show/',
# GET,将用户浏览器地址重定向回源网站
app_private_key_path="keys\\app_private_2048.txt",
alipay_public_key_path="keys\\alipay_pulic_2048.txt",
debug=True,
# 默认True测试环境,Fales正式环境
)
query_params= alipay.direct_pay(
subject=obj.name,# 商品简单描述
out_trade_no=no,# 商户订单号
total_amount=obj.price,# 交易金额(单位:元 保留两位小数)
)
pay_url= "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)
return redirect(pay_url)
def check_order(request):
"""
POST请求,支付宝通知支付信息,我们修订订单状态
:param request:
:return:
"""
if request.method== "POST":
alipay= AliPay(
appid='2016091700528867',
app_notify_url='http://118.24.89.136:8000/check_order/',
# POST,发送支付状态
return_url='http://118.24.89.136:8000/show/',
# GET,将用户浏览器地址重定向回源网站
app_private_key_path="keys\\app_private_2048.txt",
alipay_public_key_path="keys\\alipay_pulic_2048.txt",
debug=True,
# 默认True测试环境,Fales正式环境
)
from urllib.parseimport parse_qs
body_str= request.body.decode('utf-8')
post_data= parse_qs(body_str)
post_dict= {}
for k,vin post_data.items():
post_dict[k] = v[0]
sign= post_dict.pop('sign',None)
status= alipay.verify(post_dict, sign)
if status:
# 支付成功,获取订单号将订单状态更新
out_trade_no= post_dict['out-trade_no']
models.Order.objects.filter(no=out_trade_no).update(status=2)
return HttpResponse('success')
else:
return HttpResponse('支持失败')
else:
return HttpResponse('只支持POST请求')
def show(request):
"""
回到我们页面
:param request:
:return:
"""
if request.method== 'GET':
alipay= AliPay(
appid='2016091700528867',
app_notify_url='http://118.24.89.136:8000/check_order/',
# POST,发送支付状态
return_url='http://118.24.89.136:8000/show/',
# GET,将用户浏览器地址重定向回源网站
app_private_key_path="keys\\app_private_2048.txt",
alipay_public_key_path="keys\\alipay_public_2048.txt",
debug=True,
# 默认True测试环境,Fales正式环境
)
params= request.GET.dict()
sign= params.pop('sign',None)
status= alipay.verify(params, sign)
if status:
return HttpResponse('支付成功')
else:
return HttpResponse('失败')
else:
return HttpResponse('只支持GET请求')
def order_list(request):
"""
:param request:
:return:
"""
orders= models.Order.objects.all()
return render(request,'order_list.html',{'orders': orders})
```