Django rest_framework 信号机制生成并使用token

1、在setting.py 中增加设置

'DEFAULT_AUTHENTICATION_CLASSES':[
        'rest_framework.authentication.BasicAuthentication',#基本的用户名密码验证
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',# token 认证
    ],
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'course.apps.CourseConfig',
    'rest_framework',
    'rest_framework.authtoken',#DRF 自带token认证
]

2、生成token 表

python manage.py makemigration
python manage.py migrate

3、写一个信号函数 使得创建用户时 自动创建token .在views.py中增加

from django.db.models.signals import post_save
from django.dispatch import receiver
#from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.authtoken.models import Token

#@receiver(post_save,sender = User)  Django 的信号机制
@receiver(post_save,sender = settings.AUTH_USER_MODEL)
def generate_token(sender,instance=None,created=False,**kwargs):
    if created:
        Token.objects.create(user=instance)

4、创建获取token用的路由

from django.contrib import admin
from django.urls import path,include
from rest_framework.authtoken import views
urlpatterns = [
    path('api-token-auth', views.obtain_auth_token),#获取token的接口
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls')),
    path('course/',include('course.urls')),
]

5、使用方法  使用post 方法访问api-token-auth 方法  

{
    “username":"xxxx",
   "password":"xxxxx"
}

6、获取到token .就可以使用token认证访问接口了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

larance

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值