django使用REST-framework 使用重寫類視圖所遇問題記錄

1.禁止某個類視圖post的csrf驗證:

from rest_framework.authentication import SessionAuthentication as OriginalSessionAuthentication

class PassCSRFAuthentication(OriginalSessionAuthentication):
    def enforce_csrf(self, request):
        return
        
class TestView(APIView):  
    #通過設置類權限成員,使得該post方法無需csrf驗證
    authentication_classes = (PassCSRFAuthentication,)
    def post(self, request, format=None):
        return Response('{}')
    

2.無法使用裝飾器@login_required來判斷請求是否登錄,並跳轉:

自定義裝飾器解決此問題:

from functools import wraps

#自定義登錄判斷裝飾器
def check_login(func):
    @wraps(func)
    def inner(self, request):
        if request.user.is_authenticated:
            print('user has logined')
            return func(self, request)
        else:
            return redirect('/login/')#未登錄跳轉的路由
    return inner  


#裝飾器使用

class TestView(APIView):  
    #通過設置類權限成員,使得該post方法無需csrf驗證
    authentication_classes = (PassCSRFAuthentication,)
    @check_login
    def post(self, request, format=None):
        return Response('{}')

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章