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

相关推荐
2***c43517 小时前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python
2***d88517 小时前
redis的启动方式
数据库·redis·bootstrap
j***576817 小时前
【MySQL】mysqldump使用方法
数据库·mysql·oracle
Coder-coco17 小时前
在线商城系统|基于springboot vue在线商城系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·宠物
M***299117 小时前
MySQL:基础操作(增删查改)
数据库·mysql·oracle
2***c43518 小时前
Redis五种用途
数据库·redis·缓存
k***459918 小时前
MySQL----case的用法
android·数据库·mysql
San30.18 小时前
AIGC 时代如何优雅地操作数据库:SQLite + Python 实战与 SQL Prompt Engineering
数据库·sqlite·aigc
n***543818 小时前
MySQL-CPU使用率高的原因排查和解决方法
数据库·mysql
Mikey_n18 小时前
国产数据库怎么选?人大金仓 vs VStore
数据库