def builder(filename, limit=10, start=0, end=5): with open(filename) as srcfile: template = json.load(srcfile) # forma el URL a partir de los argumentos recibidos. full_url = '{}{}?page={}&limit={}'.format(PROTOCOL, SAPI_URL, start, limit) end_page = 'page={}'.format(end) print(full_url) # aquí hace falta un *do-while*, # pero claro, Python no tiene uno. [PEP315] while True: jcontent = _get_json_content(full_url) news_list = jcontent['news'] for news in news_list: news_dict = _get_news(PROTOCOL + news['href']) # busca la categoría; # si no existe, devuelve *None*. category = news['category'] topic_list = template['topic-list'] gen = (cat for cat in topic_list if _unique_key(cat) == category) cat = next(gen, None) if cat: # agrega la noticia a la categoría existente. key = _unique_key(cat) cat[key].append(news_dict) else: # agrega la nueva categoría con su noticia. print("Nueva categoría:", category) topic_list.append({category: [news_dict]}) # input() # pprint.pprint(template) # por último, revisa si es que hay más noticias. next_url = jcontent['next'] if end_page in next_url: print("Hemos llegado a la página solicitada.") break elif 'page=0' in next_url: print("No hay más noticias.") break else: full_url = PROTOCOL + next_url # pprint.pprint(template) dolphinq.enqueue(template)
def builder(filename): # filename % nombre del archivo con los NoRSS list. # obtiene todos los *sources* a partir del archivo. Si bien ahora hay 1 NoRSS, se deja de esta manera para mantener extensibilidad. with open(filename) as srcfile: all_sources = [source for source in json.load(srcfile)] for source in all_sources: for topic in source['topic-list'][:]: # forma el URL del *feed*. feed_url = source['beg-url'] + topic + source['end-url'] news_list = _emol_news_list_reader(feed_url, source['list-keyword'], topic) # agrupa el tema con la lista asociada de noticias; # luego, lo reemplaza por el tema que viene vacío. ndict = {topic: news_list} index = source['topic-list'].index(topic) source['topic-list'][index] = ndict for news in news_list: # agrega el contenido de cada noticia. news['content'] = _emol_news_reader(news['link'], source['keyword']) if news['content'] == "[]": news_list.remove(news) # print(news['title']) # input("Presione ENTER para continuar.\n") # Check if there are no new news, to not send empty messages new_news = False for topic_dict in source['topic-list']: list_per_topic = topic_dict.popitem() if list_per_topic and list_per_topic[1]: new_news = True break if new_news: # elimina las llaves innecesarias. source.pop('id') source.pop('beg-url') source.pop('end-url') source.pop('keyword') source.pop('list-keyword') dolphinq.enqueue(source)
def builder(filename): # filename % nombre del archivo con los *feeds*. # ####################################################### # Este método busca aprovechar el diccionario subyacente, # que se obtiene a partir del archivo JSON. # Luego, sólo se debe agregar las noticias, # que serían los datos faltantes. # ############################### # obtiene todos los *sources* a partir del archivo. with open(filename) as srcfile: all_sources = [source for source in json.load(srcfile)] # herramienta para imprimir largos diccionarios. pp = pprint.PrettyPrinter(width=120) pp.pprint(all_sources) for source in all_sources: for topic in source['topic-list'][:]: # noticias recientes, ergo no-duplicadas. recent_news = [] with open(source['id'] + '.txt') as histfile: all_news = histfile.read().splitlines() # forma el URL del *feed*. feed_url = source['beg-url'] + topic[0] + source['end-url'] try: news_list = _feed_reader(feed_url) except Exception as err: news_list = [] print() print("# ###################") print("# Feed no disponible.") print("# URL:", feed_url) print("# ERR:", err) print() # obtiene la lista de noticias ya vistas. for news in news_list[:]: # agrega el contenido de cada noticia. link = news['link'] print(link) # print(all_news) if link in all_news: news_list.remove(news) else: news['content'] = _news_reader(link, source['keyword']) recent_news.append(link) print(news['title']) # pp.pprint(all_sources) # input("Presione ENTER para continuar.\n") # agrupa el tema con la lista asociada de noticias; # luego, lo reemplaza por el tema que viene vacío. ndict = {topic[1]: news_list} index = source['topic-list'].index(topic) source['topic-list'][index] = ndict # pprint.pprint(source) # actualiza el historial de noticias ya extraídas. with open(source['id'] + '.txt', 'a') as histfile: for link in recent_news: histfile.write(link + '\n') # elimina las llaves innecesarias. source.pop('id') source.pop('beg-url') source.pop('end-url') source.pop('keyword') # finalmente, encola las noticias de este *source*. dolphinq.enqueue(source)