02_View

摘要:
"})2、API策略装饰器RESTframework提供了一系列可以添加到视图中的附加装饰器例如,要创建一个使用限流来确保它每天只能由特定用户调用一次的视图,请使用@throttle_classes装饰器,传递一个限流类列表:fromrest_framework.decoratorsimportapi_view,throttle_classesfromrest_framework.throttlingimportUserRateThrottleclassOncePerDayUserThrottle:#节流:一天一次访问器rate="1/day"@api_view@throttle_classesdefview1:returnResponse({"message":"hellofortoday!

1、View

1、基于类的视图 Class-based Views

REST framework提供APIView是Django的View的子类
发送到View的Request请求:是REST framework的Request类的实例,而不是Django的HttpRequest类的实例
View返回的Response响应:返回REST framework的Response,而不是Django的HttpRequest
将请求分派给处理程序方法之前,可以进行如下操作:认证,合适的权限和(或)节流检查

View视图

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
classListUser(APIView):
    """
    列出系统中的所用用户的视图
    * 需要token认证
    * 只有管理员用户可以访问这个视图
    """
    #authentication_classes = [authentication.TokenAuthentication]   # 需要携带token访问
    permission_classes =[permissions.IsAdminUser]
    def get(self, request, format=None):
        """
        Return a list of all users.
        """
        usernames = [user.username for user inUser.objects.all()]
        #方法1:lowb
        #queryset = User.objects.all()
        #usernames = []
        #for user in queryset:
        #usernames.append(user.username)
        return Response(usernames)

url

from django.urls importpath
from .views importListUser, hello_world, view1, view2
urlpatterns =[
    path('user-list', ListUser.as_view()),
]

2、API策略属性

下面这些属性控制了API视图可拔插的那些方面。

02_View第1张

3、API 策略实例化方法

下面这些方法被REST framework用来实例化各种可拔插的API策略。你通常不需要重写这些方法。

02_View第2张

4、API 策略实现方法

在分派到处理程序方法之前调用以下方法。

02_View第3张

5、dispatch 相关方法

02_View第4张

02_View第5张

1、.initialize_request(self, request,args,*kwargs)

# 初始化request请求,返回Request实例

02_View第6张

2、.initial(self, request,args,*kwargs)

运行在调用方法处理程序之前,运行你需要的任何功能。可以执行权限认证,节流限制,内容协商

02_View第7张

3、.handle_exception(self, exc)

处理程序方法抛出的任何异常都将传递给此方,通过返回适当的响应,或重新引发错误。

02_View第8张

4、.finalize_response(self, request, response,args,*kwargs)

确保从处理程序方法返回的任何Response对象都被渲染成正确的内容类型

02_View第9张

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

说 [基于类的视图] 永远是最好的解决方案是一个错误

REST framework 还允许您使用常规的基于函数的视图

urls

from django.urls importpath
from .views importListUser, hello_world, view1, view2
urlpatterns =[
    path('user-list', ListUser.as_view()),
    #@api_view
    path('hello-world', hello_world),
    path('view1', view1),   #节流
    path('view2', view2),   #schema api概要描述
]

1、@api_view()

语法:@api_view(http_method_names=['GET'])

from rest_framework.decorators importapi_view
@api_view(http_method_names=['GET', 'POST'])
defhello_world(request):
    if request.method == 'POST':
        return Response({"message": "Got some data!", "data": request.data})
    return Response({"message": "hello world!"})

2、API 策略装饰器 (API policy decorators)

REST framework 提供了一系列可以添加到视图中的附加装饰器

例如,要创建一个使用限流来确保它每天只能由特定用户调用一次的视图,请使用@throttle_classes装饰器,传递一个限流类列表:

from rest_framework.decorators importapi_view, throttle_classes
from rest_framework.throttling importUserRateThrottle
class OncePerDayUserThrottle(UserRateThrottle):  #节流:一天一次访问器
    rate = "1/day"
@api_view(['GET'])
@throttle_classes([OncePerDayUserThrottle])
defview1(request):
    return Response({"message": "hello for today!see you tomorrow"})

02_View第10张02_View第11张

可用的装饰者有:

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

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

要覆盖基于函数的视图的默认模式生成,您可以使用@schema装饰器

###
#视图模式装饰器 (View schema decorator)
###
from rest_framework.schemas importAutoSchema
from rest_framework.decorators importschema
classCustomAutoSchema(AutoSchema):
    defget_link(self, path, mehod, base_url):
        #这里重写视图,描述该API的概要
        pass
@api_view(http_method_names=['GET'])
@schema(CustomAutoSchema)
#@schema(None)
defview2(request):
    return Response({"message": "hello for today! see you tomorrow!"})

3、总结

1、APIView源码

02_View第12张

免责声明:文章转载自《02_View》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Android Studio中怎样引用图片资源MySQL笔记-高可用方案下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

服务端跨域处理 Cors

1 添加System.Web.Cors,System.Web.Http.Cors 2 global文件中 注册asp.net 管道事件 protected void Application_BeginRequest(objectsender, EventArgs e) { var response...

kaptcha Java验证码

原文:http://www.cnblogs.com/chizizhixin/p/5311619.html 在项目中经常会使用验证码,kaptcha 就一个非常不错的开源框架,分享下自己在项目中的使用: 1、首先下载kaptcha 把kaptcha-2.3.2.jar包放在lib下 2、登陆页面初始化 document.getElementById("myc...

jquery的ajax()函数传值中文乱码解决方法介绍

代码如下: $.ajax({   dataType : ‘json',type : ‘POST',url : ‘http://localhost/test/test.do',data : {id: 1, type: ‘商品'},success : function(data){ } } ); 问题: 提交后后台action程序时,取到的type是乱码...

C# HttpWebRequest请求服务器(Get/Post兼容)

简单示例说明 public static string HttpGet(string url, string data,string Method, int timeOut, Encoding encode, string contentType = "application/x-www-form-urlencoded", CookieContainer...

request和response简介

Tomcat收到客户端的http请求,会针对每一次请求,分别创建一个代表请求的request对象、和代表响应的response对象。 既然request对象代表http请求,那么我们获取浏览器提交过来的数据,找request对象即可。response对象代表http响应,那么我们向浏览器输出数据,找response对象即可。 http响应由状态行、实体内容...

Android Volley框架的几种post提交请求方式

首先简单描写叙述一下Google的Android开发团队在2013年推出的一个网络通信框架Volley.它的设计目标是进行数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作,比方下载文件等,Volley的表现就不尽如人意。 在app开发中,我们最常见的就是从appclient向服务端发一个http请求.对于两种主要的web请求方式get和post...