首页 > 解决方案 > 不使用数据库的 Django REST API

问题描述

我有一个现有的 Django 应用程序。我需要在其中包含一个不涉及 DB 的功能。我已经在views.py中编写了要执行的操作

 class VamComponent(View):
    def getSectionADetails(self,request):
     .......
    return HttpResponse()

urls.py中,我在 urlpatterens 中包含了这一行:

url(r'^vamcomponent$', VamComponent.as_view())

我可以从此网址 http://localhost:8000/vamcomponent/访问详细信息。

我需要让我的端点为 URL 中的部分设置一些值,例如http://localhost:8000/vamcomponent/SectionAhttp://localhost:8000/vamcomponent/SectionB

views.py中,如果我将类修改为具有2个函数,则根据请求中部分的值,它应该调用相应的方法

 class VamComponent(View):
    def getSectionADetails(self,request):
     .......
    return HttpResponse()
    def getSectionBDetails(self,request):
     .......
    return HttpResponse()

如何在urls.py文件中进行此更改,以便getSectionADetails()在请求中包含 SectionA 时调用它getSectionBDetails()

标签: pythondjangorestdjango-rest-framework

解决方案


我想你可以这样尝试:

首先,您需要更新视图,使其接受新参数,即SectionA# SectionB urls

url(r'^vamcomponent/(?P<section>[-\w]+)/?$', VamComponent.as_view())

现在让我们相应地更新视图,以便在 urls 中传递的值进入视图:

class VamComponent(View):
     def get(self, request, section=None):  # or post if necessary
         if section == "SectionB":
            return self.getSectionBDetails(request)
         return self.getSectionADetails(request)    

仅供参考,如果您正在使用django-rest-framework,那么为什么不使用APIView

from rest_framework.views import APIView

class VamComponent(APIView):
    # rest of the code

推荐阅读