Django rest framework ---- 权限

Posted blueskyyj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django rest framework ---- 权限相关的知识,希望对你有一定的参考价值。

Django rest framework ---- 权限

添加权限

api/utils文件夹下新建premission.py文件,代码如下:

  • message是当没有权限时,提示的信息
# FileName : permission.py
# Author   : Adil
# DateTime : 2019/7/30 5:14 PM
# SoftWare : PyCharm
from rest_framework.permissions import BasePermission

class SVIPPermission(object):

    message = 必须是SVIP才能访问!
    def has_permission(self,request,view):
        if request.user.user_type !=3:
            return False

        return True

class MyPermission(object):

    def has_permission(self,request,view):
        if request.user.user_type == 3:
            return False
        return True

settings.py全局配置权限

#设置全局认证
REST_FRAMEWORK = 
    "DEFAULT_AUTHENTICATION_CLASSES":[api.utils.auth.Authentication,],   #里面写你的认证的类的路径
    "DEFAULT_PERMISSION_CLASSES":[api.utils.permission.SVIPPermission,],  # 添加权限路径

views.py添加权限

  • 默认所有的业务都需要SVIP权限才能访问
  • OrderView类里面没写表示使用全局配置的SVIPPremission
  • UserInfoView类,因为是普通用户和VIP用户可以访问,不使用全局的,要想局部使用的话,里面就写上自己的权限类
  • permission_classes = [MyPremission,]   #局部使用权限方法
from django.shortcuts import render

# Create your views here.

import time
from api import models
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework import exceptions
from rest_framework.authentication import BasicAuthentication
from django.shortcuts import render,HttpResponse

from api.utils.permission import SVIPPermission,MyPermission



ORDER_DICT = 

    1:
        name:apple,
        price:15
    ,
    2:
        name:orange,
        price:30
    




def md5(user):
    import hashlib
    import time
    ctime = str(time.time())
    print(ctime)
    m = hashlib.md5(bytes(user,encoding=utf-8))
    print(m)
    m.update(bytes(ctime,encoding=utf-8))
    print(m)
    usertoken = m.hexdigest()
    print(usertoken)

    return usertoken



class AuthView(APIView):

    authentication_classes = []  # 里面为空,代表不需要认证
    permission_classes = []
    def post(self,request,*args,**kwargs):
        print(参数,request)

        ret = code:1000,msg:None,token:None
        try:
            # 参数是datadict 形式
            usr = request.data.get(username)
            pas = request.data.get(password)

            # usr = request._request.POST.get(‘username‘)
            # pas = request._request.POST.get(‘password‘)

            # usr = request.POST.get(‘username‘)
            # pas = request.POST.get(‘password‘)

            print(usr)
            print(pas)
            # obj = models.User.objects.filter(username=‘yang‘, password=‘123456‘).first()
            obj = models.User.objects.filter(username=usr,password=pas).first()
            # obk =models.userToken.objects.filter(token=‘9c979c316d4ea42fd998ddf7e8895aa4‘).first()
            # print(obk.token)
            print(******)
            print(obj)
            print(type(obj))
            print(obj.username)
            print(obj.password)
            if not obj:
                ret[code] = 1001
                ret[msg] = 用户名或者密码错误
                return JsonResponse(ret)
                # 里为了简单,应该是进行加密,再加上其他参数
            # token = str(time.time()) + usr
            token = md5(usr)
            print(token)
            models.userToken.objects.update_or_create(user=obj, defaults=token: token)
            ret[token] = token
            ret[msg] = 登录成功
            #ret[‘token‘] = token
        except Exception as e:
            ret[code] = 1002
            ret[msg] = 请求异常
        return JsonResponse(ret)


class OrderView(APIView):
    ‘‘‘订单业务‘‘‘

    # authentication_classes = []

    # permission_classes = []
    def get(self,request,*args,**kwargs):
        print("~~~~~~")
        print(request.user)
        print(request.auth)
        print("~~~~~~")
        ret = code:1000,msg:None,data:None
        try:
            ret[data] = ORDER_DICT
        except Exception as e:
            pass
        return JsonResponse(ret)




class UserInfoView(APIView):
    ‘‘‘
       订单相关业务(普通用户和VIP用户可以看)
       ‘‘‘
    permission_classes = [MyPermission,]    #不用全局的权限配置的话,这里就要写自己的局部权限
    def get(self,request,*args,**kwargs):

        print(request.user)
        return HttpResponse(用户信息)



# if __name__ == ‘__main__‘:
#
#     md5(‘yang‘)

 

urls

"""logintest URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path(‘‘, views.home, name=‘home‘)
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path(‘‘, Home.as_view(), name=‘home‘)
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path(‘blog/‘, include(‘blog.urls‘))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import url

from api.views import AuthView
from api.views import OrderView,UserInfoView
from api.appview.register import registerView
from django.views.generic.base import TemplateView  # 1、增加该行



urlpatterns = [
    path(admin/, admin.site.urls),
    path(r‘‘,TemplateView.as_view(template_name=index.html)),  #2、 增加该行
    url(r^api/v1/auth/$, AuthView.as_view()),
    url(r^api/v1/order/$, OrderView.as_view()),   # 权限
    url(r^api/v1/info/,UserInfoView.as_view()),    # 权限
    url(r^home/register/$, registerView.as_view()),
]

测试

普通用户访问OrderView,提示没有权限

技术图片

 

 普通用户访问UserInfoView,可以返回信息

 技术图片

 

内置权限

 django-rest-framework内置权限BasePermission

默认是没有限制权限

class BasePermission(object):
    """
    A base class from which all permission classes should inherit.
    """

    def has_permission(self, request, view):
        """
        Return `True` if permission is granted, `False` otherwise.
        """
        return True

    def has_object_permission(self, request, view, obj):
        """
        Return `True` if permission is granted, `False` otherwise.
        """
        return True

我们自己写的权限类,应该去继承BasePermission,修改之前写的permission.py文件

 

# utils/permission.py

from rest_framework.permissions import BasePermission

class SVIPPremission(BasePermission):
    message = "必须是SVIP才能访问"
    def has_permission(self,request,view):
        if request.user.user_type != 3:
            return False
        return True


class MyPremission(BasePermission):
    def has_permission(self,request,view):
        if request.user.user_type == 3:
            return False
        return True

总结:

(1)使用

  • 自己写的权限类:1.必须继承BasePermission类;  2.必须实现:has_permission方法

(2)返回值

  • True   有权访问
  • False  无权访问

(3)局部

  • permission_classes = [MyPremission,] 

 (4)全局

 
REST_FRAMEWORK = 
   #权限
    "DEFAULT_PERMISSION_CLASSES":[api.utils.permission.SVIPPremission],

 

 

以上是关于Django rest framework ---- 权限的主要内容,如果未能解决你的问题,请参考以下文章

Django-rest-framework 和 django-rest-framework-jwt APIViews and validation Authorization headers

Django Rest Framework 和 django Rest Framework simplejwt 两因素身份验证

django rest framework中文介绍

为啥 django-rest-framework 不显示 OneToOneField 数据 - django

Django:rest framework之分页(Pagination)

django使用rest_framework