【问题标题】:Unable to query an API using django forms无法使用 django 表单查询 API
【发布时间】:2018-03-27 21:02:56
【问题描述】:

我正在尝试使用 django 表单查询 API,但在从前端的表单查询 API 时遇到了困难。我有一个带有硬编码值的 python 脚本,当在终端中运行时,它将成功查询我正在使用的 API。

脚本

    import requests
    import urllib.request as urllib2
    import json

    url = "https://trackapi.nutritionix.com/v2/search/instant?"

    body = {
      "query": "query",
      'query': "apple",

    }

    headers = {
        'x-app-id': "ff0ccea8",
        'x-app-key': "605660a17994344157a78f518a111eda",
        'x-remote-user-id': "7a43c5ba-50e7-44fb-b2b4-bbd1b7d22632",

    }

    response = requests.request("GET", url, params=body, headers=headers)

    print(response.json()['common'])

目前,我正在尝试将表单中的“食物”变量传递到 URL 的末尾,然后使用 URL 查询该 API,以从“Nutritionix API”返回食物卡路里计数。问题是 food 变量将在浏览器中到达 URL 的末尾,但它没有查询 API。 我很确定我做错了,应该使用 python 请求 BODY,就像上面的例子一样,我将苹果硬编码到查询中,因为这会将我想要的内容返回到我的终端中。

form.py

class NutritionForm(forms.Form):
    food = forms.CharField(max_length=250)
    # nf_calories = forms.DecimalField()

    def search(self):
        result = {}
        food = self.cleaned_data['food']
        endpoint = 'https://trackapi.nutritionix.com/v2/search?{item_id}'
        url = endpoint.format(item_id=food)
        headers = {'app_id': settings.NUTRITIONIX_APP_ID, 'app_key': settings.NUTRITIONIX_APP_KEY}
        response = requests.get(url, headers=headers)
        if response.status_code == 200: #SUCCESS
            result = response.json()
            result['success'] = True
        else:
            result['success'] = False
            if response.status_code == 404:
                result['message'] = 'No entry found for "%s"' % food
            else:
                result['message'] = 'The Nutritionix API is not available at the moment. Please try again later.'
        return result

有没有办法将 django 表单连接到上面的 Script,这将允许用户从网页查询 API。 任何建议或文件将不胜感激。

编辑

当我查询从表单传递到“views.py”类的 API 时,浏览器中的 URL 被返回,

def nutritionix(request):
    search_result = {}
    if 'food' in request.GET:
        form = NutritionForm(request.GET)
        if form.is_valid():
            search_result = form.search()
    else:
        form = NutritionForm()
    //The following URL is returned into the browser
    //For example http://127.0.0.1:8000/nutrition/food/?food=orange
    return render(request, 'nutrition/nutrition.html', {'form': form, 'search_results': search_result})

我试图像这样将 API 查询的结果传递到前端,

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

  <form method="get">
{#      {% csrf_token %}#}
      {{ form.as_p }}
    <button type="submit">Search</button>
  </form>

【问题讨论】:

  • 如果我理解您正在尝试正确执行的操作(查询第三方 API 并向用户返回一个值,而不将数据存储在您的数据库中),那么在前面使用 JavaScript 可能会更好结束。

标签: python django api


【解决方案1】:

您的独立脚本使用端点“/v2/search/instant”,但您的 Django 版本只有“/v2/search”。此外,该脚本具有查询字符串参数“query=whatever”,但在 Django 中您只需使用“whatever”。

我不知道你为什么不做和你的脚本一样的事情:

url = 'https://trackapi.nutritionix.com/v2/search/instant'
body = {'query': food}
response = requests.get(url, headers=headers, params=body)

【讨论】:

  • 感谢您的回复。我尝试按照您的建议进行操作,但没有成功。这可能是我在查询后如何处理数据的问题。我已更新问题以包含该代码。
猜你喜欢
  • 1970-01-01
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 2015-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多