Django-restframework 认证

【view层】

from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions


# 认证类
class MyAuthentication(object):
    def authenticate(self, request):
        # token = request._request.GET.get('token')
        name = request._request.GET.get('name')
        pwd = request._request.GET.get('pwd')
        '''
        # 获取用户名和密码,去校验数据
        这里写获取用户和校验代码
        '''
        print(name, pwd)

        # if not token:
        if not name and not pwd:
            raise exceptions.AuthenticationFailed('用户认证失败')
        return ('alex', None)
    # 这个方法是必写的,先这么写着
    def authenticate_header(self, xxx):
        pass


class DogView(APIView):
    # authentication_classes = [BaseAuthentication,]
    authentication_classes = [MyAuthentication,]
    def get(self, request, *args, **kwargs):
        res = {
            'code':1000,
            'msg':{'msg':'Dog'}
        }

        print('获取Dog')
        return HttpResponse(json.dumps(res))

    def post(self, requst, *args, **kwargs):
        return HttpResponse('提交Dog')

    def delete(self, request, *args, **kwargs):
        print('删除Dog')
        return HttpResponse('删除Dog')

    def put(self, request, *args, **kwargs):
        print('更新Dog')
        return HttpResponse('更新Dog')

【url路由配置】

urlpatterns = [
    path('dog/', DogView.as_view()),
]

你可能感兴趣的:(Django,RestFramework,django,Python)