Django Rest framework (看完直接上手用)

本文详细介绍了Django REST Framework(DRF)在API开发中的关键概念和用法,包括APIView的请求处理、基于函数和类的视图、认证、权限、访问频率控制、版本管理、解析器、序列化、以及视图集和路由的使用。内容涵盖了自定义认证和权限类、节流策略、序列化模型数据、分页、视图功能和路由配置等核心功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Restframework
  • DjangoRestframework 主要使用 APIView 类,其 APIView 实质是对 View 进行继承加工了更多功能
  • 请求进来 APIView() 首先执行 self.dispatch() 方法,此方法对 原有 request 进行了再次封装

一、 基于 FBV 视图函数

* 全站使用 csrf 认证
'django.middleware.csrf.CsrfViewMiddleware', # 全站使用csrf认证

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt # 该函数无需认证
def users(request):
    user_list = ['alex','oldboy']
    return HttpResponse(json.dumps((user_list)))

* 全站不使用 csrf 认证 
#'django.middleware.csrf.CsrfViewMiddleware', # 全站不使用csrf认证

from django.views.decorators.csrf import csrf_exempt

@csrf_protect # 该函数需认证
def users(request):
    user_list = ['alex','oldboy']
    return HttpResponse(json.dumps((user_list)))

二、基于 CBV 的视图函数

CBV csrf 时需要使用

  • @method_decorator(csrf_exempt)
  • 在dispatch()方法中(单独方法无效)
方式一:
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.utils.decorators import method_decorator
class StudentsView(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
    	return super(StudentsView,self).dispatch(request, *args, **kwargs)
方式二:
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt,name='dispatch')
class StudentsView(View):
    
    def get(self,request,*args,**kwargs):
        print('get方法')
        return HttpResponse('GET')

一、认证(有些API需要用户登录成功之后才能访问;有些无需登录就能访问)

* 内置认证类
   1. 认证类,必须继承:from rest_framework.authentication import BaseAuthentication
   2. 其他认证类:BasicAuthentication

* 使用:
继承 BaseAuthentication; 必须实现:authenticate()和 authenticate_header()方法
	- 创建类:继承 BaseAuthentication;
		from rest_framework.authentication import BaseAuthentication
		class Authtication(BaseAuthentication):
    		def authenticate(self,request):
        		token = request._request.GET.get('token')
        		token_obj = models.UserToken.objects.filter(token=token).first()
        		if not token_obj:
            		raise exceptions.AuthenticationFailed('用户认证失败')
        	return (token_obj.user, token_obj)

    		def authenticate_header(self, request):
        		return 'Basic realm="api"'
	- 返回值:
    - None,我不管了,下一认证来执行。
    - raise exceptions.AuthenticationFailed('用户认证失败') # from rest_framework import exceptions
    - (元素1,元素2)  # 元素1赋值给request.user; 元素2赋值给request.auth 
    - 局部使用
        class UserInfoView(APIView):
        	""" 订单相关业务 """
            authentication_classes = [自定义认证类1,自定义认证类2]
            def get(self,request,*args,**kwargs):
            	print(request.user)
            	return HttpResponse('用户信息')
	- 全局使用:
    	REST_FRAMEWORK = {
   
        	# 全局使用的认证类
            "DEFAULT_AUTHENTICATION_CLASSES":[
                'api.utils.auth.自定义认证类1', 'api.utils.auth.自定义认证类2',],
            # "UNAUTHENTICATED_USER":lambda :"匿名用户",
            "UNAUTHENTICATED_USER":None,  # 匿名,request.user = None
            "UNAUTHENTICATED_TOKEN":None, # 匿名,request.auth = None
        }

案例:

auth.py
class Authtication(BaseAuthentication):
    def authenticate(self,request):
        token = request._request.GET.get('token')
        token_obj 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值