繁体   English   中英

Django对API的HTTP请求错误

[英]Django http request to api error

因为这是我第一次尝试,所以我不知道问题出在哪里。 因此,如果有人可以帮助我解决这个问题,那就太好了

我正在使用的代码位于该网站的底部: https : //www.twilio.com/blog/2014/11/build-your-own-pokedex-with-django-mms-and-pokeapi.html

该示例提供了有关如何使HTTP请求功能以及如何在查询中检索数据库的示例。

网站上的代码是这个。

query.py

import requests
import json

BASE_URL = 'http://pokeapi.co'


def query_pokeapi(resource_url):
    url = '{0}{1}'.format(BASE_URL, resource_url)
    response = requests.get(url)

    if response.status_code == 200:
        return json.loads(response.text)
    return None


charizard = query_pokeapi('/api/v1/pokemon/charizard/')

sprite_uri = charizard['sprites'][0]['resource_uri']
description_uri = charizard['descriptions'][0]['resource_uri']

sprite = query_pokeapi(sprite_uri)
description = query_pokeapi(description_uri)

print
charizard['name']
print
description['description']
print
BASE_URL + sprite['image']

在我的编辑中,我仅更改了此打印底部的这些打印行

query.py

print(charizard['name'])
print(description['description'])
print(BASE_URL + sprite['image'])

但是我却得到了这个错误

追溯(最近一次通话):文件“ query2.py”,第46行,位于sprite_uri = charizard ['sprites'] [0] ['resource_uri'] TypeError:“ NoneType”对象不可下标

query_pokeapi必须返回None,这意味着您的API调用未收到200 HTTP响应。 我会检查您的网址,以确保其格式正确。 在您的Web浏览器中对其进行测试。

最好的做法是尝试-除非您的API调用带有错误消息,否则您将知道您的API调用失败,否则将路由该线程。

更新:重新读取,子脚本问题可能在嵌套对象的任何层中。

在调试器中逐步评估charizard ['sprites'] [0] ['resource_uri']。

当您调用api requests.get(url)其响应为

在此URI上找到多个资源

您在结果上使用charizard['sprites'][0]['resource_uri'] ,并引发异常。

当我尝试获取响应时,状态代码为300因此

def query_pokeapi(resource_url)返回None值。

'{0}{1}'.format(BASE_URL, resource_url)

更新

这意味着在{0}将是BASE_URL ,在{1}将是resource_url。

完整网址为

url = '{0}{1}'.format(BASE_URL, resource_url)
url = 'http://pokeapi.co/api/v1/pokemon/charizard/'.

更新

你可以试试

import json
charizard = query_pokeapi('/api/v1/pokemon/')
data = json.loads(charizard.content)
print data['objects'][0]['descriptions'][0]

结果将是

{u'name': u'ekans_gen_1', u'resource_uri': u'/api/v1/description/353/'}

用完整的代码更新

import requests
import json

BASE_URL = 'http://pokeapi.co'


def query_pokeapi(resource_url):
    url = '{0}{1}'.format(BASE_URL, resource_url)
    response = requests.get(url)

    if response.status_code == 200:
        return json.loads(response.text)
    return None

charizard = query_pokeapi('/api/v1/pokemon/')
print charizard['objects'][0]['descriptions'][0]

结果将是:

{u'name': u'ekans_gen_1', u'resource_uri': u'/api/v1/description/353/'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM