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 ...
随机推荐
- redis相对关系型数据库的优势
它是键值数据库(非关系),数据查询比关系型数据库快. ps:redis是树状结构,查询快 redis是基于内存的一个数据库,I/O的效率影响较小. ps: 备份数据同步是才进行I/O操作.这个数据同步 ...
- django-admin添加权限
后台manage页面: 可以通过用户直接添加权限,如果需要添加多个权限,则可以通过组,先将多个权限添加个组(总经理,秘书),在个用户添加这个组(总经理,秘书). 代码实现: 实际就是添加多对多的关系 ...
- urllib2异常处理(七)
urllib2 的异常错误处理 在我们用urlopen或opener.open方法发出一个请求时,如果urlopen或opener.open不能处理这个response,就产生错误. 这里主要说的是U ...
- 使用Fiddler对IPhone手机的应用数据进行抓包分析
原文出自: http://www.cr173.com/html/20064_1.html Fiddler能捕获ISO设备发出的请求,比如IPhone, IPad, MacBook. 等等苹果的设备. ...
- ADO.Net学习总结
一.讲述6个ADO.NET中的常用对象: Connection对象Command对象DataReader对象DataAdapter对象DataSet对象DataTable对象DataRow对象Data ...
- forbidden Derby database starting with weblogic instance
Now doing a new project which choose the newest weblogic 12.1.2.0.0 as web container.But found the ...
- fekit 搭建
sudo apt-get install npmsudo apt-get install nodejs 保证npm配置正确 sudo npm config set registry http://r ...
- javascript数组操作(创建、元素删除、数组的拷贝)
这篇文章主要介绍了javascript数组操作,包括创建.元素的访问.元素删除.数组的拷贝等操作,还有其它示例,需要的朋友可以参考下 1.数组的创建 复制代码 代码如下: var arrayObj = ...
- centos7虚拟机安装elasticsearch6.4.x-遇到的坑
OS:Centos7x虚拟机 1H2Gjdk:1.8elasticsearch:5.6.0 1.下载“elasticsearch-5.6.0.tar.gz”解压到/usr/local/elastics ...
- 裸函数naked解析
先分享一个案例: #include <stdio.h> __declspec(naked) void Test() { int x; x = ; __asm ret; } int main ...