2013-03-28 19 views
0

如果我有這樣的鏈接<a href="/account/user">Get User Data</a>誰指向我自己的服務器內的視圖,有什麼辦法發送一個json對象(也許只是可能與ajax?)到另一個外部服務器並檢索答案?事情是這樣的:Django:是否有可能創建併發送Json從一個視圖到另一個服務器?

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,但我只是想知道如果我能做到這一點這樣......

在此先感謝。

回答

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 
     } 
    ) 
0

如果您需要將HTTP數據(通過POST或GET)發送到另一臺服務器並從您的視圖中接收結果,則可以使用Python的urllib2庫。但是有一個更簡單的第三方庫叫做Requests,它可以爲你處理這個任務。

相關問題