问题描述
我想在我的 django 视图
中向另一台服务器发送一个 http
请求,如下所示:
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)
我该怎么做?
推荐答案
您可以使用 python requests
库发送请求并获得响应.但是您需要根据需要格式化响应.
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.
这是一个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)
唯一需要注意的是,如果你在这里这样做,它将不再是 ajax
(异步 JavaScript 和 XML).另一种方法是您从 django 视图正常加载网页,然后在 javascript 中执行所有 AJAX 请求 - 进一步处理响应并将其呈现在页面中.
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.
这篇关于如何在 Django 视图中向另一台服务器发送请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!