0

I am using instagram API, and this is my code;

from instagram.client import InstagramAPI
api = InstagramAPI(access_token='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
tagname = 'naturelover'

photo_urls = []

def get_urls( skeyword, next_max_id=None ):

    tags_recent_media, next = api.tag_recent_media( max_id=next_max_id, tag_name = "%s"%skeyword )
    if tags_recent_media:
        [photo_urls.append(media.images['standard_resolution'].url) for media in tags_recent_media]
        if next is None:
            pass
        else:
            if next.find('max_id') == -1:
                next_max_id = next.split('max_tag_id=')[1]
                next_page_id="%s"%next_max_id.split('&')[0]
            else:
                next_max_id = next.split('max_id=')[1]
                if next_max_id.split('&'):
                    next_page_id="%s"%next_max_id.split('&')[0]

            get_urls( skeyword, next_page_id )
    else:
        pass
    return photo_urls

tag_media_data = get_urls(tagname,inc)
mongo.insert({'media':tag_media_data})

On every single request instagram returns 2o max images, and a next URL for pagination, i am trying to store all images based on tag for this i have to call function recursively until next url is not none, here next is a url and i sliced it to fetch next url id (instagram api support next id for pagination). But I got a max recursion call error, searching for this error i got some answers like set value for stackrecursion but that doesn't make sense in terms of logic. I am not finding any solution on this for how to break recursion after some recursion calls or any other alternative way.

In the end of code, i saved all of list data in a single mongo document, other way i saved data after every recursion call by doing this i got redundant data in every document like this:

photo_urls = []
[photo_urls.append(media.images['standard_resolution'].url) for media in tags_recent_media]
mongo.insert({'media':photo_urls})

I couldn't find other way still, i am trying to do this in other way, please point out if this problem needs to be more descriptive.

4

1 回答 1

1

递归始终可以表示为显式循环。考虑这种方法:

next_page_id = None
while True:
  tags_recent_media, next = api.tag_recent_media(keyword, next_page_id)
  extractImagesFrom(tags_recent_media)
  if not next:
    break
  next_page_id = ...

我敢打赌,这就是 API 作者的意思。

于 2013-11-01T03:28:25.100 回答