REST framework中Views API学习

REST framework提供了一个APIView类,它是Django的View类的子类。

APIView类和一般的View类有以下不同:

  • 被传入到处理方法的请求不会是Django的HttpRequest类的实例,而是REST framework的Request类的实例。
  • 处理方法可以返回REST framework的Response,而不是Django的HttpRequest。视图会管理内容协议,给响应设置正确的渲染器。
  • 任何异常情况都将被捕获并调解为适当的响应。APIException
  • 在将请求分派给处理程序方法之前,将对传入的请求进行身份验证,并运行适当的权限和/或限制检查。
    使用APIView类和使用一般的View类非常相似,通常,进入的请求会被分发到合适处理方法比如.get(),或者.post。
    此外,可以在类上设置许多属性,这些属性控制 API 策略的各个方面。
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User

class ListUser(APIView):
    authentication_classes = [authentication.TokenAuthentication]
    permission_classes = [permissions.IsAdminUser]
    def get(self, request, format=None):
        """
        Return a list of all users.
        """
        usernames = [user.username for user in User.objects.all()]
        return Response(usernames)

基于函数的视图:

REST框架还允许您使用基于常规函数的视图。它提供了一组简单的装饰器,这些装饰器包装了基于函数的视图,以确保它们接收到(而不是通常的 Django )的实例,并允许它们返回(而不是 Django ),并允许您配置如何处理请求。

@api_view()

signature: @api_view(http_method_names=[‘GET’])
demo:

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view
def hello_word(request):
    return Response({"message":"Hello World"})

这个视图会使用settings中指定的默认的渲染器,解析器,认证类等等。
默认只接受get请求,其它会得到一个405 Method Not Allowed 的响应

@api_view(['GET','POST'])
def hello_word(request):
    if request.method == 'POST':
        return Response({"message": "Got some data!", "data": request.data})
    return Response({"message":"Hello World"})

API 策略装饰器

为了覆盖默认设置,REST框架提供了一组额外的装饰器,可以将其添加到视图中。这些必须位于装饰器之后(下方)。
例如,要创建一个使用限制的视图,以确保特定用户每天只能调用一次,请使用装饰器,并传递限制类的列表:

@api_view
@throttle_classes
from rest_framework.decorators import api_view,throttle_classes
from rest_framework.throttling import UserRateThrottle

class OncePerDay(UserRateThrottle):
    rate = '1/day'
    
@api_view()
@throttle_classes([OncePerDay])
def hello_word(request):
    return Response({"message":"Hello World"})

这些装饰器对应于上述在子类上设置的属性。APIView
可用的装饰器包括:

  • @renderer_classes(…)
  • @parser_classes(…)
  • @authentication_classes(…)
  • @throttle_classes(…)
  • @permission_classes(…)

以下是一些常见的 API policy attributes 及其功能和使用方式:
1.permission_classes:用于定义访问视图的权限类。

from rest_framework.permissions 
import IsAuthenticated

class MyView(APIView):
    permission_classes = [IsAuthenticated]

功能:限制只有经过身份验证的用户才能访问该视图。

2.authentication_classes:指定用于认证用户的认证类。

from rest_framework.authentication 
import SessionAuthentication, BasicAuthentication

class MyView(APIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication]

功能:确定如何验证用户的身份。

3.throttle_classes:用于设置访问频率限制的类。

from rest_framework.throttling 
import UserRateThrottle

class MyView(APIView):
    throttle_classes = [UserRateThrottle]

功能:控制对 API 的请求速率,防止滥用。

4.renderer_classes

  • 功能:指定用于将响应数据渲染为特定格式(如 JSON、XML 等)的渲染器类。
  • 使用方式:
from rest_framework.renderers 
import JSONRenderer
class MyView(APIView):
    renderer_classes = [JSONRenderer]

5.parser_classes:

  • 功能:定义用于解析传入请求数据的解析器类。
  • 使用方式:
from rest_framework.parsers 
import JSONParser

class MyView(APIView):
    parser_classes = [JSONParser]

6.content_negotiation_class:

  • 功能:负责根据客户端的请求头来确定使用哪种渲染器和解析器。
  • 使用方式:
from rest_framework.negotiation 
import DefaultContentNegotiation

class MyView(APIView):
    content_negotiation_class = DefaultContentNegotiation

通过合理设置这些属性,可以更好地控制 API 处理请求和响应的数据格式,以满足不同客户端的需求。

API policy instantiation methods

以下是一些常见的 API policy instantiation methods 及其功能和使用方式:
1.get_permissions(self)

  • 功能:获取应用于视图的权限实例列表。
  • 使用方式:在视图类中重写该方法以自定义权限的获取逻辑。
    2.get_authentication(self)
  • 功能:获取用于视图的认证实例列表。
  • 使用方式:重写该方法来指定特定的认证方式。
    3.get_throttles(self)
  • 功能:获取应用于视图的节流(访问频率限制)实例列表。
  • 使用方式:通过重写自定义节流策略。

例如:

from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import UserRateThrottle

class MyView(APIView):
    def get_permissions(self):
        return [IsAuthenticated()]

    def get_throttles(self):
        return [UserRateThrottle()]

API 策略实现方法:
在调度到处理程序方法之前,将调用以下方法:

  • .check_permissions
  • check_throttles
  • perform_content_negotiation

架构装饰器[View schema decorator]

主要解决的问题:
1.文档生成:它可以帮助自动生成 API 的文档,让开发者和使用者更清晰地了解 API 的输入和输出格式、参数要求等。
2.接口约定和规范:明确规定 API 的结构和数据格式,有助于保证接口的一致性和可维护性。
3.客户端开发辅助:为客户端开发者提供准确的接口描述,方便他们进行开发和集成。
4.数据验证和转换:在某些情况下,可以辅助进行输入数据的验证和转换,确保传入的数据符合预期。

from rest_framework.decorators import api_view, schema
from rest_framework.schemas import AutoSchema

class CustomAutoSchema(AutoSchema):
    def get_link(self, path, method, base_url):
        # override view introspection here...

@api_view(['GET'])
@schema(CustomAutoSchema())
def view(request):
    return Response({"message": "Hello for today! See you tomorrow!"})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白日与明月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值