从 django 中的 API 获取数据

干川加拉米

我可以访问外部 API,其中包含一些类似于以下内容的数据:

{
   "Successful":true,
   "Message":"[{\"Id\":1,\"GroupId\":0,\"QuestionTitle\":\"What is your first name?\",\"GroupName\":null,\"QuestionType\":\"TEXT\",\"IsMappingAvailable\":null,\"BodyRegion\":0,\"EnableCalculation\":false,\"Responses\":[]},{\"Id\":2,\"GroupId\":0,\"QuestionTitle\":\"And your last name?\",\"GroupName\":null,\"QuestionType\":\"TEXT\",\"IsMappingAvailable\":null,\"BodyRegion\":0,\"EnableCalculation\":false,\"Responses\":[]}]"
}

现在我想告诉所有这些Id,并QuestionTitle在我的模板。

我的views.py

def GetQuestion(request):
    headers = {'Content-Type': 'application/json', 'Authorization': 'Basic XXXXXXXXXX='}
    body = { "Tenant" : "devED" }
    GetQuestion_response = requests.post('https://url_name.com/api/GetQuestions', headers=headers, json=body).json()
    GetQuestion_dict={
        'GetQuestion_response' : GetQuestion_response,
    }
    return render(request, 'app\GetQuestion.html', GetQuestion_dict)

在我的template

{% for i in GetQuestion_response.Message %}
      <h2>ID: {{ i.Id }}</h2>
      <h2>QuestionTitle: {{ i.QuestionTitle }}</h2>
{% endfor %}

但不幸的是,它没有显示任何结果。也许是因为MessageAPI 中键的值双引号内(如字符串)。

请建议我该如何解决这个问题

布赖恩·D

在这种情况下,由于Message作为字符串返回,因此需要再次解析为 json,如下所示:

import json

def GetQuestion(request):
    headers = {'Content-Type': 'application/json', 'Authorization': 'Basic XXXXXXXXXX='}
    body = { "Tenant" : "devED" }
    GetQuestion_response = requests.post('https://url_name.com/api/GetQuestions', headers=headers, json=body).json()
    
    # Parse message as json
    GetQuestion_response = json.loads(GetQuestion_response['Message'])
    
    GetQuestion_dict={
        'GetQuestion_response' : GetQuestion_response,
    }
    return render(request, 'app\GetQuestion.html', GetQuestion_dict)

然后在模板中,只需使用GetQuestion_response

{% for i in GetQuestion_response %}
    <h2>ID: {{ i.Id }}</h2>
    <h2>QuestionTitle: {{ i.QuestionTitle }}</h2>
{% endfor %}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章