建议使用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. Python2.X如何将Unicode中文字符串转换成 string字符串

    Python2.X如何将Unicode中文字符串转换成 string字符串   普通字符串可以用多种方式编码成Unicode字符串,具体要看你究竟选择了哪种编码:unicodestring = u&q ...

  2. 带参数setTimeout

    /*         功能:修改 window.setTimeout,使之可以传递参数和对象参数         使用方法: window.setTimeout(回调函数,时间,参数1,,参数n)   ...

  3. Linux 移除python Error: Trying to remove “yum”, which is protected

    >yum intall python >yum -y remove python 出现Error: Trying to remove "yum", which is p ...

  4. 10 MySQL--权限管理

    权限管理 1.创建账号 # 本地账号 create user '; # mysql -uegon1 -p123 # 远程帐号 create user '; # mysql -uegon2 -p123 ...

  5. AABB和平面的相交性检测

    [AABB和平面的相交性检测]

  6. grep 过滤.svn文件

    [grep 过滤.svn文件] 问题: 在repository搜索代码时,常常会搜索到.svn的代码,如果不想搜索.svn目录下的相关代码怎么办?    1.使用管道进行双层“过滤”,其中第二次gre ...

  7. 使用Git将码云上的代码Clone至本地

    1. 安装Git https://git-scm.com/book/zh/v2/%E8%B5%B7%E6%AD%A5-%E5%AE%89%E8%A3%85-Git Git的网站上有详细的分各种系统的安 ...

  8. Django基础学习四_数据库的增删改查

    今天主要学习两个东西 1.如何对数据库做增删改查 2.如果将数据库中的数据用html的方式返回到前台 一.对数据库中增删改查操作 1.首先需要先见表,见表的方法我们在“http://www.cnblo ...

  9. WebSocket 资料搜索

    http://jwebsocket.org/ http://zh.wikipedia.org/wiki/WebSocket http://www.infoq.com/cn/news/2013/07/e ...

  10. Linux addr2line命令

    一.简介 Addr2line (它是标准的 GNU Binutils 中的一部分)是一个可以将指令的地址和可执行映像转换成文件名.函数名和源代码行数的工具.这种功能对于将跟踪地址转换成更有意义的内容来 ...