DRF - 匿名用户设置
views.py:
from django.http import JsonResponse from rest_framework.views import APIView ORDER_DICT = { 1: { "commodity": "Phone", "price": 3600, "date": "2021-01-03", }, 2: { "commodity": "Computer", "price": 6700, "date": "2021-01-05", }, } class OrderView(APIView): """ 查看订单 """ # 不使用认证类 authentication_classes = [] def get(self, request, *args, **kwargs): print(request.user) print(request.auth) response = {"code": 1000, "msg": None, "data": None} try: response["data"] = ORDER_DICT except Exception as e: pass return JsonResponse(response)
运行结果:
在 settings.py 中进行匿名用户的设置
REST_FRAMEWORK = { # 设置 request.user "UNAUTHENTICATED_USER": lambda: "匿名用户", # 设置 request.auth "UNAUTHENTICATED_TOKEN": lambda: "匿名认证", }
运行结果:
一般将这两个配置为 None
REST_FRAMEWORK = { # 设置 request.user "UNAUTHENTICATED_USER": None, # 设置 request.auth "UNAUTHENTICATED_TOKEN": None, }