简体   繁体   English

可以在另一个视图中发送一个视图的 http 请求吗?

[英]It is possible send a http request of a view in another view?

I would want to send a http request in a view.我想在视图中发送一个 http 请求。 The request URL has relation to another view.请求 URL 与另一个视图相关。 Something like this:像这样的东西:

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'})

I have seen this question which has a different focus, however don't working for me because http method from View_A (get) is different to http method from View_B (post).我见过这个问题有不同的重点,但是对我不起作用,因为View_A (get) 的 http 方法与View_B (post) 的 http 方法不同。

You can do that with:你可以这样做:

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

We here do not really make a HTTP request, we simply make a method call and use request as parameter.我们这里并没有真正发出 HTTP 请求,我们只是进行方法调用并使用request作为参数。

That being said, often this means you should "encapsulate" the logic.话虽如此,这通常意味着您应该“封装”逻辑。 Normally one thus defines extra function(s) or class(es), normally not views, that implement common logic that is then used in both views.通常,因此定义了额外的函数或类,通常不是视图,它们实现了然后在两个视图中使用的公共逻辑。

The alternative to Willem Van Onsem answer can be using the python requests package. Willem Van Onsem 答案的替代方法是使用 python requests 包。 The example:这个例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM