django-reset-framework
-
安裝
pip install djangorestframework # 依賴包 pip install markdown django-filter coreapi django-guardian
Add
'rest_framework'
to yourINSTALLED_APPS
setting.-
在 urls 配置以下 url
path('docs', include_docs_urls(title='')), # title任意 path('api-auth', include('rest_framework.urls')),
django-reset-framework 的作用主要是序列化 model乔外,返回給網(wǎng)頁 json 格式的數(shù)據(jù),其使用有點類似 django 的 Form
-
django 的 forms 和 drf 的 serializers 比較
from rest_framework import serializers from django import forms forms.Form 對應(yīng) serializers.Serializer froms.ModelForm 對應(yīng) serializers.ModelSerializer class ModelNameSeriazer(serializers.ModelSerializer): class Meta: model = ModelName fields = '__all__' # 表示序列化該model的所有屬性
-
drf的view
最基類 View 為
from rest_framework.views import APIView
返回值為from rest_framework.response import Response
。 -
View 高級用法
from rest_framework import mixins, generics # 編寫 View 時,集成上面兩個文件中的類,重寫相關(guān)方法 # 例子 class GoodsListView(generics.ListAPIView): """ 商品列表頁 """ serializer_class = GoodsSerializer queryset = Goods.objects.all()[:10] lookup_field = 'goods_id' # 配置獲取詳情時眷柔,搜索字段名稱
-
drf 實現(xiàn)分頁
- 在setting中設(shè)置
# 在setting中作如下設(shè)置 REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, # 每頁顯示數(shù)量 }
-
繼承PageNumberPagination類
class MyPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 page_query_param = 'p'
在 View 里設(shè)置 pagination_class = MyPagination,ok!
drf 里 View 的層級關(guān)系
-
drf 過濾器
To use
DjangoFilterBackend
, first installdjango-filter
. Then adddjango_filters
to Django'sINSTALLED_APPS
-
在 view 里配置過濾字段
from django_filters.rest_framework import DjangoFilterBackend class UserListView(generics.ListAPIView): ... filter_backends = [DjangoFilterBackend] filter_fields = ['name', 'price'] # 精確搜索字段洗做,必須完全一致 filterset_fields = ['', '' ] # 同上,精確搜索彰居,必須完全一致诚纸;外鍵搜索時,使用雙下劃線指向外鍵的名字 # 配置搜索字段陈惰,使用from rest_framework import filters filter_backends = [filters.SearchFilter,] search_fields = ('name',) # 排序過濾字段畦徘,使用from rest_framework import filters filter_backends = [filters.OrderingFilter,] ordering_fields = ['shop_price', 'name']
-
編寫對于的 Filter 類實現(xiàn)過濾
from django_filters import rest_framework as filters from .models import Goods class GoodsFilters(filters.FilterSet): # price_min = filters.NumberFilter(field_name='shop_price', lookup_expr='gte') # 大于等于 # price_max = filters.NumberFilter(field_name='shop_price', lookup_expr='lte') # 小于等于 # name = filters.CharFilter(field_name='name', lookup_expr='contains') # 模糊查詢,忽略大小寫設(shè)置為icontains class Meta: model = Goods fields = ['category__name'] # 按照范圍過濾 # fields = { # 'shop_price': ['lt', 'gt'], # } # 最后在需要的 View 添加屬性:filter_class = ModelFilterClassName
-
-
drf 登錄認證機制
1)install_apps 中添加
'rest_framework.authtoken'
2)url 中配置
from rest_framework.authtoken import views path('api-token-auth/', views.obtain_auth_token),
-
添加全局設(shè)置
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', # 以上是默認的 # 使用Token認證機制需要添加如下 'rest_framework.authentication.TokenAuthentication', ] }
-
在 view 中設(shè)置屬性抬闯,局部配置
from rest_framework.authentication import TokenAuthentication authentication_classes = (TokenAuthentication, )
以上兩種方式都可以配置 TokenAuth 認證
-
-
前后端分離時一般使用 JWT 用戶認證
1)
pip install djangorestframework-jwt
2)JWT 配置添加
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', # 添加如下配置 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), }
3)url 配置
from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ url(r'^api-token-auth/', obtain_jwt_token), ]
3)JWT 驗證機制井辆,最好在 ViewSet 中添加
authentication_classes = (JSONWebTokenAuthentication,)
,全局配置會導(dǎo)致不需要登錄的信息獲取失敗溶握。 -
Django 信號量
django 中有信號量機制杯缺,比如創(chuàng)建 user 時需要做一些其它邏輯,就可以使用信號量睡榆。
例子:
from django.db.models.signals import post_save from django.dispatch import receiver from .models import UserFav @receiver(post_save, sender=UserFav) def create_userfav(sender, instance=None, created=False, **kwargs): if created: goods = instance.goods goods.fav_num += 1 goods.save() # apps from django.apps import AppConfig class UserOperationConfig(AppConfig): name = 'user_operation' verbose_name = '用戶操作管理' # 使用信號量 def ready(self): import user_operation.signals
-
動態(tài)配置 ViewSet 中的權(quán)限認證和 serializer 類
# 動態(tài)配置serializer類 def get_serializer_class(self): if self.action == 'retrieve': return UserDetailSerializer elif self.action == 'create': return UserRegSerializer return UserDetailSerializer # 動態(tài)設(shè)置權(quán)限 def get_permissions(self): if self.action == 'retrieve': return [permissions.IsAuthenticated()] elif self.action == 'create': return [] return []
-
Serializer 嵌套 Serializer
源碼級別萍肆,序列化 Image 字段,它會判斷上下文是否有 request胀屿,有的話會加上域名塘揣。
如果調(diào)用的 Serializer 里需要序列化圖片字段,則需要添加 context 的 request 屬性碉纳,否則它不會自動添加域名勿负。
goods_json = GoodsSerializer(goods_ins, many=False, context={'request': self.context['request']}).data
-
drf 配置限速
setting 里配置:
REST_FRAMEWORK = { # 兩個限速類 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', # 用戶沒有登錄 'rest_framework.throttling.UserRateThrottle' # 用戶登錄 ], 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' } }
ViewSet 中添加屬性
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle throttle_classes = (UserRateThrottle, AnonRateThrottle)
?