简体   繁体   English

如何在django视图中向另一台服务器发送请求?

[英]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: 我想在我的django view向另一台服务器发送一个http请求,如下所示:

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

How can I do that? 我怎样才能做到这一点?

You can use python requests library to send the request and get the response. 您可以使用python requests库发送请求并获取响应。 But you will need to format the response for your need. 但是您需要根据需要格式化响应。

Here is an example of GET request: 以下是GET请求的示例:

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. 唯一需要注意的是,如果你在这里做,它将不再是ajax (异步JavaScript和XML)。 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. 另一种方法是您正常从django视图加载网页,然后在javascript中执行所有AJAX请求 - 进一步处理响应并在页面中呈现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM