【发布时间】:2018-08-19 13:29:56
【问题描述】:
我想链接 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 的响应,我更愿意通过post 将x 和y 参数传递给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 就不能这样做,即就像我们通过来自Django templates 的namespace 那样做:
<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>
注意:我在另一个 Django App urls 文件中有 ParentAPI url 模式,
我们从另一个函数调用一个函数的方式,我可以从另一个通过 post 包装的传递参数调用一个 API
更新:
这里ParentAPI 也被独立调用,所以我只想通过post 传递包装到request 中的参数。无法将它们传递给ParentAPI.post(request, x=x)
如果ParentAPI 被独立命中,那么我宁愿创建一个带有可变参数参数**kwarg 的函数并调用该函数。
如果我这样做,我将拥有:
class ParentAPI(APIView):
def post(self, request, *args, **kwargs):
x = request.POST.get('x')
if not x:
x = kwargs['x']
基本上我想将x,y 包装成request。所以它可以通过ParentAPI 访问为request.POST.get('x') 或reques.POST['x']
【问题讨论】:
-
也许
requests.post()会起作用,但会占用domainname.com
标签: django django-rest-framework django-views