python drf各類組件的用法和作用
自定義認(rèn)證的類 ''' from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed from authapp.models import UserToken class MyOrderAuthentication(BaseAuthentication): 在這里實現(xiàn)認(rèn)證的邏輯 def authenticate(self, request): token = request._request.GET.get(’token’) # 獲取到token之后,需要在數(shù)據(jù)庫中查找token obj = UserToken.objects.filter(token=token).first() if not obj: # 沒有通過認(rèn)證 raise AuthenticationFailed(’認(rèn)證失敗’) # 返回元組( user, auth ) return (obj.user, obj) ''' 使用局部配置(在視圖函數(shù)中) ''' class OrderView(APIView): # 通過authentication_classes設(shè)置認(rèn)證類 authentication_classes = [MyOrderAuthentication,] # 通過authentication_classes設(shè)置為空列表,就不再進(jìn)行認(rèn)證了 # authentication_classes = [] ''' 全局配置 ''' REST_FRAMEWORK = { ’DEFAULT_AUTHENTICATION_CLASSES’:[’unitls.authentication.MyOrderAuthentication’], } ''' 設(shè)置匿名用戶 ''' REST_FRAMEWORK = { ’UNAUTHENTICATED_USER’: lambda :'匿名用戶', ’UNAUTHENTICATED_TOKEN’: lambda :’123456’, } ''' ## 最最重要的,理清認(rèn)證的源代碼權(quán)限
自定義權(quán)限類 ''' from rest_framework.permissions import BasePermission class MyOrderPermission(BasePermission): #自定義權(quán)限認(rèn)證的類,必須要實現(xiàn)has_permission方法 message = ’你不是超級用戶,沒有權(quán)限訪問’ def has_permission(self, request, view): #Return `True` if permission is granted, `False` otherwise. #返回True表示有權(quán)限訪問,返回False表示沒有權(quán)限訪問 if request.user.user_type != 3: return False return True ''' 局部使用 ''' class OrderView(APIView): # permission_classes設(shè)置權(quán)限類 permission_classes = [MyOrderPermission,] # 通過authentication_classes設(shè)置為空列表,就不再進(jìn)行權(quán)限認(rèn)證了 permission_classes = [] ''' 全局的設(shè)定 ''' REST_FRAMEWORK = { ’DEFAULT_PERMISSION_CLASSES’:[’unitls.permission.MyOrderPermission’], } ''' 最最重要的,理清權(quán)限認(rèn)證的源代碼分頁
自定義分頁類PageNumberPagination # 自定制分頁類 class MyPageNumberPagination(PageNumberPagination): '''http://127.0.0.1:8000/api/userpage/?page=1&pagesize=10''' # page_size每一返回多少條 page_size = 5 # 設(shè)置分頁的參數(shù)名 page_query_param = ’page’ # 設(shè)置每頁返回數(shù)據(jù)量的參數(shù)名 page_size_query_param = ’pagesize’ # 設(shè)置每頁最大返回的條數(shù) max_page_size = 6 使用 class UsersPageView(APIView): def get(self,request,*args,**kwargs): # 獲取表中所有用戶的row(記錄) obj = models.UserInfo.objects.all() #實例化分頁的類 #page_obj = PageNumberPagination() page_obj = MyPageNumberPagination() #獲取分頁數(shù)據(jù) page_data = page_obj.paginate_queryset( queryset=obj,request=request,view=self) # 序列化 ser = UsersSerializer(instance=page_data,many=True)# return Response(ser.data) #get_paginated_response會返回上一頁下一頁和總條數(shù) return page_obj.get_paginated_response(ser.data) 自定義分頁類LimitOffsetPagination from rest_framework.pagination import LimitOffsetPagination class MyLimitOffsetPagination(LimitOffsetPagination): '''http://127.0.0.1:8000/api/userpage/?limit=10&offset=0''' default_limit = 5 limit_query_param = ’limit’ offset_query_param = ’offset’ max_limit = 7 自定義分頁類CursorPagination(會對分頁參數(shù)進(jìn)行加密) from rest_framework.pagination import CursorPagination class MyCursorPagination(CursorPagination): '''http://127.0.0.1:8000/api/userpage/?cursor=cD01''' cursor_query_param = ’cursor’ page_size = 4 #返回數(shù)據(jù)市的排序的方式 ordering = ’-id’ max_page_size = 8 設(shè)置全局的分頁 ''' REST_FRAMEWORK = { ’DEFAULT_PAGINATION_CLASS’:’unitl.pagination.MyCursorPagination’, ’PAGE_SIZE’:3 } '''視圖
以前 (Django的View) ''' class MyView(View) ..... ''' 現(xiàn)在(rest_framework的APIView) ''' class MyView(APIView) ..... ''' 其他視圖的使用 第一個:GenericAPIView 視圖的使用 (跟繼承自APIViewq其實一樣,只是我們在外面邏輯, GenericAPIView在內(nèi)部c定制方法幫我們實現(xiàn)了) ''' from rest_framework.generics import GenericAPIView class BookinfoSeralizer(serializers.ModelSerializer):class Meta: model = models.BookInfo fields = '__all__' class BookView(GenericAPIView): # queryset: 設(shè)置獲取的數(shù)據(jù) queryset = models.BookInfo.objects.all() # serializer_class: 設(shè)置序列化的類 serializer_class = BookinfoSeralizer # pagination_class : 設(shè)置分頁的類 pagination_class = MyPageNumberPagination def get(self,request,*args,**kwargs): obj = self.get_queryset() #=> obj = models.BookInfo.objects.all() # 獲取當(dāng)前分頁的數(shù)據(jù) page_data = self.paginate_queryset(obj) #=>page_obj = MyPageNumberPagination() #獲取分頁數(shù)據(jù)page_data = page_obj.paginate_queryset() # 獲取序列化之后的數(shù)據(jù) ser = self.get_serializer(instance=page_data,many=True) #->ser = BookinfoSeralizer(instance=page_data,many=True) return Response(ser.data) ''' 第二個:GenericViewSet 視圖的如下使用,注意路由會發(fā)生變化 ''' class BookView(GenericViewSet): # queryset: 設(shè)置獲取的數(shù)據(jù) queryset = models.BookInfo.objects.all() # serializer_class: 設(shè)置序列化的類 serializer_class = BookinfoSeralizer # pagination_class : 設(shè)置分頁的類 pagination_class = MyPageNumberPagination def list(self,request,*args,**kwargs):obj = self.get_queryset() #=> obj = models.BookInfo.objects.all()# 獲取當(dāng)前分頁的數(shù)據(jù)page_data = self.paginate_queryset(obj) #=>page_obj = MyPageNumberPagination() #獲取分頁數(shù)據(jù)page_data = page_obj.paginate_queryset(# 獲取序列化之后的數(shù)據(jù)ser = self.get_serializer(instance=page_data,many=True) #->ser = BookinfoSeralizer(instance=page_data,many=True)return Response(ser.data) ''' 路由會發(fā)生變化,配置如下 ''' url(r'bookpage/$',views.BookView.as_view({’get’: ’list’}),name=’bookpage’) '''第三個:ListModelMixin,CreateModelMixin,RetrieveModelMixin, DestroyModelMixin,UpdateModelMixin 等視圖的使用''' from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin from rest_framework.viewsets import GenericViewSet # ListModelMixin : 返回列表數(shù)據(jù)據(jù)( get請求) # CreateModelMixin : 新增一條數(shù)據(jù) (Post請求) # RetrieveModelMixin, : 獲取詳情數(shù)據(jù) (get請求) # DestroyModelMixin, : 刪除數(shù)據(jù)的時候 (delete) # UpdateModelMixin : 跟新數(shù)據(jù)的時候使用 (put) class BookView(ListModelMixin,RetrieveModelMixin,CreateModelMixin,DestroyModelMixin,UpdateModelMixin,GenericViewSet): # queryset: 設(shè)置獲取的數(shù)據(jù) queryset = models.BookInfo.objects.all() # serializer_class: 設(shè)置序列化的類 serializer_class = BookinfoSeralizer # pagination_class : 設(shè)置分頁的類 pagination_class = MyPageNumberPagination ''' 第四個:ModelViewSet視圖的使用 ModelViewSet繼承自istModelMixin,CreateModelMixin, RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin視圖 如果要實現(xiàn)最基本的增刪改查功能,就直接繼承自ModelViewSet ''' from rest_framework.viewsets import ModelViewSet class BookView(ModelViewSet): # queryset: 設(shè)置獲取的數(shù)據(jù) queryset = models.BookInfo.objects.all() # serializer_class: 設(shè)置序列化的類 serializer_class = BookinfoSeralizer # pagination_class : 設(shè)置分頁的類 pagination_class = MyPageNumberPagination ''' 視圖使用小總結(jié) 只想實現(xiàn)簡單的增刪改查ModelViewSet 只想增CreateModelMixin,GenericViewSet 只想增刪改CreateModelMixin,DestroyModelMixin,UpdateModelMixin,GenericViewSet 如果視圖中的業(yè)務(wù)邏輯復(fù)雜,以上都不能滿足的時候,直接使用APIView #自動路由配置 ''' from django.conf.urls import url,include from api import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'bookpage',views.BookView,base_name=’bookpage’) urlpatterns = [ url(r’v1/’,include(router.urls)), ] ''' 自動路由會生成四個接口 ^api/ v1/ ^bookpage/$ [name=’bookpage-list’] ^api/ v1/ ^bookpage.(?P<format>[a-z0-9]+)/?$ [name=’bookpage-list’] ^api/ v1/ ^bookpage/(?P<pk>[^/.]+)/$ [name=’bookpage-detail’] ^api/ v1/ ^bookpage/(?P<pk>[^/.]+).(?P<format>[a-z0-9]+)/?$ [name=’bookpage-detail’]頻率限制節(jié)流
節(jié)流: 自定義節(jié)流類 ''' VISIT_RECORD = {} class VisitThrottle(object): def __init__(self): self.history = None def allow_request(self,request,view): #實現(xiàn)節(jié)流的邏輯 #基于ip做節(jié)流 # #獲取用戶訪問的IP地址 # ip_address = request._request.META.get(’REMOTE_ADDR’) ctime = time.time() # if ip_address not in VISIT_RECORD: # #第一次訪問的時候?qū)⒃L問的時間存儲在字典中(ip地址為Key,訪問的時間為value值) # VISIT_RECORD[ip_address] = [ctime,] # # #第二次訪問的時候取出訪問的歷史記錄 # history = VISIT_RECORD[ip_address] # 基于用戶的節(jié)流 username = request.user.username if username not in VISIT_RECORD:VISIT_RECORD[username] = [ctime, ] history = VISIT_RECORD[username] self.history = history while history and history[-1] < ctime - 10:#如果訪問的時間記錄超過60秒,就把超過60秒的時間記錄移除history.pop() if len(history) < 6:history.insert(0,ctime)return True return False def wait(self): #一旦用戶訪問次數(shù)到達(dá)閥值,顯示用戶需要等待的時間 ctime = time.time() #09:54:30 09:54:28 return 10 - (ctime - self.history[-1]) ''' 局部使用 ''' class OrderView(APIView): # throttle_classes設(shè)置節(jié)流類 throttle_classes = [VisitThrottle,] '''全局設(shè)置 ''' REST_FRAMEWORK = { ’DEFAULT_THROTTLE_CLASSES’:[’unitls.throttle.VisitThrottle’], } ''' 使用DRF內(nèi)置的限頻類 ''' from rest_framework.throttling import SimpleRateThrottle #推薦使用這種 class VisitThrottle(SimpleRateThrottle): #沒有登錄用戶,每分鐘訪問10次 scope = ’logined’ def get_cache_key(self, request, view): return request.user.username ''' 全局設(shè)置 ''' REST_FRAMEWORK = { ’DEFAULT_THROTTLE_RATES’:{ ’unlogin’:’10/m’, ’logined’:’3/m’, }, ’DEFAULT_THROTTLE_CLASSES’:[’unitls.throttle.VisitThrottle’], } '''版本控制
自定義版本控制類 ''' class ParmasVersion(object): def determine_version(self, request, *args, **kwargs):version = request.query_params.get(’version’)return version ''' 使用(局部) ''' class VersionView(APIView): #設(shè)置獲取版本的類 versioning_class = ParmasVersion ''' 全局設(shè)置 ''' ’DEFAULT_VERSIONING_CLASS’:’unitls.version.ParmasVersion’, ''' 使用 DRF內(nèi)置的版本控制類QueryParameterVersioning(局部) ''' from rest_framework.versioning import QueryParameterVersioning class VersionView(APIView): #設(shè)置獲取版本的類 versioning_class = QueryParameterVersioning ''' 設(shè)置文件中的配置信息 ''' REST_FRAMEWORK = { ’VERSION_PARAM’:’version’, ’DEFAULT_VERSION’:’v1’, ’ALLOWED_VERSIONS’:[’v1’,’v2’], } ''' 全局設(shè)置 ''' REST_FRAMEWORK = { ’VERSION_PARAM’:’version’, ’DEFAULT_VERSION’:’v1’, ’ALLOWED_VERSIONS’:[’v1’,’v2’], ’DEFAULT_VERSIONING_CLASS’:’rest_framework.versioning.QueryParameterVersioning’, } ''' 使用 DRF內(nèi)置的版本控制類URLPathVersioning(局部) ''' from rest_framework.versioning import URLPathVersioning class VersionView(APIView): #設(shè)置獲取版本的類 versioning_class = URLPathVersioning ''' 設(shè)置文件中的配置信息 ''' REST_FRAMEWORK = { ’VERSION_PARAM’:’version’, ’DEFAULT_VERSION’:’v1’, ’ALLOWED_VERSIONS’:[’v1’,’v2’], } ''' 全局設(shè)置 ''' REST_FRAMEWORK = { ’VERSION_PARAM’:’version’, ’DEFAULT_VERSION’:’v1’, ’ALLOWED_VERSIONS’:[’v1’,’v2’], ’DEFAULT_VERSIONING_CLASS’:’rest_framework.versioning.URLPathVersioning’, } ''' 如果使用URLPathVersioning,路由格式如下 ''' url(r'^(?P<version>[v1|v2]+)/version/',VersionView.as_view(),name=’vvvv’) ''' #使用 DRF內(nèi)置的版本控制類URLPathVersioning 反向生成url地址 ''' #反向生成url地址 reverse obj = request.versioning_scheme url1 = obj.reverse(viewname=’orders’,request=request)#使用django的reverse方法反響生成url地址 from django.urls import reverse url2 = reverse(viewname=’orders’,kwargs={’version’:’v2’}) '''解析器
因為開發(fā)人員post請求上傳數(shù)據(jù)時,傳遞的數(shù)據(jù)類型不同,我們可能在request._request.POST中獲取不到數(shù)據(jù) case1: Content-Type : application/x-www-form-urlencoded 服務(wù)端接收到的post請求的數(shù)據(jù)格式:username=xxxxx&age=18&sex=男 我們就可以在request._request.POST中獲取到數(shù)據(jù) ''' class UserInfoView(APIView): def post(self,request,*args,**kwargs):username = request._request.POST.get(’username’)age = request._request.POST.get(’age’)sex = request._request.POST.get(’sex’) ''' case2:Content-Type:application/json 服務(wù)端接收到的post請求的數(shù)據(jù)格式就是json數(shù)據(jù):{'username':'xxxx','age':'18','sex':'男'} 在request._request.POST中就獲取不到數(shù)據(jù),但是在request.body中可以拿到 ''' class UserInfoView(APIView): def post(self,request,*args,**kwargs):import jsondata = json.loads(request.body.decode(’utf8’))print(data) ''' DRF內(nèi)置的解析器FormParser,JSONParser 使用(局部): ''' from rest_framework.parsers import FormParser,JSONParser class UserInfoView(APIView): parser_classes = [FormParser,JSONParser] #這時DRF 內(nèi)部代碼會根據(jù)request.Content-Type和解析器支持的media_type比較 從而選擇對應(yīng)的解析器 def post(self,request,*args,**kwargs):# 如果使用JSONParser、FormParser解析數(shù)據(jù)的話data = request.dataprint(data)'''渲染器
渲染器 INSTALLED_APPS = [ ’rest_framework’, ] from rest_framework.renderers import BrowsableAPIRenderer,JSONRenderer,AdminRenderer class BookView(ModelViewSet): # 設(shè)置渲染器類型 renderer_classes = [JSONRenderer]序列化
Django的序列化 ''' #django序例化方式一 books = models.BookInfo.objects.all().values(’id’,’bookname’) books = list(books) print(type(books), books) self.ret[’books’] = books #django序例化方式二 books = models.BookInfo.objects.all() books = [model_to_dict(item) for item in books] self.ret[’books’] = books ''' DRF 序列化 第一種:繼承自serializers.Serializer ''' class BookDetailSerializer(serializers.Serializer): # 正常的字段序列化 id = serializers.IntegerField() bookname = serializers.CharField() author = serializers.CharField() category = serializers.IntegerField() bookdesc = serializers.CharField() # 獲取枚舉類型的文本是 source=get_字段名_display status = serializers.CharField( source=’get_status_display’ ) categoryname = serializers.CharField( source=’get_category_display’ ) # 自定義方法獲取字段 chpaters = serializers.SerializerMethodField() #序列化時可以自定義方法獲取字段 def get_chpaters(self,row): ''' row - > bookinfo ''' chpaters = models.ChpaterInfo.objects.filter(book=row) ser = ChpaterSerializer(instance=chpaters,many=True, context=self.context ) return ser.data ''' 序列化時生成url ''' url = serializers.HyperlinkedIdentityField( view_name=’chpaterdetail’, lookup_field=’id’, lookup_url_kwarg=’pk’, ) ''' 注意:如果序列化類中使用HyperlinkedIdentityField生成url,那我們在序例化時添加context={’request’: request} ''' ser = BookDetailSerializer( instance=obj,many=False, context={’request’: request} ) ''' 如果出現(xiàn)關(guān)聯(lián)關(guān)系時,獲取model對像的某一個字段 ''' bookname = serializers.CharField(source=’book.bookname’) ''' 第二種繼承自:serializers.ModelSerializer ''' class ChpaterDetailSerializer(serializers.ModelSerializer): #使用ModelSerializer進(jìn)行章節(jié)詳情的序列化 bookname = serializers.CharField(source=’book.bookname’) class Meta: model = models.ChpaterInfo #fields = '__all__' fields = [’id’,’bookname’] ''' DRF (序列化時)自定義方法獲取數(shù)據(jù) ''' book = serializers.SerializerMethodField() ''' ''' def get_book(self,row): ''' row - > UserInfo''' print(’======’,row.book.all()) ser = UsersBooksSerializer( instance=row.book.all(), many=True ) return ser.data ''' DRF depth深度的使用 # depth會根據(jù)關(guān)聯(lián)的數(shù)據(jù)不停的深入將數(shù)據(jù)獲取出來(最多不超過10層) # depth = 1 ''' class UsersSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = '__all__' #depth會根據(jù)關(guān)聯(lián)的數(shù)據(jù)不停的深入將數(shù)據(jù)獲取出來(最多不超過10層) depth = 1 ''' DRF序列化的驗證功能 ''' class UsersSerializer(serializers.ModelSerializer): #自定義驗證錯誤的信息 username = serializers.CharField(error_messages={’required’:’用戶名不能為空’}) class Meta: model = models.UserInfo fields = '__all__' ''' ''' class UsersView(APIView): def post(self,request,*args,**kwargs): '''DRF 序列化自帶驗證功能''' data = request.data #print(data) ser = UsersSerializer(data=data) if ser.is_valid(): # ser.is_valid()y驗證數(shù)據(jù)的有效性print(’驗證后的數(shù)據(jù)’,ser.validated_data)#驗證后的數(shù)據(jù)正確后,保存數(shù)據(jù)至數(shù)據(jù)庫ser.save() else:#上傳數(shù)據(jù)不符合規(guī)范時ser.errors,返回錯誤詳細(xì)print(ser.errors) return Response(data) ''' 自定義字段驗證規(guī)則 ''' class UsersInfoSerializer(serializers.ModelSerializer): username = serializers.CharField(error_messages={’required’:’用戶名不能為空’}) class Meta:model = models.UserInfofields = '__all__' # 用戶名中必須包含老王兩個字,不包含則認(rèn)為名字無效 def validate_username(self,validated_value):print(validated_value)from rest_framework.exceptions import ValidationErrorif ’老王’ not in validated_value:#驗證不通過,拋出異常 raise ValidationError(’用戶名不合法’)#驗證通過,返回數(shù)據(jù)return validated_value '''
以上就是python drf各類組件的用法和作用的詳細(xì)內(nèi)容,更多關(guān)于python drf組件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
