Reputation: 117
I'm having an issue related to parsing a JSON response of the Instagram API, but I believe it's a general Python thing (I'm a n00b).
I'm building a Django app. When an authenticated user makes a comment on Instagram, I want to store some data related to it. The code below works when I hardcode the username in the for loop at the bottom (i.e. sub_item['from']['username'] == 'hansolo'
).
However, the function fails to find and save any new data when I replace the hardcoded username with a variable that stores the same string. i.e. sub_item['from']['username'] == ig_username, where ig_username = 'hansolo'
.
if form.is_valid():
instance = form.save(commit=False)
user = request.user
instance.user = user
ig_username = str(user)
print ig_username # for debugging
print 'hansolo' # for debugging
client_id = "[hidden]"
client_secret = "[hidden]"
access_token = "[hidden]"
api = InstagramAPI(client_id=client_id, client_secret=client_secret, access_token=access_token)
# Get list of recently liked media from authenticated user
api_call_likes = 'https://api.instagram.com/v1/users/self/media/liked?access_token=' + access_token
r = requests.get(api_call_likes)
json_data = r.json()
for item in json_data['data']:
for sub_item in item['comments']['data']:
if sub_item['from']['username'] == ig_username and 'keyword' in sub_item['text']:
# save some data
When I print the ig_username variable in the terminal (line 6), it prints the exac same string as the hardcoded username (line 7, i.e. hansolo).
Why would the string variable fail, but the hardcoded string work? By "fail," I mean data is not found and saved.
Upvotes: 1
Views: 343
Reputation: 599926
If you want to compare with the username, you should do that, rather than comparing with the string representation of the User object; they may be the same, but they probably aren't.
ig_username = user.username
Also, not related to your problem but you should really use the Instagram Python library, which makes this sort of thing a bit easier.
Upvotes: 2