[英]Python Requests with Django Rest Framework - 'detail': 'Authentication credentials were not provided'
I've got a tiny function that just looks to get a response from my DRF API Endpoint.我有一个很小的 function,它只是看起来从我的 DRF API 端点得到响应。
My DRF settings look like this:我的 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"
],
I'm using this to try and hit the endpoint:我正在使用它来尝试达到终点:
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
I keep getting 'detail': 'Authentication credentials were not provided'
我不断收到
'detail': 'Authentication credentials were not provided'
Do I need to generate a CSRF token and include it in a GET request?我是否需要生成 CSRF 令牌并将其包含在 GET 请求中? The only time this gets hit is when a user goes to a view that requires they are logged in. Is there a way to pass that logged-in user to the endpoint??
唯一一次被击中是当用户进入需要他们登录的视图时。有没有办法将该登录用户传递到端点?
When you make your request from the get_car_details
function you need to be sure that the request is authenticated.当您从
get_car_details
function 发出请求时,您需要确保请求已通过身份验证。 This does not look like a CSRF issue.这看起来不像是 CSRF 问题。
When using session based authentication a session cookie is passed back after logging in. So before you call get_car_details
you would need to first make a request to login, keep that session, and use that session when calling the API. When using session based authentication a session cookie is passed back after logging in. So before you call
get_car_details
you would need to first make a request to login, keep that session, and use that session when calling the API.
Requests has a session class requests.Session()
that you can use for this purpose. Requests 有一个 session class
requests.Session()
可用于此目的。 Details here: https://docs.python-requests.org/en/latest/user/advanced/详细信息: https://docs.python-requests.org/en/latest/user/advanced/
Many people find token based authentication easier partly a session cookie does not need to be maintained.许多人发现基于令牌的身份验证更容易,部分原因是不需要维护 session cookie。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.