【问题标题】:It is possible send a http request of a view in another view?可以在另一个视图中发送一个视图的 http 请求吗?
【发布时间】:2021-02-09 05:55:25
【问题描述】:

我想在视图中发送一个 http 请求。请求 URL 与另一个视图有关。像这样的:

class View_A(APIView):
    def get(self, request):
       return Response({'foo':'bar'})


class View_B(APIView):
    def post(self, request):
        # Here I would want to send a request to View_A, something like this:
        request_view_A = View_A.as_view().get('URL_FROM_VIEW_A')
        # ...
        return Response({'foo2':'bar2'})

我见过这个question 有不同的关注点,但是对我不起作用,因为来自View_A(get)的http 方法与来自View_B(post)的http 方法不同。

【问题讨论】:

    标签: python django django-rest-framework django-views


    【解决方案1】:

    你可以这样做:

    class View_B(APIView):
        def post(self, request):
            httpresponse = View_A().get(request)
            # …
            return Response({'foo2':'bar2'})

    我们这里并没有真正发出HTTP请求,我们只是进行方法调用并使用request作为参数。

    话虽如此,这通常意味着您应该“封装”逻辑。通常,其中一个定义了额外的函数或类,通常不是视图,它们实现了随后在两个视图中使用的通用逻辑。

    【讨论】:

    • 嗨@Willem,感谢您的回答,请原谅我的延误。今天我测试了你的解决方案,但我收到了这个错误:The response content must be rendered before it can be accessed. 所以,我发现了这个错误:stackoverflow.com/questions/7258912/… 但我还不明白。
    • @CarMoreno:你能分享一下traceback吗?请注意,httpresponse 将是 Response 对象,而不是包含在其中的字典。
    • 是的@Willem,我的错。您的解决方案对我有用。但是我将听取您的建议,我将编写一个具有辅助功能的解决方案。谢谢! +25
    【解决方案2】:

    Willem Van Onsem answer 的替代方案可以使用 python requests 包。例子:

    import requests 
    #...
    class View_B(APIView):
        def post(self, request):
            response = requests.get(your_url)
            # ...
            return Response({'foo2':'bar2'})
    

    【讨论】:

      猜你喜欢
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2011-04-18
      • 1970-01-01
      相关资源
      最近更新 更多