其他分享
首页 > 其他分享> > 【djangorestframework】3、Views(视图)

【djangorestframework】3、Views(视图)

作者:互联网

基于类的视图

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 ListUsers(APIView):
    """
    	查看列出系统中的所有用户
        * 需要令牌认证
        * 只有管理员用户才能访问此视图
    """
    authentication_classes = (authentication.TokenAuthentication, )
    permission_classes = (permissions.IsAdminUser, )
    
    def get(self, request, format=None):
        """
        	返回所有用户的列表
        """
        usernames = [user.username for user in User.objects.all()]
        return Response(usernames)

API策略属性

API策略实例化方法

API策略实现方法

调度方法

基于函数的视图(Function Based Views)

from rest_framework.decorators import api_view

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

API策略装饰器(API poliy decorators)

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

class OncePerDayUserThrottle(UserRateThrottle):
    rate = '1/day'

@api_view(['GET'])
@throttle_classes([OncePerDayUserThrottle])
def view(request):
    return Response({'message': 'hello for day'})

视图模式装饰器(View schema decorator)

from rest_framework.decorators import api_view, schema
form rest_framework.schema 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': '12312321321'})

标签:Views,self,request,视图,framework,djangorestframework,方法,view
来源: https://www.cnblogs.com/guojie-guojie/p/16190591.html