首页 > 解决方案 > 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我宁愿将xandy参数传递postParentAPI它,然后将响应返回为:

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.comie,就像我们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也是独立调用的,所以我只想传递包装到requestvia中的参数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 可以通过ParentAPIasrequest.POST.get('x')reques.POST['x']

标签: djangodjango-rest-frameworkdjango-views

解决方案


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


推荐阅读