我有一个Django应用程序,我使用DRF为我的API与会话和令牌认证 . 我在已安装的应用程序中有rest_framework和rest_framework.authtoken . 我已经迁移了我的数据库,可以为Django Admin中的用户创建令牌 . 我知道这一切都有效,因为我正在访问rest_framework.auth_token的obtain_auth_token视图,用于在POST请求中提交用户数据时返回令牌,并返回一个 . 当我尝试向我的应用程序中对其视图集具有TokenAuthentication的视图函数发出GET请求时,它会一直返回 .
{"detail":"Authentication credentials were not provided."}
Settings File
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# My Apps
'rest_framework',
'rest_auth',
'rest_framework.authtoken',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
}
URLS
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken import views
from api.views.some_model import MyViewSet
urlpatterns = [
path('', include(router.urls)),
path('rest-auth/', include('rest_auth.urls')),
path('api-token-auth/', views.obtain_auth_token)
]
Viewset
from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from some_app.models import SomeModel
from api.serializers.exams import SomeModelSerializer
class ExamViewSet(ModelViewSet):
permission_classes = (IsAuthenticated,)
authentication_classes = (TokenAuthentication, SessionAuthentication)
queryset = SomeModel.objects.all()
serializer_class = SomeModelSerializer
Python Script to Get Response
import requests
import json
data = {
"username": "myemail@gmail.com",
"password": "password124"
}
url = "http://localhost:8002/api/v1/api-token-auth/"
response = requests.post(url, data=data)
token = json.loads(response.text).get('token')
if token:
token = f"Token {token}"
headers = {"Authentication": token}
response = requests.get("http://localhost:8002/api/v1/model/", headers=headers)
print(response.text)
else:
print('No Key')
1 回答
Headers 名称应为
Authorization
而不是Authentication
: