2016-12-29 95 views
0

我想豁免處理REST API POST請求的視圖的CSRF驗證,但我仍然收到CSRF verification failed錯誤。@csrf_exempt不工作休息api

我試過this question給出的解決方案,它沒有工作。

我的代碼:

sendmoney REST API視圖:

@api_view(["POST"])                   
@authentication_classes([TokenAuthentication,])            
@permission_classes([IsAuthenticated, ])              
@csrf_exempt                     
def send_money(request):                  
    if request.method == "POST":                
     data = JSONParser().parse(request)             
     success = send_money_api(request, data)            
     if success["status"]:                 
      return Response(status=status.HTTP_202_ACCEPTED)         
     else:                     
      return Response({"error": success["errors"]}, status=status.HTTP_400_BAD_REQUEST) 

send_money_api方法:

def send_money_api(request, data): 
    if data["amount"] and data["to"]: 
     wallet = Wallet.objects.get(username=request.user.username) 
     users = User.objects.all() 
     users_names = [] 
     for user in users: 
      users_names.append(user) 
     if int(data["amount"]) > int(wallet.amount): 
      return {"status": False, "errors": "Withdraw amount greater than balance"} 
     elif data["to"] == "ravinkohli" and data["to"] == request.user.username and data["to"] not in users_names: 
      return {"status": False, "errors": "Invalid recipient"} 
     else: 
      wallet.subtract_money(data["amount"]) 
      wallet.save() 
      transaction = Transaction(from_name=request.user.username, wallet_id=wallet, date=datetime.datetime.now(), 
             to=data['to'], amount=data["amount"]) 
      transaction.save() 
      return {"status": True} 
    else: 
     return {"status": False, "errors": "Missing content"} 

錯誤

Forbidden (403) 
CSRF verification failed. Request aborted. 
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. 
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. 
+1

爲什麼不在'send_money_api'上的'@ csrf_exempt'呢? – Jedi

+0

我雖然因爲它不是一個視圖,但感謝它的工作 –

+1

引用文檔:*視圖函數,或簡稱爲視圖,只是一個Python函數,它接受Web請求並返回響應。 – Jedi

回答

1

對於send_money_api(...)視圖,CSRF驗證失敗。只需在第二個視圖上方添加@csrf_exempt修飾器。