1.设置路由 urls.py
from django.conf.urls import url,include from django.contrib import admin from rest_framework import routers from app01 import views ##实例化routers,将请求路径和执行函数注册到routers中 routers=routers.DefaultRouter() routers.register("authors",views.AuthorModelView) routers.register("book",views.BookModelView) routers.register("publish",views.PublishModelView) urlpatterns = [ url(r'^admin/', admin.site.urls), #进行路由分发 url(r"^", include(routers.urls)), ]
2.views.py
from app01 import models from rest_framework.serializers import ModelSerializer from rest_framework.viewsets import ModelViewSet class BookModelSerializers(ModelSerializer): class Meta: model=models.Book fields="__all__" class PublishModelSerializers(ModelSerializer): class Meta: model = models.Publish fields = "__all__" class AuthorModelSerializers(ModelSerializer): class Meta: model = models.Author fields = "__all__" class BookModelView(ModelViewSet): ##queryset和serializer_class这两个变量名不能变 queryset=models.Book.objects.all() serializer_class = BookModelSerializers class PublishModelView(ModelViewSet): ##queryset和serializer_class这两个变量名不能变 queryset = models.Publish.objects.all() serializer_class = PublishModelSerializers class AuthorModelView(ModelViewSet): ##queryset和serializer_class这两个变量名不能变 queryset = models.Author.objects.all() serializer_class = AuthorModelSerializers
3.局部添加添加认证和权限组件
新建service文件夹,将认证,权限,(访问频率)组件的逻辑关系放到这个文件夹中
auth.py 认证逻辑关系
from rest_framework import HTTP_HEADER_ENCODING, exceptions from rest_framework.exceptions import AuthenticationFailed from rest_framework.authentication import BaseAuthentication from rest_framework.authentication import SessionAuthentication from app01.models import UserToken class AuthUser(BaseAuthentication): #类名可以随便器 def authenticate(self,request): #函数名只能是这个 token=request.GET.get("token") token_obj=UserToken.objects.filter(token=token).first() if token_obj: return token_obj.users.name,token #返回元祖 else: raise AuthenticationFailed #抛出异常
permission.py 权限逻辑关系
from app01.models import UserToken from app01.models import UserToken from rest_framework.permissions import BasePermission class SVIPpermission(BasePermission): message="您没有权限访问该资源" def has_permission(self,request,obj): # print(request.user) # print(request.auth) token_obj=UserToken.objects.filter(token=request.auth).first() if token_obj.users.role in [2,3]: return True else: return False
throttle.py 访问频率
from rest_framework.throttling import BaseThrottle VISIT_RECORD={} class VisitThrottle(BaseThrottle): def __init__(self): self.history=None def allow_request(self,request,view): remote_addr = request.META.get('REMOTE_ADDR') print(remote_addr) import time ctime=time.time() if remote_addr not in VISIT_RECORD: VISIT_RECORD[remote_addr]=[ctime,] return True history=VISIT_RECORD.get(remote_addr) self.history=history while history and history[-1]<ctime-60: history.pop() if len(history)<3: history.insert(0,ctime) return True else: return False def wait(self): import time ctime=time.time() return 60-(ctime-self.history[-1])
views.py
from app01.service.auth import * from app01.service.permission import * from app01.service.throttle import * ##分页设置函数 from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination from rest_framework.parsers import JSONParser,FormParser #响应器设置,JSONRenderer页面只以json字符串显示,没有样式 from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer class MyPageNumberPagination(PageNumberPagination): page_size = 1 page_size_query_param="size" max_page_size=2 class AuthorModelView(ModelViewSet): queryset = models.Author.objects.all() serializer_class = AuthorModelSerializers #添加认证组件 authentication_classes = [AuthUser] #添加权限组件 permission_classes = [SVIPpermission] #throttle(访问频率)组件 throttle_classes = [VisitThrottle] #分页 pagination_class = MyPageNumberPagination #数据解析器 parser_classes = [JSONParser] #响应器 renderer_classes = [JSONRenderer,BrowsableAPIRenderer ]
4.全局设置
在setting.py中设置 REST_FRAMEWORK={ "DEFAULT_AUTHENTICATION_CLASSES":( "app01.service.auth.AuthUser", ), "DEFAULT_PERMISSION_CLASSES":( "app01.service.permission.SVIPpermission", ), "DEFAULT_THROTTLE_CLASSES":( "app01.service.throttle.VisitThrottle", ), "DEFAULT_PARSER_CLASSES":('rest_framework.parsers.FormParser',), "DEFAULT_RENDERER_CLASSES":('rest_framework.renderers.JSONRenderer'), }