django - Django 中的 APIView 链接
问题描述
我想链接 API 的调用,我拥有的是:
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
class ChildAPI(APIView)
def get(self, request):
store_id = request.GET.get('store_id')
prodcuts = ProductsModel.objects\
.filter(store_id=store_id)\
.annotate(SUM('price'))... etc
x = products['price__sum']
y = products['tax__sum']
现在而不是从我返回一个响应,ChildAPI
我宁愿将x
andy
参数传递post
给ParentAPI
它,然后将响应返回为:
class ParentAPI(APIView):
def post(self, request):
store_id = request.POST.get('store_id')
x = request.POST.get('x')
y = request.POST.get('y')
AwesomeModel.objects.filter(...).update(x=x,y=y)
return Response({"code": 1, "message": "Updated"})
我正在阅读Calling a REST API from Django view,
由于参数没有通过post
并被url
通过requests
,所以我不能没有domainname.com
ie,就像我们namespace
从 Django做的templates
那样:
<form method="post" action="{% url 'product:update-product' %}">
<input type="hidden" value="{{ x }}" name="x">
<input type="hidden" value="{{ y }}" name="y">
<input type="submit" value="Update">
</form>
注意:我ParentAPI url
在另一个 Django Appurls
文件
中有模式,
我们从另一个调用一个函数的方式可以从另一个传递参数调用一个 APIpost
更新:
这里ParentAPI
也是独立调用的,所以我只想传递包装到request
via中的参数post
。不能将它们传递给函数,因为ParentAPI.post(request, x=x)
IfParentAPI
是独立命中的,那么我会创建一个带有可变参数参数**kwarg
的函数并调用该函数。
如果我这样做,我将拥有:
class ParentAPI(APIView):
def post(self, request, *args, **kwargs):
x = request.POST.get('x')
if not x:
x = kwargs['x']
基本上我想发送x,y
包裹到request
. 所以 as 可以通过ParentAPI
asrequest.POST.get('x')
或reques.POST['x']
解决方案
Do something like this,
from rest_framework.views import APIView
class Parent(APIView):
def post(self, request, *args, **kwargs):
return Response(data={"store_id": kwargs['store_id']})
class ChildAPI(APIView):
def get(self, request, *args, **kwargs):
store_id = request.GET.get('store_id')
parent = Parent()
return parent.post(request, store_id=store_id)
Access the child api , /child/?store_id=12323
and you will get response from Parent
API
推荐阅读
- r - R Shiny - 按下操作按钮后在数据表中保存函数值
- highcharts - highcharts - yAxis 网格线的数量不一致
- azure - 资源 > Azure DevOps yaml 管道中未触发的存储库触发器和未禁用的默认触发器
- c++ - 使用 NVCC 编译/链接时,预处理指令 #\ 无效
- javascript - 在引用组件时在 vue 中制作 onClick="" 属性
- html - 如何让我的图像跨越多列?
- volttron - 如何在 volttron 中使用 gevent 和请求进行并发 jsonrpc
- drupal - 将补丁应用于 webform 模块返回错误
- regex - 如何使用 GAS 中的正则表达式将匹配限制在电子邮件正文的前 5 行
- android - 为什么“queueInputBuffer”中的“MediaCodec CodecException”只发生在 Android API 29 上?