Python Django 休息框架 api_view 与普通视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21195821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django rest framework api_view vs normal view
提问by Ryan Saxe
I have been looking everywhere to find a decent explanation for this, and they all come short...When do you use the @api_view decorator rather than a class based view with the django rest framework app
我一直在到处寻找对此的体面解释,但它们都不足......你什么时候使用@api_view 装饰器而不是基于类的视图与django rest 框架应用程序
采纳答案by JCotton
REST Framework aside, it's the same question of when to use class based views versus function based views in general. CBVs in Django are awesome, flexible and save loads of boilerplate code, but sometimes it's just faster, easier and clearer to use a function based view. Think about it with the same approach you'd take to writing a normal view in Django. REST Framework simply supports both methods of writing view code as it introduces in the tutorial.
除了 REST 框架之外,一般来说,何时使用基于类的视图与基于函数的视图是相同的问题。Django 中的 CBV 很棒、灵活并且可以节省大量样板代码,但有时使用基于函数的视图会更快、更容易、更清晰。用与在 Django 中编写普通视图相同的方法来考虑它。REST Framework 仅支持本教程中介绍的两种编写视图代码的方法。
Generally go with a CBV unless it's getting in your way, then keep it simple with a function based view and the decorator. In both Django and the REST Framework, the logic for typical things like lists, pagination and CRUD operations is already written and easily extendable in the form of classes and mixins. If your view logic is doing something notably different, a function based view might be appropriate. And of course you can use both approaches in your app.
通常使用 CBV 除非它妨碍您,然后使用基于函数的视图和装饰器保持简单。在 Django 和 REST Framework 中,列表、分页和 CRUD 操作等典型事物的逻辑已经编写好,并且可以以类和 mixin 的形式轻松扩展。如果您的视图逻辑正在做一些明显不同的事情,则基于函数的视图可能是合适的。当然,您可以在您的应用程序中使用这两种方法。
回答by nemesisdesign
Personally, I use the APIView Base Class or @api_view decorator only when I need to do something very specific/custom. For example, to show a list of URLS of the endpoint, aggregate data from different models in a particular manner and so on.
就我个人而言,只有当我需要做一些非常具体/自定义的事情时,我才使用 APIView 基类或 @api_view 装饰器。例如,要显示端点的 URL 列表,以特定方式聚合来自不同模型的数据等等。
Whenever I deal with usual list, create, update and delete operations I use the other classes (Retrieve, Create, Update and Destroy Views or Mixins).
每当我处理通常的列表、创建、更新和删除操作时,我都会使用其他类(检索、创建、更新和销毁视图或混合)。
Example of use of @api_viewdecorator to make a list of all the endpoints of my app:
使用@api_view装饰器制作我的应用程序的所有端点列表的示例:
from django.core.urlresolvers import NoReverseMatch
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from .urls import urlpatterns
@api_view(('GET',))
def root_endpoint(request, format=None):
"""
List of all the available resources of this RESTful API.
"""
endpoints = []
# loop over url modules
for urlmodule in urlpatterns:
# is it a urlconf module?
try:
urlmodule.urlconf_module
is_urlconf_module = True
except AttributeError:
is_urlconf_module = False
# if url is really a urlmodule
if is_urlconf_module:
# loop over urls of that module
for url in urlmodule.urlconf_module.urlpatterns:
# TODO: configurable skip url in settings
# skip api-docs url
if url.name in ['django.swagger.resources.view']:
continue
# try adding url to list of urls to show
try:
endpoints.append({
'name': url.name.replace('api_', ''),
'url': reverse(url.name, request=request, format=format)
})
# urls of object details will fail silently (eg: /nodes/<slug>/)
except NoReverseMatch:
pass
return Response(endpoints)
This code is on github.
这段代码在github 上。

