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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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: stackoverflow.com/questions/7258912/… but I don't understan yet.
@CarMoreno: can you share the traceback? Note that httpresponse will be Response object, not the dictionary wrapped in it.
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
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'})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.