基于Django框架的rest_framework的身份驗證和權(quán)限解析
1. 概述
到目前為止,程序的API對任何人都可以編輯或刪除,沒有任何限制。我們希望有一些更高級的行為,進行身份驗證和權(quán)限分配,以確保:
- 數(shù)據(jù)始終與創(chuàng)建者相關(guān)聯(lián)
- 只有經(jīng)過身份驗證的用戶才能創(chuàng)建數(shù)據(jù)
- 只有數(shù)據(jù)的創(chuàng)建者可以更新或刪除未經(jīng)身份驗證的請求
- 若未經(jīng)過身份驗證只有只讀訪問權(quán)限
2. 使用admin應(yīng)用的User
- 配置好settings中的數(shù)據(jù)庫配置
- 將admin應(yīng)用的數(shù)據(jù)庫進行遷移
- 使用 createsuperuser 創(chuàng)建用戶
給可瀏覽的API添加登錄功能 在根urls中添加:
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('rest_app.urls')), path('api-auth/',include('rest_framework.urls')), ]
說明:
- api-auth: 可以設(shè)置為任意符合規(guī)則的路徑
- 再次訪問api頁面,在頁面的右上角會看到登錄操作的按鈕
此時,還是沒有做到身份驗證的功能
3. 視圖中添加權(quán)限
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_app.models import * from rest_app.app_serializer import StudentSerializer,ClassesSerializer from django.http import JsonResponse,HttpResponse,Http404 from rest_framework.parsers import JSONParser from rest_framework.request import Request from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import api_view from rest_framework.views import APIView from rest_framework import mixins, generics from rest_framework import permissions # Create your views here. ''' 新增 post students/ 刪除 delete students/id/ 修改 put students/id/ 查詢一個 get students/id/ 查詢所有 get students/ ''' # 優(yōu)化代碼: class StudentsView(generics.ListCreateAPIView): # 指定需要操作的數(shù)據(jù)與序列化類 queryset = Student.objects.all() serializer_class = StudentSerializer # 添加身份驗證功能 permission_classes = [permissions.IsAuthenticatedOrReadOnly] class StudentDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Student.objects.all() serializer_class = StudentSerializer # 添加身份驗證功能 permission_classes = [permissions.IsAuthenticatedOrReadOnly]
此時,再次訪問頁面就無法對其進行操作了,需要登錄
到此這篇關(guān)于基于Django框架的rest_framework的身份驗證和權(quán)限解析的文章就介紹到這了,更多相關(guān)Django-rest_framework身份驗證和權(quán)限內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
梅爾頻率倒譜系數(shù)(mfcc)及Python實現(xiàn)
這篇文章主要為大家詳細介紹了語音識別之梅爾頻率倒譜系數(shù)及Python實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-06-06通過python調(diào)用adb命令對App進行性能測試方式
這篇文章主要介紹了通過python調(diào)用adb命令對App進行性能測試方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04Python 函數(shù)list&read&seek詳解
這篇文章主要介紹了Python 函數(shù)list&read&seek詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08