zoukankan      html  css  js  c++  java
  • 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(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',
    }
  • 相关阅读:
    Tomcat部署web项目,虚拟目录,上下文(Context),WEB-INF,web.xml,servlet,404
    Android异常:唤醒锁未授权。(Caused by: java.lang.SecurityException: Neither user 10044 nor current process has android.permission.WAKE_LOCK.)
    .hiverc
    Hive安装
    搭建Kafka开发环境
    java实现Kafka的消费者示例
    java实现Kafka生产者示例
    Kafka集群部署
    kafka介绍
    Pig UDF 用户自定义函数
  • 原文地址:https://www.cnblogs.com/chenyishi/p/10659065.html
Copyright © 2011-2022 走看看