1

The question is how can I handle HttpResponce from an external server?

The idea is that I send json data to an external server

(e.g search data {'keyword': keyword, 'limit':limit, 'db':db})

response = requests.post(url, json = userupload, headers=headers)

after that I'm getting response from the server with json data

return HttpResponse(response)

It is on the screen, but as you can understand not in a good view for user...

So how can I add this data in a proper html table for example? (the best option is if I can print it out on the same page)

sys__admin
  • 124
  • 1
  • 12
  • If you dont need a "middle man" why not use javascript? I'm not quite sure what you want to achieve, but this: http://docs.python-requests.org might help? – Eska Jul 24 '16 at 22:09

2 Answers2

2

If I understand you correctly, you want to render the output of the post request which is in JSON format into a HTML file.

To do this, pass the json-encoded object from the view to the template:

views.py:

import json

def myview(request):
    obj = requests.post(url, json = userupload, headers=headers)
    return render_to_response("template.html", {"obj_as_json": json.dumps(obj.json())})

template.html:

<html>
    <head>
    <script type="text/javascript">
    var obj = {{ obj_as_json }};
    </script>
    </head>
    ...
</html>
nipun edara
  • 48
  • 1
  • 4
1

https://docs.djangoproject.com/en/1.9/intro/tutorial03/ In the django tutorial you learn how to render a response with html and context data.

If you are using requests you can do like:

response = requests.api.post(...
context = json.loads(response.json())
return render(request, 'index.html', context)

One of the big advanteges with json api's is that you can access it asynchronously with javascript. You should look in to that if you just want to render a response without calling your database to manipulate data from the json api.

Eska
  • 251
  • 2
  • 6