1. 程式人生 > 實用技巧 >SQL語法分類

SQL語法分類

1、路由

​ drf中可以通過繼承檢視基類ModelViewSet的路由寫法,可以自動生成路由,從而優化繼承檢視類ViewSetMixin的路由

​ drf中不同路由的使用:

1.1、urls.py中的基礎路由

url('book/',views.Bookview.as_view())
url('book/(?P<pk>\d+)',views.Bookdataview.as_view())

1.2、繼承ViewSetMixin檢視類後的路由

url('book'/,views.Bookview.as_view(action={'get':'list','post':'create'})),
url('book/',views.Bookdataview.as_view(action={'get':'retrieve','put':'update','delete':'destroy'}))

1.3、繼承ModelViewSet檢視類,優化之後的實現自動路由

#1.匯入routers模組
from rest_framework.viewsets routers
#2.例項化得到物件,二選一,DefaultRouter生成的路由比較多,不推薦使用
route=router.DefaultRouter()
route=router.SimpleRouter()
#3.設定路由的url路徑,以及路徑觸發檢視層的物件
router.register('books',view.Bookviewset)
#4.將自動生成的url加入到原路由中
urlpatterns+=router.urls

2、action的使用

​ action是將已經繼承了ModelViewSet檢視類的自定義函式也新增到路由中,

​ 將裝飾器放置在被裝飾函式的上方,methods:請求方式,detail:是否帶pk

class Bookviewset(ModelViewSet):
	queryset = Book.object.all()	
	serializer_class = BookSerializer    #繼承ModelVIESet,裡面封裝了各種的請求方式,通過url進行關聯,內建了框架,需要設定資料庫中的資料,以及設定序列化器
	@action(methods=['GET','POST'],detail=True)#第一個為請求方式,可以在列表內放置多個,第二個為是否需要<pk>值
	def get_1(self,request,pk):   #訪問時路徑為url('book/(?P<pk>[^/.]+)/get_1$'),即必須要提交pk以及get_1
		book=self.get_queryset()[:2]		#自定義,取前兩個值
		ser = self.get_serializer(book,many=True)
		return Response(ser.data)
	

3、認證

3.1、認證的寫法

​ 先寫一個類,繼承BaseAuthentication,類裡面重寫函式authenticate,認證的邏輯寫在裡面,

​ 認證成功,返回兩個值,其中給一個值賦給Request的物件user,

​ 認證失敗,則丟擲異常:APIEception或者AuthenticationFailed

3.2、認證原始碼分析

#1 APIVIew----》dispatch方法---》self.initial(request, *args, **kwargs)---->有認證,許可權,頻率
#2 只讀認證原始碼: self.perform_authentication(request)
#3 self.perform_authentication(request)就一句話:request.user,需要去drf的Request物件中找user屬性(方法) 
#4 Request類中的user方法,剛開始來,沒有_user,走 self._authenticate()

#5 核心,就是Request類的 _authenticate(self):
    def _authenticate(self):
        # 遍歷拿到一個個認證器,進行認證
        # self.authenticators配置的一堆認證類產生的認證類物件組成的 list
        #self.authenticators 你在檢視類中配置的一個個的認證類:authentication_classes=[認證類1,認證類2],物件的列表
        for authenticator in self.authenticators:
            try:
                # 認證器(物件)呼叫認證方法authenticate(認證類物件self, request請求物件)
                # 返回值:登陸的使用者與認證的資訊組成的 tuple
                # 該方法被try包裹,代表該方法會拋異常,拋異常就代表認證失敗
                user_auth_tuple = authenticator.authenticate(self) #注意這self是request物件
            except exceptions.APIException:
                self._not_authenticated()
                raise

            # 返回值的處理
            if user_auth_tuple is not None:
                self._authenticator = authenticator
                # 如何有返回值,就將 登陸使用者 與 登陸認證 分別儲存到 request.user、request.auth
                self.user, self.auth = user_auth_tuple
                return
        # 如果返回值user_auth_tuple為空,代表認證通過,但是沒有 登陸使用者 與 登陸認證資訊,代表遊客
        self._not_authenticated()

3.3、認證元件的使用

​ 先新建一個檔案:app_auth.py,裡面建立一個認證類,繼承BaseAuthentication,

​ 建立函式authenticate,認證就是確定token是否存在,在檢視層views中建立了登入函式 ,裡面有產生一個隨機的token,從前端取到token的值判斷它是否存在,再判斷它是否存在資料庫內,如果存在的話返回給使用者資訊,以及token,用來放行該使用者

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01.models import UserToken
class MyAuthentication(BaseAuthentication):
	def authenticate(self,request):
		token=request.GET.get('token')
		if token:
			user_token = UserToken.objects.filter(token=token).first()
			if user_token:
				return user_token.user,token
			else:
				raise AuthenticationFailed('認證失敗')
		else:
			raise AuthenticationFailed('請求地址中需要攜帶token')

4、認證功能全域性和區域性的使用

4.1、全域性使用

​ 在setting中配置

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.app_auth.MyAuthentication",]
}

4.2、區域性使用

​ 在檢視類中寫

authentication_classes=[MyAuthentication]

4.3、區域性禁用

​ 在檢視類前新增空,優先查詢自身的屬性

authentication_classes=[]