Django 从api调用此函数时,如何在返回重定向函数以获取上下文数据的同时发送字典上下文?
我有一个重定向到url的函数,这个函数有一个上下文dict,我想通过从另一个api函数调用这个函数来获取这个dict,请帮助我,我的代码在这里Django 从api调用此函数时,如何在返回重定向函数以获取上下文数据的同时发送字典上下文?,django,django-models,django-rest-framework,django-views,django-templates,Django,Django Models,Django Rest Framework,Django Views,Django Templates,我有一个重定向到url的函数,这个函数有一个上下文dict,我想通过从另一个api函数调用这个函数来获取这个dict,请帮助我,我的代码在这里 web function API调用函数 class CallingAPI(APIView): permission_classes = (IsAuthenticated,) serializer_class = SomeSerializer def post(self, request): se
web function
API调用函数
class CallingAPI(APIView):
permission_classes = (IsAuthenticated,)
serializer_class = SomeSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
try:
response = function1(request=request, id=serializer.data['id'])
# here in response i want the context from function1
json_response = json.loads(response.content)
if json_response['status'] == 'success':
# Do something
return JsonResponse(final_result, safe=False, status=status.HTTP_200_OK)
except Exception as e:
pass
因此,当我执行response=function1(request=request,id=serializer.data['id'])时,我希望响应中的上下文词典和重定向保持不变。如何实现它。现在我得到的只有您可以创建一个单独的函数,在这里您可以保留公共功能。然后从Web视图和API视图中使用它。像这样:
def some_function(id):
"""
Here I am adding the common codes which will be used by both myfunction and CallingAPI view.
"""
context = dict()
obj = Model.objects.get(id=id)
obj.status = 'Draft'
obj.save()
# Success Message to Mobile App
context['status'] = 'Success'
context['message'] = 'Reset successfully'
context['d'] = id
context['Number'] = obj.no
return context
def myfunction(request, id):
context = some_function(id)
return redirect('del_details', str(id))
class CallingAPI(APIView):
permission_classes = (IsAuthenticated,)
serializer_class = SomeSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
data = some_function(serializer.data['id'])
# rest of the code
是的,但要求对web和api都只使用一个函数,是否有任何方法可以实现它,请建议您可以使用布尔值来实现。您可以使用另一种解决方案,例如使用GET请求,通过覆盖CallingAPI视图中的
GET()
方法和post()进行重定向
要发送与当前实现类似的上下文,我将尝试一下,谢谢
def some_function(id):
"""
Here I am adding the common codes which will be used by both myfunction and CallingAPI view.
"""
context = dict()
obj = Model.objects.get(id=id)
obj.status = 'Draft'
obj.save()
# Success Message to Mobile App
context['status'] = 'Success'
context['message'] = 'Reset successfully'
context['d'] = id
context['Number'] = obj.no
return context
def myfunction(request, id):
context = some_function(id)
return redirect('del_details', str(id))
class CallingAPI(APIView):
permission_classes = (IsAuthenticated,)
serializer_class = SomeSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
data = some_function(serializer.data['id'])
# rest of the code