解析数据后重定向视图集到Django Rest Framework上的另一个视图集

yi0zb3m4  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(90)

假设我有一个视图集A,我将通过querystring接收一堆数据。我想在视图集A上解析这个查询字符串,然后用解析后的查询字符串将请求重定向到视图集B。我该怎么做呢?
我尝试过在视图集A中添加视图集B,然后手动调用get方法,但没有用。

63lcw9qa

63lcw9qa1#

如果你想从ViewsetA中的一个动作重定向到ViewsetB中的一个动作,下面是你如何使用前面提到的两种不同的方法来实现:

HTTP重定向方式:

通过HTTP重定向将涉及为ViewsetB中的操作创建URL,然后发送HTTP 302响应以将客户端重定向到该URL。

from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.urls import reverse
from urllib.parse import urlencode

class ViewsetA(viewsets.ViewSet):

    @action(detail=False, methods=['GET'])
    def action_in_a(self, request):
        # Do your parsing here
        parsed_data = parse_querystring(request.GET)
        
        # Prepare the new URL for the action in ViewsetB
        new_url = reverse('viewsetb-action_in_b') + '?' + urlencode(parsed_data)
        
        # Redirect to action in Viewset B
        return Response(status=status.HTTP_302_FOUND, headers={'Location': new_url})

class ViewsetB(viewsets.ViewSet):

    @action(detail=False, methods=['GET'])
    def action_in_b(self, request):
        # Handle your request as needed
        return Response(data={"message": "Handled in ViewsetB's action"})

字符串

内部调用方式:

这将涉及从ViewsetA中手动调用ViewsetB中的操作。

from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

class ViewsetA(viewsets.ViewSet):

    @action(detail=False, methods=['GET'])
    def action_in_a(self, request):
        # Do your parsing here
        parsed_data = parse_querystring(request.GET)

        # Manually instantiate and invoke action in Viewset B
        viewset_b = ViewsetB()
        viewset_b.request = request
        viewset_b.format_kwarg = self.format_kwarg
        viewset_b.args = self.args
        viewset_b.kwargs = self.kwargs
        
        # Add parsed_data to the request or any other adjustments
        viewset_b.request.GET = parsed_data

        return viewset_b.action_in_b(request)

class ViewsetB(viewsets.ViewSet):

    @action(detail=False, methods=['GET'])
    def action_in_b(self, request):
        # Handle your request as needed
        return Response(data={"message": "Handled in ViewsetB's action"})

相关问题