02_View
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
class ListUser(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 in User.objects.all()]
# 方法1:lowb
# queryset = User.objects.all()
# usernames = []
# for user in queryset:
# usernames.append(user.username)
return Response(usernames)
url
from django.urls import path
from .views import ListUser, hello_world, view1, view2 urlpatterns = [
path('user-list', ListUser.as_view()),
]
2、API策略属性
下面这些属性控制了API视图可拔插的那些方面。

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

4、API 策略实现方法
在分派到处理程序方法之前调用以下方法。

5、dispatch 相关方法


1、.initialize_request(self, request, args, *kwargs)
# 初始化request请求,返回Request实例

2、.initial(self, request, args, *kwargs)
运行在调用方法处理程序之前,运行你需要的任何功能。可以执行权限认证,节流限制,内容协商

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

4、.finalize_response(self, request, response, args, *kwargs)
确保从处理程序方法返回的任何 Response 对象都被渲染成正确的内容类型

2、基于函数的视图 (Function Based Views)
说 [基于类的视图] 永远是最好的解决方案是一个错误
REST framework 还允许您使用常规的基于函数的视图
urls
from django.urls import path
from .views import ListUser, 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 import api_view @api_view(http_method_names=['GET', 'POST'])
def hello_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 import api_view, throttle_classes
from rest_framework.throttling import UserRateThrottle class OncePerDayUserThrottle(UserRateThrottle): # 节流:一天一次访问器
rate = "1/day" @api_view(['GET'])
@throttle_classes([OncePerDayUserThrottle])
def view1(request):
return Response({"message": "hello for today!see you tomorrow"})


可用的装饰者有:
@renderer_classes(...)@parser_classes(...)@authentication_classes(...)@throttle_classes(...)@permission_classes(...)
3、视图模式装饰器 (View schema decorator)
要覆盖基于函数的视图的默认模式生成,您可以使用 @schema 装饰器
###
# 视图模式装饰器 (View schema decorator)
### from rest_framework.schemas import AutoSchema
from rest_framework.decorators import schema class CustomAutoSchema(AutoSchema):
def get_link(self, path, mehod, base_url):
# 这里重写视图,描述该API的概要
pass @api_view(http_method_names=['GET'])
@schema(CustomAutoSchema)
# @schema(None)
def view2(request):
return Response({"message": "hello for today! see you tomorrow!"})
3、总结
1、APIView源码

02_View的更多相关文章
随机推荐
- 通俗理解TCP的三次握手
三次握手流程的本质,可以这么理解:TCP的三次握手其实是双方各一次握手,各一次确认,只是其中一次握手和确认合并在一起. 当然也可以更通俗的去理解: "喂,你听得到吗?" " ...
- 剑指offer54:字符流中第一个不重复的字符
1 题目描述 请实现一个函数用来找出字符流中第一个只出现一次的字符.例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g".当从该字符流中 ...
- 简单添加自己的驱动程序到Linux内核树中
背景: 移植4g模块的时候,看到文档中有添加驱动到内核的步骤,于是趁着这个机会,展开有关的学习. 了解更多可以访问:<Kconfig语法简介> Target :hi3531d Linux ...
- 在论坛中出现的比较难的sql问题:23(随机填充问题)
原文:在论坛中出现的比较难的sql问题:23(随机填充问题) 最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了. 所以,觉得有必要记录下 ...
- IErrorHandler
/// <summary> /// WCF服务端异常处理器 /// </summary> public class WCF_ExceptionHandler : IErrorH ...
- 【转】Java最常见的200+面试题
今天看到一份面试题总结,感觉很到位,主要包括以下模块:Java基础.容器.多线程.反射.对象拷贝.Java Web模块,异常.网络.设计模式.Spring/Spring MVC .Spring Boo ...
- element-ui default-checked-keys 会把节点下所有子节点全部勾选解决方法
<el-tree class="filter-tree" :data="permissionData" :props="props" ...
- nginx 反向代理配置(二)
上一篇文章主要是对 nginx 各个模块做了一个介绍,以及对什么是反向代理在文章开头做了一个简单介绍,这篇文章我们主要来看下如何进行 nginx 反向代理的配置 proxy 模块 nginx ...
- 使用angularJS设置复选框的回显状态
思路分析: 在angularJS中,我们可以使用ng-checked="expression()"来设置复选框的状态:当expression()返回true时,该复选框为选择中状态 ...
- shell 数学运算
数学运算之 expr expr操作符对照表 比较大小,只能对整数进行比较,需要加空格,linux 保留关键字要转义 num1=30 num2=50 expr $num1 \> $num2 查看上 ...