【问题标题】:APIView chaining in DjangoDjango 中的 APIView 链接
【发布时间】: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 的响应,我更愿意通过postxy 参数传递给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 templatesnamespace 那样做:

<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


【解决方案1】:

做这样的事情,

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)

访问子 api,/child/?store_id=12323,您将收到来自 Parent API 的响应

【讨论】:

  • 这不会改变ParentAPI接受参数的方式吗?现在它通过kwargs['x'] 获取它们,而之前它以request.POST.get('x') 获取它们
  • 您不能更改request.POST 属性,因为request 对象是不可变
  • 你不能模仿HTTP POST请求直接。您可以尝试的是,模拟请求对象.. see the realted post
猜你喜欢
  • 2017-07-07
  • 2017-10-09
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
  • 2020-11-08
相关资源
最近更新 更多