这个标题说明了一切。我正试图用标记来验证身份。我正在从django数据库获取信息到我的应用程序。我已经成功地从rest_framework中检索了我的令牌,并将它添加到rest请求的头中。我在django中打印了这些标题,结果是
{
'Content-Length': '0',
'Content-Type': 'text/plain',
'User-Agent': 'Dart/2.5 (dart:io)',
'Accept-Encoding': 'gzip',
'Authorization': 'Token 10cf58e1402b8e48c1a455aaff7f7bcf53e24231',
'Host': '192.168.0.110:8000'
}但是,结果是带有登录表单的网页,而不是我请求的rest数据。我遗漏了什么?
settings.py
...
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
...views.py
...
@login_required
@csrf_exempt
def ui_list(request):
print(request.headers)
"""
List all code user_informations, or create a new user_information.
"""
if request.method == "GET":
users = UserInformation.objects.all()
serializer = UserInformationSerializer(users, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == "POST":
data = JSONParser().parse(request)
serializer = UserInformationSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
...发布于 2019-10-30 10:38:13
您的问题来自于装饰器@login_required的使用,它应该保护一个django视图。
Django视图和django_rest_framework 不使用相同的身份验证系统,因此需要以不同的方式实现。
手动认证
您可以删除@login_required并按以下方式实现view.py:
from rest_framework.authentication import TokenAuthentication
...
@csrf_exempt
def ui_list(request):
print(request.headers)
"""
List all code user_informations, or create a new user_information.
"""
if request.method == "GET":
user_auth_tuple = TokenAuthentication().authenticate(request)
if user_auth_tuple is None:
return HttpResponse(status=401)
else:
(user, token) = user_auth_tuple # here come your user object
users = UserInformation.objects.all()
serializer = UserInformationSerializer(users, many=True)
return JsonResponse(serializer.data, safe=False)
if request.method == "POST":
...
...但是手动执行这个过程确实是很费时的,不应该这样做,因为提供了很多选项来实现这种自动化。
基于类的视图
实际应该做的是将一个django rest框架APIView类匹配到您的模型,并使用权限系统生成一个适当的入口点。
REST框架提供了一个APIView类,它是Django的视图类的子类。 APIView类是与常规视图类不同的(),其方式如下:
https://stackoverflow.com/questions/58622836
复制相似问题