【问题标题】:Django: Is it possible create and send Json from a view to another server?Django:是否可以创建 Json 并将其从视图发送到另一台服务器?
【发布时间】:2013-03-28 01:08:52
【问题描述】:

如果我有一个像 <a href="/account/user">Get User Data</a> 这样指向我自己服务器内的 view 的链接,有没有办法将 json 对象(也许只是用 ajax?)发送到另一个外部服务器并检索答案?像这样的:

from django.shortcuts import render

def profile(request):
   #send a json object to another server like http://www.myotherserver.com/user
   #get the answer and process it
   return render(request, 'accounts/profile.html' , 
                {'profile_user': data_from_the_external_server})

上面我当然可以用 jquery-ajax 来实现它,但我只是想知道我是否可以这样做......

提前致谢。

【问题讨论】:

    标签: ajax django json django-views query-string


    【解决方案1】:

    当然可以。为什么不可能?

    如果没有必要,不要在 AJAX 中编码。

    你需要两件事,你需要准备好要发送的 JSon,然后你需要将它发送到你想要的 API:

    1. 查看“simplejson”以创建要发送的 json 数据。
    2. 查看“urllib”以在 Python 中向另一台服务器发送请求(如:How to send a POST request using django?

    也不要把它直接放在你的视野中。为它创建一个新类。所以在你看来,你会有类似的东西:

    def profile(request):
        # instantiate your service here (better with DI)
    
        profile_user = my_service.get_profile_user()
        return render(
            request, 
            'accounts/profile.html' , 
            {
                'profile_user': profile_user
            }
        )
    

    【讨论】:

      【解决方案2】:

      如果您需要将 HTTP 数据(通过 POST 或 GET)发送到另一个服务器并从您的视图中接收结果,您可以使用 Python 的 urllib2 库。但是,有一个更简单的第三方库,称为 Requests,可以为您处理此任务。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-29
        • 1970-01-01
        • 2011-09-16
        相关资源
        最近更新 更多