网络编程
位置:首页>> 网络编程>> Python编程>> 基于Django框架的rest_framework的身份验证和权限解析

基于Django框架的rest_framework的身份验证和权限解析

作者:想成为数据分析师的开发工程师  发布时间:2021-02-21 23:42:58 

标签:Django,验证,权限

1. 概述

到目前为止,程序的API对任何人都可以编辑或删除,没有任何限制。我们希望有一些更高级的行为,进行身份验证和权限分配,以确保:

  • 数据始终与创建者相关联

  • 只有经过身份验证的用户才能创建数据

  • 只有数据的创建者可以更新或删除未经身份验证的请求

  • 若未经过身份验证只有只读访问权限

2. 使用admin应用的User

  • 配置好settings中的数据库配置

  • 将admin应用的数据库进行迁移

  • 使用 createsuperuser 创建用户

基于Django框架的rest_framework的身份验证和权限解析

给可浏览的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: 可以设置为任意符合规则的路径

  • 再次访问api页面,在页面的右上角会看到登录操作的按钮

基于Django框架的rest_framework的身份验证和权限解析

此时,还是没有做到身份验证的功能

3. 视图中添加权限

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/
'''
# 优化代码:
class StudentsView(generics.ListCreateAPIView):
   # 指定需要操作的数据与序列化类
   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]

此时,再次访问页面就无法对其进行操作了,需要登录

基于Django框架的rest_framework的身份验证和权限解析

基于Django框架的rest_framework的身份验证和权限解析

来源:https://blog.csdn.net/m0_63953077/article/details/128175648

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com