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',
}
django drf JWT的更多相关文章
- DRF JWT的用法 & Django的自定义认证类 & DRF 缓存
JWT 相关信息可参考: https://www.jianshu.com/p/576dbf44b2ae DRF JWT 的使用方法: 1. 安装 DRF JWT # pip install djang ...
- django drf框架中的user验证以及JWT拓展的介绍
登录注册是几乎所有网站都需要去做的接口,而说到登录,自然也就涉及到验证以及用户登录状态保存,最近用DRF在做的一个关于网上商城的项目中,引入了一个拓展DRF JWT,专门用于做验证和用户状态保存.这个 ...
- DRF JWT认证(一)
为什么要使用JWT认证?构成和原理又是什么?怎么还有Base64的事?我都写了
- DRF JWT认证(二)
快速上手JWT签发token和认证,有这一篇就够了,DRF自带的和自定义的都帮你总结好了,拿去用~
- django restframework jwt
既然要来学习jwt(json web token),那么我们肯定是先要了解jwt的优势以及应用场景--跨域认证. $ pip install djangorestframework-jwt 传统coo ...
- 解决Django + DRF:403 FORBIDDEN:CSRF令牌丢失或不正确,{"detail":"CSRF Failed: CSRF cookie not set."}
我有一个Android客户端应用程序尝试使用Django + DRF后端进行身份验证.但是,当我尝试登录时,我收到以下响应: 403: CSRF Failed: CSRF token missing ...
- django DRF理解
django restframework(DRF) 最近的开发过程当中,发现restframework的功能很强大,所以尝试解读了一下源码,写篇博客分享给大家,有错误的地方还请各位多多指出 视图部分 ...
- Django DRF 分页
Django DRF 分页 分页在DRF当中可以一共有三种,可以通过setttings设置,也可也通过自定义设置 PageNumberPagination 使用URL http://127.0.0.1 ...
- Django - DRF自带的token认证和JWT区别
问题重现 当查看DRF 文档时发现DRF内置的token是存储在数据库里,这和我在网上搜索资料时认识的token-based authentication有出入. from rest_framewor ...
随机推荐
- selenium+python自动化81-html报告优化(饼图+失败重跑+兼容python2&3)
优化html报告 为了满足小伙伴的各种变态需求,为了装逼提升逼格,为了让报告更加高大上,测试报告做了以下优化: 测试报告中文显示,优化一些断言失败正文乱码问题 新增错误和失败截图,展示到html报告里 ...
- 关于微信小程序的一些看法和理解
最近做了几个小时的调研,微信小程序 微信小程序是可以理解成在微信中的APP,他的目标是APP的替代者,由于目前的APP主要区分安卓和IOS,或者其他平台, 那么微信小程序的平台在微信,在任何一个手机系 ...
- 778. Swim in Rising Water
▶ 给定方阵 grid,其元素的值为 D0n-1,代表网格中该点处的高度.现在网格中开始积水,时刻 t 的时候所有值不大于 t 的格点被水淹没,当两个相邻格点(上下左右四个方向)的值都不超过 t 的时 ...
- 常见反编译产生错误 k__BackingField 解决办法
常见反编译产生错误 k__BackingField 解决办法 无聊反编译小蚂蚁出现上千的错同样的错 private bool <EnableRuntimeHandler> ...
- How to Integrate JCaptcha in Spring Security
The repository for JCaptcha is this one: <repository> <id>sourceforge-releases</id> ...
- JAVA 非对称加密工具
import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.securi ...
- Redis 键空间通知
[Redis 键空间通知] 键空间通知使得客户端可以通过订阅频道或模式, 来接收那些以某种方式改动了 Redis 数据集的事件. 以下是一些键空间通知发送的事件的例子: 所有修改键的命令. 所有接收到 ...
- VMware Workstation 虚拟机的服务启动项
- [leetcode]301. Remove Invalid Parentheses 去除无效括号
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...
- [Training Video - 5] [Groovy Script Test Step - Collections, Exceptions] Array and ArrayList
Array: def x = new String[5] x[0] = "India" x[1] = "USA" x[2] = "Korea" ...