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 小时前
【数据库-入门2】基本概念
数据库
实泽有之,无泽虚之17 小时前
MySQL主机因多次连接数据库错误而被阻塞
数据库·sql·mysql
Knight_AL17 小时前
从自然语言到 SQL:为什么向量数据库是更好的选择
数据库·sql
Maybe I Simple18 小时前
MySql 数据库分表 简单思路
数据库·php·webman
智航GIS19 小时前
8.11 sys 模块
数据库·windows·microsoft
陈天伟教授19 小时前
国产数据库快速入门《数据库技术原理及应用》(DM8)
数据库·数据挖掘
optimistic_chen19 小时前
【Redis 系列】常用数据结构---SET类型
linux·数据结构·数据库·redis·set·数据类型·命令行
zbguolei20 小时前
上传 Excel 文件进行数据库比对--增加导出功能
数据库·excel
amao998820 小时前
数据库原理与技术 - 3-7 视图和索引 View& Index
数据库·sql·oracle
酸菜牛肉汤面20 小时前
30、大表数据查询,怎么优化
数据库