[Answer]-Django: Is it possible create and send Json from a view to another server?

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

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

Leave a comment