Python 使用 Django Rest Framework 的请求 - 'detail':'Authentication credentials were not provided'
Python Requests with Django Rest Framework - 'detail': 'Authentication credentials were not provided'
我有一个小函数,它只是为了从我的 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 请求中?唯一一次发生这种情况是当用户转到需要登录的视图时。有没有办法将该登录用户传递到端点??
当您从 get_car_details
函数发出请求时,您需要确保该请求已通过身份验证。这看起来不像是 CSRF 问题。
当使用基于会话的身份验证时,会话 cookie 会在登录后传回。因此,在您调用 get_car_details
之前,您需要先发出登录请求,保留该会话,并在调用时使用该会话API.
Requests 有一个会话 class requests.Session()
,您可以将其用于此目的。详情在这里:https://docs.python-requests.org/en/latest/user/advanced/
许多人发现基于令牌的身份验证更容易,部分原因是不需要维护会话 cookie。
我有一个小函数,它只是为了从我的 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 请求中?唯一一次发生这种情况是当用户转到需要登录的视图时。有没有办法将该登录用户传递到端点??
当您从 get_car_details
函数发出请求时,您需要确保该请求已通过身份验证。这看起来不像是 CSRF 问题。
当使用基于会话的身份验证时,会话 cookie 会在登录后传回。因此,在您调用 get_car_details
之前,您需要先发出登录请求,保留该会话,并在调用时使用该会话API.
Requests 有一个会话 class requests.Session()
,您可以将其用于此目的。详情在这里:https://docs.python-requests.org/en/latest/user/advanced/
许多人发现基于令牌的身份验证更容易,部分原因是不需要维护会话 cookie。