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认证访问接口了

相关推荐
一个响当当的名号16 分钟前
lectrue9 索引并发控制
java·开发语言·数据库
liu****20 分钟前
4.Qt窗口开发全解析:菜单栏、工具栏、状态栏及对话框实战
数据库·c++·qt·系统架构
三水不滴32 分钟前
Redis缓存更新策略
数据库·经验分享·redis·笔记·后端·缓存
企鹅侠客1 小时前
第35章—内核解析篇:Redis内存淘汰机制
数据库·redis
西柚小萌新1 小时前
【人工智能:Agent】--12.多智能体(二)
数据库
快乐非自愿1 小时前
【面试题】MySQL 的索引类型有哪些?
数据库·mysql·面试
naruto_lnq1 小时前
使用Fabric自动化你的部署流程
jvm·数据库·python
曹轲恒1 小时前
【Redis持久化核心】AOF/RDB通俗详解+多场景对比
数据库·redis·bootstrap
冉冰学姐2 小时前
SSM疫情期间学生作业线上管理系统55zmw(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·计算机毕设·ssm作业管理系统