2017-02-15 46 views
0

我正在調用api並獲取響應,但不知道如何根據每個鍵訪問它。如何訪問從Django的請求中獲取的單獨數據?

import requeste 

def test(request): 
if request.method == 'POST': 
    data={ 'operator_id':request.POST.get('operator_id'),'mobile_number' :request.POST.get('mobile_number'),'amount':request.POST.get('amount') 
      } 
    r = requests.post(''https://www.somedomain.com/some/url/recharge'', data) 
    print(r.text) 
    if r.status_code == 200: 
     return HttpResponse('it worked') 

else: 
    return render(request, 'account/apitest.html') 

響應:

{ 
    "error":true, 
    "message":"", 
    "NumberVerificationError":"", 
    "Num‌​berVerificationResul‌​t":"", 
    "NumberVerific‌​ationTransactionID":‌​"", 
    "Rechargeerror":"‌​","Rechargeresult":"‌​", 
    "Rechargetransacti‌​onID":"","Paymenterr‌​or":"", 
    "Paymentresul‌​t":"", 
    "Paymenttransa‌​ctionID":"" 
} 
+0

你的API預計婆(參數,值)或JSON有效載荷? –

+0

我應該這樣做r = requests.post('https://www.somedomain.com/some/url/recharge',json = data) – kkk

+0

如果我像上面那樣修改,它會在打印時給出錯誤,如下所示print(r.text) – kkk

回答

0

您可以轉換成字典全光照python json

import json 
response = json.loads(r.text) 
print response['message'] 

或您的請求也可以選擇叫json()

response = r.json() 
print response['message'] 
+0

非常感謝你的工作。 – kkk

相關問題