python - 不使用数据库的 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/SectionA和http://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()
?
解决方案
我想你可以这样尝试:
首先,您需要更新视图,使其接受新参数,即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
推荐阅读
- jenkins - Jenkins 在 npm install 上崩溃
- python - 与 Sublime Text 等其他代码编辑器不同,Pygame 不适用于 VS Code
- scala - 在 Scala 中更改函数中的参数
- sql-server - 使用 Django 配置 MSSQL Server
- java - Java 11. javac/ 警告:[options] 模块名称在 --add-reads 选项未找到:moduleB
- android - Flutter - 单击按钮时在 GridView 中添加容器(小部件)?
- python - 单元测试用例没有在 python 中执行
- javascript - 用户输入正确密码后,如何使提交按钮重定向到另一个页面?
- python - 在 tkinter 中检查时如何打印相应的复选框名称?
- ios - 在 Xcode 中构建档案时出错(我使用过 Unity 和 Firebase)