Django rest framework api_view vs normal view

前端 未结 2 1057
我在风中等你
我在风中等你 2021-02-12 22:50

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 wi

2条回答
  •  有刺的猬
    2021-02-12 23:31

    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.

    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_view decorator to make a list of all the endpoints of my app:

    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//)
                    except NoReverseMatch:
                        pass
    
    
        return Response(endpoints)
    

    This code is on github.

提交回复
热议问题