django drf JWT

Posted chenyishi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django drf JWT相关的知识,希望对你有一定的参考价值。

建议使用djangorestframework-jwt或者djangorestframework_simplejwt,文档为

https://github.com/GetBlimp/django-rest-framework-jwt

https://github.com/davesque/django-rest-framework-simplejwt

这里以djangorestframework-jwt举例

1.安装

pip install djangorestframework-jwt

2.配置settings

REST_FRAMEWORK = {
    # ‘DEFAULT_PAGINATION_CLASS‘:‘rest_framework.pagination.PageNumberPagination‘,
    # ‘PAGE_SIZE‘:2,
    # ‘DEFAULT_PERMISSION_CLASSES‘: (
    #     ‘rest_framework.permissions.IsAuthenticated‘,
    # ),
    DEFAULT_FILTER_BACKENDS: (django_filters.rest_framework.DjangoFilterBackend,),
    DEFAULT_AUTHENTICATION_CLASSES: (
        rest_framework_jwt.authentication.JSONWebTokenAuthentication,
        rest_framework.authentication.BasicAuthentication,
        rest_framework.authentication.SessionAuthentication,
        # ‘rest_framework.authentication.TokenAuthentication‘

        # ‘rest_framework_simplejwt.authentication.JWTAuthentication‘,
    )
}

3.url配置

from django.urls import path, include
import users.urls as userurl
from django.conf.urls import url
from django.views.static import serve
from MxShop.settings import MEDIA_ROOT
from goods.views_base import GoodsListView
from rest_framework.documentation import include_docs_urls
from rest_framework.routers import DefaultRouter
from goods.views import GoodsList,GoodsCategotyList #,CategoryList


router = DefaultRouter()
router.register(goods,GoodsList,base_name=a)
router.register(categorys,GoodsCategotyList)

# goods_list = GoodsListSet.as_view({
#     ‘get‘:‘list‘
# })

from rest_framework.authtoken import views
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
    # path(‘admin/‘, admin.site.urls),
    url(ruseradmin/, include(userurl)),
    url(r^media/(?P<path>.*)$, serve, {"document_root": MEDIA_ROOT}),
    url(r^docs/,include_docs_urls(title=drf文档)),
    url(r^api-auth/, include(rest_framework.urls,namespace=rest_framework)),
    # url(r‘^goods/$‘, goods_list, name="goods-list"),
    url(r^,include(router.urls)),
    url(r^api-token-auth/, obtain_jwt_token),
    # url(r‘^api-token-auth/‘, views.obtain_auth_token),
    url(r^api/token/$, TokenObtainPairView.as_view(), name=token_obtain_pair),
    url(r^api/token/refresh/$, TokenRefreshView.as_view(), name=token_refresh),
    # url(r‘^category/$‘,CategoryList.as_view())
]

4.viewdemo

class GoodsFilter(django_filters.rest_framework.FilterSet):
    category_id = django_filters.rest_framework.NumberFilter(method=filter_catetory_id)

    def filter_catetory_id(self, queryset, name, value):
        return queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) | Q(
            category__parent_category__parent_category_id=value))

    class Meta:
        model = Goods
        fields = [category_id]

from rest_framework.authentication import TokenAuthentication

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

5.test

技术图片

 

技术图片

 

 

以上是关于django drf JWT的主要内容,如果未能解决你的问题,请参考以下文章

Django - DRF自带的token认证和JWT区别

DRF:如何将 django-rest-framework-jwt 集成到 Djoser

自定义路由组件,Django的admin后台管理,DRF的三大认证,jwt认证

django drf 自定义jwt用户验证逻辑

Django Rest Framework(DRF) Json Web Token(JWT) 身份验证和登录过程

django drf框架中的user验证以及JWT拓展的介绍