Django中的APIView链接
我想链接API的调用,我拥有的是:Django中的APIView链接,django,django-rest-framework,django-views,Django,Django Rest Framework,Django Views,我想链接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 = Produc
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"})
我在读,由于参数不是通过
post
传递的,而且url
是通过请求
命中的,因此我不能在没有domainname.com
的情况下执行此操作,例如,我们通过Django模板中的名称空间
执行此操作,如下所示:
<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>
基本上,我想将x,y
包装成请求
。因此,可以通过ParentAPI
asrequest.POST.get('x')
或requues.POST['x']
访问它,请执行类似操作
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
,您将从父api获得响应
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
对象是不可变的,您不能直接模拟httppost
请求。您可以尝试的是模拟请求对象。。这不会改变ParentAPI
接受参数的方式吗?现在它是通过kwargs['x']
获取它们,而之前它是作为request.POST.get('x')
获取它们的,您不能更改request.POST
属性,因为request
对象是不可变的,您不能直接模拟httppost
请求。您可以尝试的是模拟请求对象。。也许requests.post()
可以工作,但需要domainname.com
也许requests.post()
可以工作,但需要domainname.com