我目前正在使用django webframework创建一个python应用程序,它允许用户查询外部API来获取有关食物营养(例如卡路里、脂肪)的信息。目前,当用户在网页上的搜索栏中输入食物时,API将被查询并显示在终端上。我试图在网页上显示信息,但在呈现数据时遇到问题。在
表单.pyclass 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'])
视图.py
^{pr2}$
这是我用来显示信息的html页面。但是,当我运行搜索时,API被查询,显示在终端上,但是没有显示在网页上。在
html{% block content %}
Nutritionix API
{% csrf_token %}
{{ form.as_p }}
Search Food info
{% block body %}
Food name: {{ food }}
{% endblock %}
{% endblock %}
它没有打印到网页上,我这样做正确吗?在