django drf JWT

2023-05-30,,

建议使用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(r'useradmin/', 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

 PS:可以在settings中配置JWT,常用的有过期时间和前缀

import datetime
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=300),
'JWT_AUTH_HEADER_PREFIX': 'Token',
}

django drf JWT的相关教程结束。

《django drf JWT.doc》

下载本文的Word格式文档,以方便收藏与打印。