簡體   English   中英

向 APIException 添加自定義響應標頭

[英]Adding custom response Headers to APIException

我創建了一個參考http://django-rest-framework.org/api-guide/exceptions.html的自定義異常。

請知道我有自己的身份驗證后端。 因此我沒有使用 rest_framework 的身份驗證模塊。

對於身份驗證錯誤,我想將“WWW-Authenticate: Token”標頭添加到從異常發送的響應中。

任何想法都會非常有幫助。

更新:

謝謝@Pathétique,這就是我最終要做的。

- 有一個名為 BaseView 的基本視圖類。

- 覆蓋 handle_exception 方法以設置適當的標頭,在我的例子中是“WWW-Authenticate”。

這是代碼:

class BaseView(APIView):
  def handle_exception(self, exc):
     if isinstance(exc, MYEXCEPTION):
        self.headers['WWW-Authenticate'] = "Token"
        return Response({'detail': exc.detail,
                        status=exc.status_code, exception=True)

你的意見?

嘗試在您的休息框架視圖中覆蓋finalize_response

def finalize_response(self, request, *args, **kwargs):
    response = super(SomeAPIView, self).finalize_response(request, *args, **kwargs)
    response['WWW-Authenticate'] = 'Token'
    return response

編輯:

看到你的更新后,我認為你對handle_exception的覆蓋應該可以工作,我只會添加一個 else 語句來調用父方法來覆蓋其他異常。 我在覆蓋 dispatch 時注意到的一件事(這里可能不是問題)是為 self.headers 設置新的鍵/值會導致服務器錯誤,我沒有花時間去追蹤。 不管怎樣,看來你是在正確的軌道上。

在您的身份驗證類上使用authenticate_header方法。

此外,這將確保您的響應也具有正確的401 Unauthorized狀態代碼集,而不是403 Forbidden

請參閱此處: http : //django-rest-framework.org/api-guide/authentication.html#custom-authentication

您的解決方案非常正確,在我的情況下,我發現添加標頭然后在超級實例上調用該方法更合適,以保持默認行為:

class BaseView(APIView):
  def handle_exception(self, exc):
     if isinstance(exc, MYEXCEPTION):
        self.headers['WWW-Authenticate'] = "Token"
        return super().handle_exception(excepto)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM