KeyError: 'data' with Python Instagram API client

KeyError: 'data' with Python Instagram API client

我在 MacOS 上与 Python 3.4.3 一起使用此客户端 python-instagram

这是我的步骤:

我按照 Sample app, I successfully authorized my app via instagram and tried this list of examples 上的说明进行操作,但其中 none 行得通。在我点击 <h2> header 和 API 请求的计数器后,我看到 Remaining API Calls = 486/500.

如果我尝试获取 User Recent Media,我的终端中会显示异常 KeyError: 'data'。如果我删除 try - except 构造,在 try 中留下块,当我看到 'Error: 500 Internal Server Error'.

这是回溯:

Traceback (most recent call last):
File "/Users/user/.envs/insta/lib/python3.4/site-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/Users/user/.envs/insta/lib/python3.4/site-packages/bottle.py", line 1732, in wrapper
rv = callback(*a, **ka)
File "sample_app.py", line 79, in on_recent
recent_media, next = api.user_recent_media()
File "/Users/user/.envs/insta/lib/python3.4/site-packages/instagram/bind.py", line 197, in _call
return method.execute()
File "/Users/user/.envs/insta/lib/python3.4/site-packages/instagram/bind.py", line 189, in execute
content, next = self._do_api_request(url, method, body, headers)
File "/Users/user/.envs/insta/lib/python3.4/site-packages/instagram/bind.py", line 151, in _do_api_request
obj = self.root_class.object_from_dictionary(entry)
File "/Users/user/.envs/insta/lib/python3.4/site-packages/instagram/models.py", line 99, in object_from_dictionary
for comment in entry['comments']['data']:
KeyError: 'data'

我使用的所有代码均来自Instagram官方pythonAPI客户端的示例。

models.py 中似乎存在错误。如果您注释掉该文件中的第 99 行和第 100 行,"sample app" 将起作用,或者至少看起来起作用。显然,这不是 "real" 修复,但它确实表明它不是示例 Python 程序或 Instagram 的问题。

    Line 99  #  for comment in entry['comments']['data']:
    Line 100 #      new_media.comments.append(Comment.object_from_dictionary(comment))

有一个打开的 Github issue for this bug, a fix 已发送,但尚未合并。

将一行修复程序添加到已安装软件包的 models.py

用 sudo 打开:

sudo vi /Library/Python/2.7/site-packages/instagram/models.py  # Use relevant python version 

在第 99 行添加:

if "data" in entry["comments"]:

更正下两行的缩进:

       for comment in entry['comments']['data']: 
           new_media.comments.append(Comment.object_from_dictionary(comment))

+1 来自@forge 的回答

对于 docker 用户(如评论中所述),fork python-instagram 存储库,编辑,然后通过 github.

进行 pip 安装

或者在您的 Dockerfile 中使用其他人的 fork 并添加以下行:

pip install git+https://github.com/zgazak/python-instagram

当您在 docker 等环境或没有可读终端的环境中工作时,这并不是真正的答案,只是基于@forge 的回答的快速解决方法。

sed -i '99,100 s/^/#/' /usr/local/lib/python3.5/site-packages/instagram/models.py