luffy项目中关于APIView的使用

views中

from rest_framework.views import APIView
from django.shortcuts import HttpResponse

from api.utils.auth_class import LoginAuth
from api.models import *

from django.core.exceptions import ObjectDoesNotExist

from api.utils.response import BaseResponse
import json

from rest_framework.response import Response
from django.http import JsonResponse

from api.utils.exceptions import PriceException

from django_redis import get_redis_connection

class ShoppingCarView(APIView):

    authentication_classes = [LoginAuth,]
    response=BaseResponse()
    conn=get_redis_connection("default")def post(self,request):
     def post(self,request):
        """
        购物车的添加课程请求
        :param request:
        :return:
        """
        .....
     def get(self,request):
        """
        查看购物车列表请求
        :param request:
        :return:
        """
        pass
自定义认证  from api.utils.auth_class import LoginAuth,api是自定义组件(相当于app01)
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from api.models import UserToken

class LoginAuth(BaseAuthentication):

    def authenticate(self, request):      #一定要重写该方法
        token=request.GET.get("token")
        token_obj=UserToken.objects.filter(token=token).first()

        if token_obj:
            return token_obj.user,token_obj.token
        else:
            raise AuthenticationFailed("认证失败了")

 

自定义异常处理  from api.utils.exceptions import PriceException
class PriceException(Exception):

    def __init__(self):
        self.msg="价格策略有问题,你不是人!"

 

自定义 response      from api.utils.response import BaseResponse
class BaseResponse(object):

    def __init__(self):
        self.data=None
        self.error_msg=""
        self.code=1000

    @property
    def dict(self):

        return self.__dict__

 

转载于:https://www.cnblogs.com/95lyj/p/9484549.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值