建议使用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的更多相关文章

  1. DRF JWT的用法 & Django的自定义认证类 & DRF 缓存

    JWT 相关信息可参考: https://www.jianshu.com/p/576dbf44b2ae DRF JWT 的使用方法: 1. 安装 DRF JWT # pip install djang ...

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

    登录注册是几乎所有网站都需要去做的接口,而说到登录,自然也就涉及到验证以及用户登录状态保存,最近用DRF在做的一个关于网上商城的项目中,引入了一个拓展DRF JWT,专门用于做验证和用户状态保存.这个 ...

  3. DRF JWT认证(一)

    为什么要使用JWT认证?构成和原理又是什么?怎么还有Base64的事?我都写了

  4. DRF JWT认证(二)

    快速上手JWT签发token和认证,有这一篇就够了,DRF自带的和自定义的都帮你总结好了,拿去用~

  5. django restframework jwt

    既然要来学习jwt(json web token),那么我们肯定是先要了解jwt的优势以及应用场景--跨域认证. $ pip install djangorestframework-jwt 传统coo ...

  6. 解决Django + DRF:403 FORBIDDEN:CSRF令牌丢失或不正确,{"detail":"CSRF Failed: CSRF cookie not set."}

    我有一个Android客户端应用程序尝试使用Django + DRF后端进行身份验证.但是,当我尝试登录时,我收到以下响应: 403: CSRF Failed: CSRF token missing ...

  7. django DRF理解

    django restframework(DRF) 最近的开发过程当中,发现restframework的功能很强大,所以尝试解读了一下源码,写篇博客分享给大家,有错误的地方还请各位多多指出 视图部分 ...

  8. Django DRF 分页

    Django DRF 分页 分页在DRF当中可以一共有三种,可以通过setttings设置,也可也通过自定义设置 PageNumberPagination 使用URL http://127.0.0.1 ...

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

    问题重现 当查看DRF 文档时发现DRF内置的token是存储在数据库里,这和我在网上搜索资料时认识的token-based authentication有出入. from rest_framewor ...

随机推荐

  1. maven常用命令集合

    作者:ydlmlh 原文:http://ydlmlh.iteye.com/blog/2158973 抽了点时间,整理了一些maven常用命令参数,以便参考:参考了maven官网和网上其他一些maven ...

  2. Linux Tomcat8 访问管理页面 403 Access Denied

    http://blog.csdn.net/u012167045/article/details/61624226 1:修改conf/tomcat-users.xml配置文件 2:vi /usr/loc ...

  3. 【Directshow】IFilterGraph::AddFilter方法参数问题<转>

    看dx里dshow的例子和别人的程序,用IFilterGraph::AddFilter()这个API添加filter到Graph的时候,第二个参数是一个设备友好名称: 我看有的填的是通过IProper ...

  4. 迷你MVVM框架 avalonjs 0.91发布

    本版本修了一些BUG与不合理的地方,感谢感谢ztz, 民工精髓, 姚立, qiangtou等人指正. 处理AMD加载 旧式IE下移除script节点内存泄漏的问题 fix firefox 全系列vis ...

  5. LDA处理文档主题分布代码

    [python] LDA处理文档主题分布代码入门笔记  http://blog.csdn.net/eastmount/article/details/50824215

  6. Liunx 解压篇

    解压完 却不知道到哪里去了这时

  7. Git学习笔记——从一台电脑上传文件到Github上

    目标:从一台电脑上传文件到Github上 前提: 1.这里假定已在Github上创建了仓库,建立了仓库 2.已在这台电脑上安装了Git客户端 实验环境: 1.Windows 10 64位,已安装了Gi ...

  8. Sprint boot notes

    1. spring.io 官网 2. http://javainuse.com/spring/sprboot spring boot学习资源 3. spring boot websocketss视频  ...

  9. macOS 安装设置 Tunnelblick (openvpn 替代)

    1、下载.安装 2、准备好 openvpn 相关的文件,全部放在一个目录中.主要有以下几个: ca.crt client.crt client.key client.ovpn 3、打开 client. ...

  10. [Jmeter]让报告在邮件中以链接进行显示,通过IIS