python - Is my application of a generator wrong here? -
i'm using facebook api , looking @ reactions post. fb limits responses max of 100 records puts pagination next lot etc.
my test case has on 100 reactions (last count: 550) . want returned list of tuples each tuple reaction post.
here have far... output list on 100 less expected-
import requests def get_next_linksv3(page): while true: #try: r = requests.get(page) r_json = r.json() if 'paging' in r_json.keys() , 'next' in r_json['paging']: page = r_json['paging']['next'] yield page else: return def process_follow_on_reactions_link(next_link, list_reaction_tuples): nr = requests.get(next_link) r_json = nr.json() tmp_list = [] if 'data' in r_json.keys(): nrecord in r_json['data']: reaction_id = nrecord['id'] reaction_id_name = nrecord['name'] reaction_type = nrecord['type'] tmp_list.append((reaction_id,reaction_id_name,reaction_type)) return tmp_list def process_initial_reactions_link(link): list_reaction_tuples = [] r = requests.get(link) r_json = r.json() if 'reactions' in r_json.keys(): record in r_json['reactions']['data']: reaction_id = record['id'] reaction_id_name = record['name'] reaction_type = record['type'] list_reaction_tuples.append((reaction_id,reaction_id_name,reaction_type)) if 'reactions' in r_json.keys() , 'paging' in r_json['reactions'] , 'next' in r_json['reactions']['paging']: next_link = r_json['reactions']['paging']['next'] gen = get_next_linksv3(next_link) while true: try: list_reaction_tuples = list_reaction_tuples + (process_follow_on_reactions_link(next(gen), list_reaction_tuples)) except stopiteration: return list_reaction_tuples return list_reaction_tuples tuple_list = process_initial_reactions_link(target_link)
it may hang waiting data or spin in loop. in while true
loop. when gets incorrect (or producing other output desired) url (the if
condition not satisfy), generator downloads same page , never yields. may want introduce max_retries
variable instead of while true
loop.
run program under debugger , pinpoint hangs. if impossible - use simple print-debugging method. , show trace.
Comments
Post a Comment