DjangoRESTframework 接口开发

djangorestframework模块为django提供了restful接口

安装

 

pip install djangorestframework

 

在django项目settings.py 配置文件中加入

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
'rest_framework',
]

解析器

除了直接用url发get请求,我们还有post请求,还有url参数。restframework组件提供了更方便的功能处理各种请求数据

from rest_framework.parsers import FormParser,JSONParser,FileUploadParser,MultiPartParser 

以上四个模块分别用来处理【application/x-www-form-urlencoded】,【application/json】,【multipart/form-data】,【文件上传】,把相关内容赋值给request.data

 全局配置

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES':[
        'rest_framework.parsers.JSONParser'
        'rest_framework.parsers.FormParser'
        'rest_framework.parsers.MultiPartParser'
    ],
}

 使用实例

class UserView(APIView):

    def get(self, request, *args, **kwargs):
        ret = {'code': 1000, 'data': None}
        # request.query_params  #这里取GET的数据
        try:
            obj = models.Register.objects.all()
            ser = UserSerializer(instance=obj, many=True)
            ret['data'] = ser.data
        except Exception as e:
            ret['code'] = 1001
            ret['error'] = '获取用户列表失败'
        return Response(ret)

    def post(self, request, *args, **kwargs):
        ret = {'code': 1000, 'data': None}
        # request.data # 这里取解析器解析的数据
        return Response(ret)

认证

 

django restframework还在django auth模块的基础上集成了认证和权限模块,方便客户登陆,并对访问进行限制

 

其中认证模块主要的功能是确认客户端身份并,并将身份赋值给相关变量(BaseAuthentication)

 

权限模块是通过相关变量拿到客户端身份,并对该身份客户的请求进行限制

自定义认证类

 

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from api import models


class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        """
        Authenticate the request and return a two-tuple of (user, token).
        """
        token = request.query_params.get('token')
        # print(token)
        obj = models.UserToken.objects.filter(token=token).first()
        if not obj:
            raise AuthenticationFailed({'code': 1001, 'error': '登录过期,请重新登陆'})
        return (obj.user.username, token) # 这里返回的元组两个值用户名及token分被处理赋值给 request.user ,request.auth
        # return None # 表示跳过验证 默认用户及token使用配置文件进行设置

    def authenticate_header(self, request):
        pass

 

全局配置

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
    ],
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "api.mmm.auth.MyAuthentication", #这里注意对应认证类的路径
    ],
}

 局部不使用认证类

class UserView(APIView):
    # authentication_classes = [] # 不需要经过认证的视图类需要这里需要写一个空列表

 

权限 

自定义权限类

from rest_framework.permissions import BasePermission


class MyPermission(BasePermission):
    message = "无权访问!"
    def has_permission(self, request, view):
        if 4 > 3:  #这里写权限逻辑 
            return True
        return False

全局配置

 

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
    ],
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "api.mmm.auth.MyAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "api.mmm.Permission.MyPermission",
    ],
}

局部不使用认证类

class UserView(APIView):
    # permission_classes = [] # 不需要经过权限的视图类需要这里需要写一个空列表

 

 访问频率

 自定义类

from rest_framework.throttling import SimpleRateThrottle


class UserRateThrottle(SimpleRateThrottle):
    """
    登录用户,根据用户token限制
    """
    scope = "user"

    def get_cache_key(self, request, view):
        return request.user


class VisitRateThrottle(SimpleRateThrottle):
    """
    访客限制
    """
    scope = "visit"

    def get_cache_key(self, request, view):
        """
        获取缓存key
        :param request:
        :param view:
        :return:
        """
        # 未登录用户,则跳过 Token限制
        if not request.user:
            return None

        return self.cache_format % {
            'scope': self.scope,
            'ident': self.get_ident(request)
        }

 

全局配置

 

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
    ],
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "api.mmm.auth.MyAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "api.mmm.Permission.MyPermission",
    ],
    'DEFAULT_THROTTLE_CLASSES': [
        "api.mmm.Throttle.UserRateThrottle",
    ],
    'DEFAULT_THROTTLE_RATES': {
        'user': '3/s',  # 登录用户
        'visit': '5/m',  # 匿名用户
    },
}

局部使用

from api.mmm.Throttle import VisitRateThrottle #导入匿名用户限制类
class LoginView(APIView):
    authentication_classes = []
    permission_classes = []
    throttle_classes = [VisitRateThrottle, ] 

 

版本控制

url参数方法

 

from django.urls import re_path
from api import views


urlpatterns = [
    re_path(r'^(?P<version>[v1|v2]+)/user/', views.UserView.as_view()),
]

 

全局配置

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
    ],
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "api.mmm.auth.MyAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "api.mmm.Permission.MyPermission",
    ],
    'DEFAULT_THROTTLE_CLASSES': [
        "api.mmm.Throttle.UserRateThrottle",
    ],
    'DEFAULT_THROTTLE_RATES': {
        'user': '20/m',
    },
    'DEFAULT_VERSION': 'v1',  # 默认版本
    'ALLOWED_VERSIONS': ['v1', 'v2'],  # 允许的版本
    'VERSION_PARAM': 'version',  # URL中获取值的key
}

 

版本处理

class UserView(APIView):

    def get(self, request, *args, **kwargs):
        ret = {'code': 1000, 'data': None}
        # request.query_params  #这里取GET的数据

        # request.version # 获取版本

        # request.versioning_scheme # 获取版本管理的类

        reverse_url = request.versioning_scheme.reverse('user', request=request)  # 反向生成URL
        try:
            obj = models.Register.objects.all()
            ser = UserSerializer(instance=obj, many=True)
            ret['data'] = ser.data
        except Exception as e:
            ret['code'] = 1001
            ret['error'] = '获取用户列表失败'
        return Response(ret)

 

 

posted @ 2019-11-26 14:00  丹尼伯夷  阅读(266)  评论(0编辑  收藏  举报