Django DRF Token認(rèn)證基本使用小結(jié)
一. 前言
Django Rest Framework Token是Django Rest Framework中的一個擴展,用于實現(xiàn)用戶認(rèn)證和授權(quán)。它為每個用戶生成一個唯一的Token,并將其存儲在數(shù)據(jù)庫中。在用戶進行API請求時,用戶需要在請求的HTTP Header中包含Token,這樣服務(wù)器就可以驗證用戶的身份。
二. 基本使用
1. 安裝DRF Token擴展:
pip install djangorestframework pip install django-rest-framework-authtoken
2.在Django的settings.py中添加以下配置
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
}
3. 遷移
python manage.py migrate
遷移完成會生成authtoken_token這張表來記錄用戶的token

4. 生成Token
from rest_framework.authtoken.models import Token from django.contrib.auth.models import User user = User.objects.create_user(username='johnson', password='doe') token, created = Token.objects.get_or_create(user=user)
現(xiàn)在,johnson用戶已經(jīng)有了一個令牌??梢詫⒋肆钆品祷亟o客戶端,并在以后的請求中使用它進行身份驗證:
GET /api/test/ HTTP/1.1 Authorization: Token <token>
5. 使用TokenAuthentication
現(xiàn)在,可以通過在視圖中使用TokenAuthentication來保護視圖
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
class TestView(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({'message': 'Hello, world!'})
在這個例子中,TestView視圖被保護,只有經(jīng)過身份驗證的用戶才能訪問。
到此這篇關(guān)于Django DRFToken認(rèn)證基本使用小結(jié)的文章就介紹到這了,更多相關(guān)Django DRFToken認(rèn)證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python數(shù)據(jù)寫入列表并導(dǎo)出折線圖
這篇文章主要介紹了python數(shù)據(jù)寫入列表并導(dǎo)出折線圖,文章以舉例展開對文章主題的介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-01-01
一個Python優(yōu)雅的數(shù)據(jù)分塊方法詳解
在做需求過程中有一個對大量數(shù)據(jù)分塊處理的場景,具體來說就是幾十萬量級的數(shù)據(jù),分批處理,每次處理100個。這時就需要一個分塊功能的代碼。本文為大家分享了一個Python中優(yōu)雅的數(shù)據(jù)分塊方法,需要的可以參考一下2022-05-05
Python列表數(shù)據(jù)如何按區(qū)間分組統(tǒng)計各組個數(shù)
這篇文章主要介紹了Python列表數(shù)據(jù)如何按區(qū)間分組統(tǒng)計各組個數(shù),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07

