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

相关推荐
l1t2 小时前
DeepSeek辅助总结postgresql wiki提供的数独求解器
数据库·sql·postgresql
appearappear2 小时前
大数据量处理
数据库
万行2 小时前
SQL进阶&索引篇
开发语言·数据库·人工智能·sql
我是黄骨鱼2 小时前
【零基础学数据库|第二篇】MySql启动!!!
数据库·mysql
陌上丨2 小时前
什么是Redis的大Key和热Key?项目中一般是怎么解决的?
数据库·redis·缓存
Remember_9932 小时前
Spring 事务深度解析:实现方式、隔离级别与传播机制全攻略
java·开发语言·数据库·后端·spring·leetcode·oracle
小园子的小菜2 小时前
深入剖析HBase HFile原理:文件结构、Block协作与缓存机制
数据库·缓存·hbase
空空kkk3 小时前
SSM项目练习——hami音乐(三)
java·数据库
好奇的菜鸟3 小时前
Ubuntu 18.04 启用root账户图形界面登录指南
数据库·ubuntu·postgresql
天桥下的卖艺者3 小时前
使用R语言编写一个生成金字塔图形的函数
开发语言·数据库·r语言