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的更多相关文章

随机推荐

  1. 解决idea tomcat乱码问题

    解决idea Server Output.TomcatLocalhost Log.Tomcat Catalina Log控制台乱码问题 问题原因:编码不一致,tomcat启动后默认编码UTF-8,而w ...

  2. Python29之字符str与字节bytes

    详解见这位大神:https://www.cnblogs.com/xiaobingqianrui/p/9870480.html 实际上字符串和字节之间的转换过程,就是编码解码的过程,我们必须显示的指定编 ...

  3. python 之 网络编程(基于UDP协议的套接字通信)

    8.5 基于UDP协议的套接字通信 UDP协议:数据报协议 特点:无连接,一发对应一收,先启动哪一端都不会报错 优点:发送效率高,但有效传输的数据量最多为500bytes 缺点:不可靠:发送数据,无需 ...

  4. svn: E230001: Server SSL certificate verification failed: certificate issued

    svn: E230001: Server SSL certificate verification failed: certificate issued 今天在使用svn时候发现出现这个问题,这个是因 ...

  5. (未完成)ARM-linux 移植 SDL

    ref : https://blog.csdn.net/u012075739/article/details/24877639   2.      交叉编译SDL 编译SDL前先要编译其依赖库 tsl ...

  6. U盘安装Ubuntu14.04&配置远程win10远程连接

    1.U盘安装Ubuntu:https://blog.csdn.net/baigoocn/article/details/26561473 2.win10远程访问Ubuntu系统:https://www ...

  7. Linux环境实现python远程可视编程

    1. Linux环境 已经安装spyder模块 spyder模块是anaconda自动安装.anaconda安装步骤转:centos7安装Anaconda3 已安装X服务 2. 客户端环境 安装Mob ...

  8. 节日营销!这样搞-App运营日常

    节日送礼需求日益增长,当儿女们有了购买需求的时候,商家如何突出重围,成为孝子们的首选?如何做好节日营销?几个经验分享一下: 1.抓住节日特色 结合节日风格特色,营造节日气氛,如母亲节这种节日,主要体现 ...

  9. react-native——tab配置及跳转

    在 App 中 tab 是常见的页面类型,在 RN 里使用 react-navigation 可快速地进行 tab 配置. 假设应用有4个页面,两个是tab页面,两个是详情页面. App.js //应 ...

  10. active port

    2510099 - SSL Port XXXXX Not Active - message on NWA even though SSL works Resolution Open the defau ...