如何在Django视图中向另一个服务器发送请求? [英] How to send a request to another server in a django view?

查看:83
本文介绍了如何在Django视图中向另一个服务器发送请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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请求 库发送请求并获取响应.但是您将需要根据需要设置响应的格式.

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视图中向另一个服务器发送请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆