我有一個小函式,它只是希望從我的 DRF API 端點獲得回應。
我的 DRF 設定如下所示:
"DEFAULT_AUTHENTICATION_CLASSES": [
# Enabling this it will require Django Session (Including CSRF)
"rest_framework.authentication.SessionAuthentication"
],
"DEFAULT_PERMISSION_CLASSES": [
# Globally only allow IsAuthenticated users access to API Endpoints
"rest_framework.permissions.IsAuthenticated"
],
我正在使用它來嘗試到達終點:
def get_car_details(car_id):
headers = {"X-Requested-With": "XMLHttpRequest"}
api_app = "http://localhost:8000/"
api_model = "cars/"
response = requests.get(api_app api_model str(car_id), headers=headers)
json_response = response.json()
return json_response
我不斷得到 'detail': 'Authentication credentials were not provided'
我是否需要生成 CSRF 令牌并將其包含在 GET 請求中?只有當用戶進入需要他們登錄的視圖時才會出現這種情況。有沒有辦法將該登錄用戶傳遞給端點?
uj5u.com熱心網友回復:
當您從該get_car_details函式發出請求時,您需要確保該請求已通過身份驗證。這看起來不像 CSRF 問題。
當使用基于會話的身份驗證時,會話 cookie 會在登錄后傳回。因此,在您呼叫之前,您get_car_details需要先發出登錄請求,保持該會話,并在呼叫 API 時使用該會話。
Requests 有一個會話類requests.Session(),您可以將其用于此目的。詳情請見:https : //docs.python-requests.org/en/latest/user/advanced/
許多人發現基于令牌的身份驗證更容易,部分會話 cookie 不需要維護。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/372315.html
標籤:Python 姜戈 Django 休息框架 蟒蛇请求 django-rest-framework-permissions
