APIView和View的区别
2021-03-15 18:34
标签:lob pre 并且 make simple only follow items import django中编辑视图views.py有两种方式,一种是基于类的实现,另外一种是函数式的实现方式,两种方法都可以用。 django的View部分源码 REST framework的 先使用django自带的view,获取一个Card表里面的卡号信息: views.py视图的编写 APIView和View的区别 标签:lob pre 并且 make simple only follow items import 原文地址:https://www.cnblogs.com/jiangcw/p/12412017.html前言
REST框架提供了一个APIView类,它是Django View类的子类。View与APIView的区别
View
是Django默认的视图基类,APIView
是REST framework提供的所有视图的基类, 继承自Django的View
。APIView
与View
的不同之处在于:
class View:
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
"""
http_method_names = [‘get‘, ‘post‘, ‘put‘, ‘patch‘, ‘delete‘, ‘head‘, ‘options‘, ‘trace‘]
def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in kwargs.items():
setattr(self, key, value)
APIView
继承了django的View
,部分源码如下class APIView(View):
# The following policies may be set at either globally, or per-view.
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
parser_classes = api_settings.DEFAULT_PARSER_CLASSES
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
metadata_class = api_settings.DEFAULT_METADATA_CLASS
versioning_class = api_settings.DEFAULT_VERSIONING_CLASS
# Allow dependency injection of other settings to make testing easier.
settings = api_settings
schema = DefaultSchema()
APIView
多了一些属性和方法,比如:身份认证、权限检查、流量控制
django的View
models.py设计card表# models.py
class Card(models.Model):
‘‘‘银行卡 基本信息 # 作者:JAY,QQ交流群:123456789‘‘‘
card_id = models.CharField(max_length=30, verbose_name="卡号", default="")
card_user = models.CharField(max_length=10, verbose_name="姓名", default="")
add_time = models.DateField(auto_now=True, verbose_name="添加时间")
class Meta:
verbose_name_plural = ‘银行卡账户‘
verbose_name = "银行卡账户_基本信息"
def __str__(self):
return self.card_id
from django.http import JsonResponse
from rest_framework import serializers
from django.core import serializers as dj_serializers # 避免和rest_framework里面的serializers冲突
from .models import *
from django.views.generic.base import View
import json
# 作者:上海悠悠,QQ交流群:750815713
class CardListView(View):
‘‘‘基于django的view实现获取card列表‘‘‘
def get(self, request):
data = {}
cards = Card.objects.all()
data[‘result‘] = json.loads(dj_serializers.serialize("json", cards))
return JsonResponse(data)
上一篇:C# - Task