0

If i have a link like this one <a href="/account/user">Get User Data</a> who points in a view inside my own server, is there any way to send a json object (maybe just maybe with ajax?) to another external server and retrieve an answer? Something like this:

from django.shortcuts import render

def profile(request):
   #send a json object to another server like http://www.myotherserver.com/user
   #get the answer and process it
   return render(request, 'accounts/profile.html' , 
                {'profile_user': data_from_the_external_server})

The above i can implement it of course with jquery-ajax but i just was wondering if i can do it this way...

Thanks in advance.

CodeArtist
  • 5,534
  • 8
  • 40
  • 65

2 Answers2

1

Of course you can. Why wouldn't it be possible?

Don't code this in AJAX if that's not necessary.

There are 2 things you need, you need to prepare the JSon to send and then you need to send it to the API you want:

  1. Look at "simplejson" to create the json data to send.
  2. Look at "urllib" to send a request to another server in Python (like here: How to send a POST request using django?)

Also do not put it straight in your view. Create a new class for it. So in your view you'll have something like that:

def profile(request):
    # instantiate your service here (better with DI)

    profile_user = my_service.get_profile_user()
    return render(
        request, 
        'accounts/profile.html' , 
        {
            'profile_user': profile_user
        }
    )
Community
  • 1
  • 1
François Constant
  • 5,531
  • 1
  • 33
  • 39
0

If you need to send HTTP data (via a POST or GET) to another server and receive a result from within your view, you can use Python's urllib2 library. However there is an easier third party library called Requests which can handle this task for you.

Brian Neal
  • 31,821
  • 7
  • 55
  • 59