使用python django在html页面上显示查询的API结果

时间:2018-04-06 11:37:32

标签: python html django api

我目前正在使用django webframework创建一个python应用程序,它允许用户查询外部API以获取有关食物营养的信息(例如卡路里,脂肪)。目前,当用户在网页上的搜索栏中输入他们的食物时,查询API并在终端中显示。我试图在网页上显示信息但是在渲染数据时遇到问题。

form.py

class NutritionForm(forms.Form):
    food = forms.CharField(max_length=100000)

def search(self):
    # result = {}
    food = self.cleaned_data['food']

    headers = {
        'x-app-id': "ff0ccea8",
        'x-app-key': "605660a17994344157a78f518a111eda",
        'x-remote-user-id': "7a43c5ba-50e7-44fb-b2b4-bbd1b7d22632",
        'Content-Type': "application/x-www-form-urlencoded",

    }

    url = 'https://trackapi.nutritionix.com/v2/natural/nutrients'
    body = {
        'query': food,
        'timezone': 'US/Eastern',
    }
    response = requests.request("POST", url, data=body, headers=headers)
    data = response.json()

    print ('food name: ', data['foods'][0]['food_name'])
    print ('food calories: ', data['foods'][0]['nf_calories'])
    print ('food protein: ', data['foods'][0]['nf_protein'])
    print ('food fats: ', data['foods'][0]['nf_total_fat'])

views.py

def nutritionix(request):
    search_result = {}
    if 'food' in request.POST:
        form = NutritionForm(request.POST)
        if form.is_valid():
            search_result = form.search()
    else:
        form = NutritionForm()
    return render(request, 'nutrition/nutrition.html', {'form': form, 'search_results': search_result})

这是我用来尝试显示信息的html页面。但是,当我运行搜索时,会查询API,显示在终端中,但不会显示在网页上。

HTML

{% block content %}
  <h2>Nutritionix API</h2>

  <form action="" method="post">
      {% csrf_token %}
      {{ form.as_p }}
    <button type="submit">Search Food info</button>
  </form>

    {% block body %}
    <div class="container">
        <p>Food name:  {{ food }}</p>
    </div>
{% endblock %}


{% endblock %}

它没有打印到网页上,我这样做是否正确?

1 个答案:

答案 0 :(得分:0)

search()方法似乎没有返回任何内容。更改此项以返回结果:

def search(self):
    ...
    return data['foods'][0]

然后在您的视图中,您可以输出如下结果:

<div class="container">
    <p>Food name:  {{ search_results.food_name }}</p>
    <p>Food calories:  {{ search_results.nf_calories }}</p>
</div>