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

Viewed 460

I would want to send a http request in a view. The request URL has relation to another view. 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).

2 Answers

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.

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. The example:

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