Skip to content

Commit f2e1c31

Browse files
committed
Safely fetch entry data, by checking availability before calling
1 parent f04d178 commit f2e1c31

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

instagram/models.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -68,25 +68,28 @@ def object_from_dictionary(cls, entry):
6868
new_media.user = User.object_from_dictionary(entry['user'])
6969

7070
new_media.images = {}
71-
for version, version_info in six.iteritems(entry['images']):
72-
new_media.images[version] = Image.object_from_dictionary(version_info)
71+
if entry.get('images'):
72+
for version, version_info in six.iteritems(entry['images']):
73+
new_media.images[version] = Image.object_from_dictionary(version_info)
7374

74-
if new_media.type == 'video':
75+
if new_media.type == 'video' and entry.get('videos'):
7576
new_media.videos = {}
7677
for version, version_info in six.iteritems(entry['videos']):
7778
new_media.videos[version] = Video.object_from_dictionary(version_info)
7879

79-
if 'user_has_liked' in entry:
80+
if entry.get('user_has_liked'):
8081
new_media.user_has_liked = entry['user_has_liked']
81-
new_media.like_count = entry['likes']['count']
82+
83+
new_media.like_count = entry.get('likes', {}).get('count', 0)
8284
new_media.likes = []
83-
if 'data' in entry['likes']:
84-
for like in entry['likes']['data']:
85-
new_media.likes.append(User.object_from_dictionary(like))
85+
if new_media.like_count:
86+
if entry.get('likes', {}).get('data'):
87+
for like in entry['likes']['data']:
88+
new_media.likes.append(User.object_from_dictionary(like))
8689

8790
new_media.comment_count = entry.get('comments', {}).get('count', 0)
91+
new_media.comments = []
8892
if new_media.comment_count:
89-
new_media.comments = []
9093
if entry.get('comments', {}).get('data'):
9194
for comment in entry['comments']['data']:
9295
new_media.comments.append(Comment.object_from_dictionary(comment))
@@ -98,15 +101,15 @@ def object_from_dictionary(cls, entry):
98101

99102
new_media.created_time = timestamp_to_datetime(entry['created_time'])
100103

101-
if entry['location'] and 'id' in entry:
104+
if entry.get('location') and entry.get('id'):
102105
new_media.location = Location.object_from_dictionary(entry['location'])
103106

104107
new_media.caption = None
105-
if entry['caption']:
108+
if entry.get('caption'):
106109
new_media.caption = Comment.object_from_dictionary(entry['caption'])
107110

108111
new_media.tags = []
109-
if entry['tags']:
112+
if entry.get('tags'):
110113
for tag in entry['tags']:
111114
new_media.tags.append(Tag.object_from_dictionary({'name': tag}))
112115

0 commit comments

Comments
 (0)