django drf Token验证

谁说胖子不能爱 提交于 2020-03-08 18:26:20

https://www.django-rest-framework.org/api-guide/authentication/#basicauthentication

1.INSTALLED_APPS

INSTALLED_APPS = (
    ...
    'rest_framework.authtoken'
)

2.REST_FRAMEWORK配置

REST_FRAMEWORK = {
    # 'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination',
    # 'PAGE_SIZE':2,
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication'
    )
}

3.migrate生成表

4.创建一个token

import sys
import os

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MxShop.settings')

import django
django.setup()

from rest_framework.authtoken.models import Token

from django.contrib.auth import authenticate
user = authenticate(username='admin',password='admin')
token = Token.objects.create(user=user)
print(token.key)

5.生成oken

6.验证token

可通过request.user查看

 

PS:Settings.py中的TokenAuthorazition是全局的,我们也可以取消全局,只在徐娅授权的View中添加authorazition

1.取消settings中配置

REST_FRAMEWORK = {
    # 'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination',
    # 'PAGE_SIZE':2,
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.TokenAuthentication'
    )
}

2.在View中配置

class GoodsList(mixins.ListModelMixin,mixins.CreateModelMixin, viewsets.GenericViewSet):
    class GoodsPagination(PageNumberPagination):
        page_size = 2
        page_size_query_param = 'pageSize'
        page_query_param = 'p'
        max_page_size = 100

    queryset = Goods.objects.all()  # 不能切片后再过滤,例如:Goods.objects.all()[:10]
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination
    authentication_classes = (TokenAuthentication,)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    search_fields = ('=name',)  # 文档:https://www.django-rest-framework.org/api-guide/filtering/#searchfilter
    ordering_fields = ('name',)
    # filter_fields = ('name',) #逗号必加,缺点无法模糊查询
    filterset_class = GoodsFilter

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!