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

相关推荐
prince057 分钟前
用户积分系统怎么设计
java·大数据·数据库
原来是猿2 小时前
MySQL【内置函数】
数据库·mysql
難釋懷2 小时前
Redis分片集群插槽原理
数据库·redis·缓存
冷小鱼2 小时前
pgvector 向量数据库完全指南:PostgreSQL 生态的 AI 增强
数据库·人工智能·postgresql
陈天伟教授2 小时前
人工智能应用- 天文学家的助手:08. 星系定位与分类
前端·javascript·数据库·人工智能·机器学习
yunyun321233 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
m0_662577973 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
ℳ๓₯㎕.空城旧梦3 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
Navicat中国3 小时前
Navicat 高效破解 SQL 编写繁琐难题,提升数据库设计效率
数据库·可视化·sql编写繁琐
Amctwd3 小时前
【数据库】常用 Sql 示例
数据库·sql·oracle