Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a request to another server in a django view?

I want to send an http request to another server in my django view like this:

def django_view(request):
    response = send_request('http://example.com')
    result = do_something_with_response(response)
    return HttpResponse(result)

How can I do that?

like image 243
Navid777 Avatar asked Mar 31 '16 05:03

Navid777


1 Answers

You can use python requests library to send the request and get the response. But you will need to format the response for your need.

Here is an example of GET request:

import requests

def django_view(request):
    # get the response from the URL
    response = requests.get('http://example.com')
    result = do_something_with_response(response)
    return HttpResponse(result)

The only caveat is that if you do it here it won't be ajax (Asynchronous JavaScript and XML) anymore. The alternative would be that you load your webpage from django view normally and then perform all the AJAX requests in javascript - further processing the response and rendering it in the page.

like image 158
AKS Avatar answered Oct 18 '22 18:10

AKS