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

我只是一个虾纸丫 提交于 2020-12-29 06:01:33

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/36324889/how-to-send-a-request-to-another-server-in-a-django-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!