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)), ]
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
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 #拋出異常
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
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])
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 ]
在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'), }