2

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).

Carmoreno
  • 1,271
  • 17
  • 29

2 Answers2

3

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Hi @Willem, thanks for your answer and excuse me for my delay. Today I test your solution but I get this error: `The response content must be rendered before it can be accessed.` So, I found this asnwer: https://stackoverflow.com/questions/7258912/manually-calling-a-class-based-generic-view but I don't understan yet. – Carmoreno Nov 03 '20 at 22:55
  • 1
    @CarMoreno: can you share the *traceback*? Note that `httpresponse` will be `Response` object, not the dictionary wrapped in it. – Willem Van Onsem Nov 03 '20 at 23:02
  • Yeah @Willem, my fault. Your solution working for me.However I'm going to take your advice, I will program a solution with an auxiliar function. Thank you! +25 – Carmoreno Nov 04 '20 at 14:45
2

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'})
pplonski
  • 5,023
  • 1
  • 30
  • 34