def generate_rss(content, project=""): title = "OpenStack %s watch RSS feed" % (project) rss = PyRSS2Gen.RSS2( title=title, link="http://github.com/chmouel/openstackwatch.rss", description="The latest reviews about OpenStack, straight " "from Gerrit.", lastBuildDate=datetime.datetime.now() ) for row in parse_json(content): author = row['owner']['name'] author += " <%s>" % ('email' in row['owner'] and row['owner']['email'] or row['owner']['username']) rss.items.append( PyRSS2Gen.RSSItem( title="%s [%s]: %s" % (os.path.basename(row['project']), row['status'], row['subject']), author=author, link=row['url'], guid=PyRSS2Gen.Guid(row['id']), description=row['subject'], pubDate=datetime.datetime.fromtimestamp(row['lastUpdated']), )) return rss.to_xml()
def writeRSS2file(inputitems): """Writes actual feeds to a file on disk. Makes use of a 3rd party module --PyRSS2Gen. keyword arguments: inputitems --list containing absolute file paths to feeds """ print "START: FEED GENERATOR[WRITING]: ", time.time() feed_items = [] for item in inputitems: print "appending... ", item feed_items.append(RSS2format(item)) rss = PyRSS2Gen.RSS2(title="A File-based RSS Feed Generator", link="lphiri.cs.uct.ac.za/simplyct", description="A File-based RSS Feed Generator", lastBuildDate=datetime.utcnow(), items=feed_items) print "DEBUGGING feed_items... -> ", feed_items for l in feed_items: pprint(vars(l)) print "DEBUGGING rss object... -> ", rss rss.write_xml(open("new-simplyctrss2.xml", "w")) print "END: FEED GENERATOR[WRITING]: ", time.time()
def gen_rss(self): rss_item = [] for news in self.info: # print(news) item = PyRSS2Gen.RSSItem( title=news['title'], link=news['url'], description=news['title'], pubDate=arrow.get(news['lastupdatetime']).format('YYYY-MM-DD')) rss_item.append(item) rss = PyRSS2Gen.RSS2(title="scurss feed", link="http://scurss.les1ie.com", description=" 四川大学校内新闻聚合平台", lastBuildDate=datetime.datetime.now(), items=rss_item) rss.write_xml(open("./web/feed.xml", "w")) # 修改格式 f = open("./web/feed.xml", 'r') con = f.read() f.close() con = con.replace("iso-8859-1", 'utf-8') f = open('./web/feed.xml', 'w') f.write(con) f.close()
def blog_rss(): if not env.owner or not env.owner.id: raise UserNotFound if env.owner.type == 'feed': raise Forbidden plist = posts.recent_blog_posts(env.owner, settings.page_limit, 0) feed = PyRSS2Gen.RSS2(title="%s@point" % env.owner.login, link='http://%s.%s/' % (env.owner.login, settings.domain), description="Point.im user's blog") for p in plist: if 'comment_id' in p and p['comment_id']: title = '#%s/%s' % (p['post'].id, p['comment_id']) link = 'http://%s/%s#%s' % \ (settings.domain, p['post'].id, p['comment_id']) else: title = '#%s' % p['post'].id link = 'http://%s/%s' % (settings.domain, p['post'].id) feed.items.append( PyRSS2Gen.RSSItem(author=env.owner.login, title=title, link=link, guid=link, pubDate=p['post'].created, categories=p['post'].tags, description=render_string('/rss-text.html', p=p))) return Response(feed.to_xml(), mimetype='application/rss+xml')
async def rss(request): engine = DatabaseContext.default.engine async with engine.acquire() as connection: topic_dao = TopicDAO(connection) topics = await topic_dao.latest100() rss = PyRSS2Gen.RSS2( title="DOIST", link="https://doist.cn/", description=u"实干家", lastBuildDate="", items=[ PyRSS2Gen.RSSItem( title=topic['title'], link="https://doist.cn/t/%d" % (topic['id'], ), description=markdown.markdown( bleach.clean(topic['content']), extensions=['markdown.extensions.tables']), guid="https://doist.cn/t/%d" % (topic['id'], ), pubDate=topic['created_at'], ) for topic in topics ]) response = web.StreamResponse(headers={'Content-Type': 'text/xml'}) await response.prepare(request) buf = StringIO() rss.write_xml(buf, 'utf-8') await response.write(buf.getvalue().encode('utf-8')) return response
def rss_page(request, username=None): puser = get_object_or_404(User, username=username, is_active=True) notes = puser.notes.order_by('-date_created')[:10] rssurl = request.build_absolute_uri( reverse('blog_page', kwargs={'username': username})) last_build = None items = [] for note in notes: if (last_build is None or last_build < note.date_created): last_build = note.date_created note_url = note.get_absolute_url() rssitem = PyRSS2Gen.RSSItem(title=note.title, link=note_url, description=note.get_html_content(), guid=PyRSS2Gen.Guid(note_url), pubDate=note.date_created) items.append(rssitem) if last_build is None: last_build = datetime.now() # render the rss rss = PyRSS2Gen.RSS2(title=u"%s's notes" % puser.username, link=rssurl, description='%s' % puser.username, lastBuildDate=last_build, items=items) resp = HttpResponse(rss.to_xml()) resp.content_type = 'application/rss+xml' return resp
def main(self, url=None, authText=None): auth = self.processAuthText(authText) req = r.request('GET', url, auth=auth) (docTitle, items) = self.parseResponse( req.text ) rssItems = [PyRSS2Gen.RSSItem(t,l,d) for (t,l,d) in items] rss = PyRSS2Gen.RSS2( title=docTitle, link=DOCLINK, description=docTitle, items=rssItems ) return rss.to_xml()
def rss(): validate_token() client = asana.Client.access_token(os.environ['ASANA_TOKEN']) client.headers = {'asana-enable': 'string_ids'} project_gid = os.environ['ASANA_PROJECT_GID'] items = [] for task in fetch_tasks(): items.append( PyRSS2Gen.RSSItem( title=task['name'], link= "http://www.dalkescientific.com/news/030906-PyRSS2Gen.html", guid=task['id'], pubDate=datetime.datetime.now())) rss = PyRSS2Gen.RSS2( title="Asana project RSS", link="http://www.dalkescientific.com/Python/PyRSS2Gen.html", description='Tasks', lastBuildDate=datetime.datetime.now(), items=items) buffer = StringIO.StringIO() rss.write_xml(buffer) return buffer.getvalue()
def Build_RSS(r_path, r_filename, r_home, r_desc): # Setup RSS t_delta = datetime.timedelta(hours=9) rss = PyRSS2Gen.RSS2(title=r_filename, link=r_home, description=r_desc, lastBuildDate=datetime.datetime.utcnow(), items=[]) # Read DB for Current RSS CurData = MariaDB.ReadSQL(r_filename) # Append Item to RSS for r in CurData: item = PyRSS2Gen.RSSItem(title=r['title'], link=r_home + r['url'], guid=PyRSS2Gen.Guid(r_home + r['url']), description=str(r['text']), pubDate=r['pubdate'] - t_delta, author=r['author']) rss.items.append(item) # Write RSS rss.write_xml(open(r_path + "rss_" + r_filename + ".htm", 'w', encoding='utf-8'), encoding="utf-8")
def users_rss_public(user_id): import datetime import PyRSS2Gen as RSS2 try: user = User.objects(id=user_id)[0] except IndexError: return 'Wrong user ID!' else: notes = Note.objects(user=user, private=False).order_by('-created_at')[:20] notes_items = [] for note in notes: notes_items.append( RSS2.RSSItem(title=note.title, link=note.get_url_rss(), description=note.get_dropbox_content(), guid=RSS2.Guid("http://jabjot.com/notes/" + str(note.id)), pubDate=note.created_at)) rss = RSS2.RSS2(title=user.username + "'s public notes feed - jabjot", link="http://jabjot.com/user/rss/" + str(user.id), description=user.username + "'s latest public notes.", lastBuildDate=datetime.datetime.utcnow(), items=notes_items) return rss.to_xml(encoding='utf-8')
def feed_latest(request): entry = EntryDetail() entries = entry.get_queryset().filter( status=PUBLISHED).order_by('-creation_date')[:50] for entry in entries: if entry.entry_type == TYPE_ANNOUNCEMENT: url = entry.get_absolute_url().replace('/blog/', '/announcement/') entry.urls = url else: entry.urls = entry.get_absolute_url() items = [] for entry in entries: link = "%s%s" % (settings.BASE_URL, entry.urls) enclosure = None if entry.image: enclosure = PyRSS2Gen.Enclosure(entry.image.url, 1024, 'image/jpeg') item = PyRSS2Gen.RSSItem(title=entry.title, link=link, guid=PyRSS2Gen.Guid(link), enclosure=enclosure, pubDate=entry.creation_date) items.append(item) rss = PyRSS2Gen.RSS2(title='newtonproject.org', link="%s/feed/" % settings.BASE_URL, description="newtonproject", lastBuildDate=datetime.datetime.now(), docs='%s/about/' % settings.BASE_URL, items=items) rss.rss_attrs['xmlns:atom'] = 'http://www.w3.org/2005/Atom' xml = rss.to_xml(encoding='UTF-8') return HttpResponse(xml, mimetype='application/rss+xml;charset=utf-8')
def make_video_rss(fh, eps): items = [] for ep in eps: info = PyRSS2Gen.RSSItem( title=ep.name, description=ep.description, guid=PyRSS2Gen.Guid(ep.conf_url), pubDate=ep.end, link=ep.conf_url, enclosure=PyRSS2Gen.Enclosure( url= 'http://meetings-archive.debian.net/pub/debian-meetings/%s/%s/%s.webm' % (ep.end.year, ep.show.slug, ep.slug), length=os.stat( '/home/veyepar/Videos/veyepar/%s/%s/webm/%s.webm' % (ep.show.client.slug, ep.show.slug, ep.slug)).st_size, type='video/webm', )) items.append(info) rss = PyRSS2Gen.RSS2(title="Debconf 16 video RSS feed", link="https://debconf16.debconf.org", description="The published videos from Debconf 16", lastBuildDate=datetime.datetime.now(), items=items) rss.write_xml(fh, encoding='UTF-8')
def write_rss(posts, filename): rss_items = [] for post in posts: if 'link' in post.meta: the_link = post.meta['link'] html = post.html + u"\n\n<p><strong><a href='%s'>β</a></strong></p>" % post.get_absolute_url( ) else: the_link = post.get_absolute_url() html = post.html item = PyRSS2Gen.RSSItem( title=post.meta['title'], link=the_link, description=html, # Temporary fix: I'm on Brussels time, which is 2 hours ahead of # UTC. Proper timezone support will be added later. pubDate=post.meta['pubdate'] - datetime.timedelta(0, 0, 0, 0, 0, 2, 0), ) rss_items.append(item) rss = PyRSS2Gen.RSS2( title="bjornssaga.com", link="http://bjornssaga.com", description="Latest entries from bjornssaga.com", lastBuildDate=posts[0].meta['pubdate'] - datetime.timedelta(0, 0, 0, 0, 0, 2, 0), items=rss_items, ) rss_file = open(filename, "w") rss.write_xml(rss_file) rss_file.close()
def create(self): items = list() for info in self.target_info: items.append( PyRSS2Gen.RSSItem( title=info[1], link=self.target_link.split('.com')[0] + '.com' + '/' + info[0].strip('/') + '/' if 'http' not in info[0] else info[0], description=info[2] if len(info) == 3 else info[1]), ) rss = PyRSS2Gen.RSS2(title=self.target_title, link=self.target_link, description=self.target_description, lastBuildDate=datetime.datetime.now(), items=items) if self.xml_name: filename = '{}'.format(self.xml_name) rss.write_xml(open(BASE_DIR + '/feed/templates/xml_html/{}'.format(filename), 'w', encoding='utf-8'), encoding='utf-8') else: filename = '{}.xml'.format(str(int(time.time()))) rss.write_xml(open(BASE_DIR + '/feed/templates/xml_html/{}'.format(filename), "w", encoding='utf-8'), encoding='utf-8') return filename
def buildRssLevel2(folder,xml,list): #Creation of the rss rss = PyRSS2Gen.RSS2( title = "TV Show Paradize RSS Feed : "+folder.capitalize(), link = "https://fi08.us.to/"+folder, description = "The latest "+xml.capitalize()+" of the server", lastBuildDate = datetime.datetime.now(), ) #Creating item for item in list: filedate = item[0] filename = item[1] info = item[2] path = item[3] rss.items.append( PyRSS2Gen.RSSItem( title = info, link = http_dir + folder + "/" + path + filename, description = info, guid = PyRSS2Gen.Guid(http_dir + folder + "/" + path + filename), pubDate = filedate ) ) # Write ! rss.write_xml(open(xml_dir+xml+".xml", "w"))
def get_rss(content): soup = BeautifulSoup(content).contents[0] myrss = PyRSS2Gen.RSS2( title='91ri', link='http://www.91ri.org/', atom_link='http://117.28.237.21:29956/ording/resource/91ri.xml', description=str(datetime.date.today()), # pubDate=datetime.datetime.now(), lastBuildDate=datetime.datetime.now(), language="zh-CN", items=[]) for x in xrange(0, len(soup)): print soup.contents[x].find_all( attrs={"data-no-turbolink": "true"})[0].get('href') print soup.contents[x].find_all( attrs={"data-no-turbolink": "true"})[0].string # print soup.contents[x].p.get_text() rss = PyRSS2Gen.RSSItem( title=soup.contents[x].find_all( attrs={"data-no-turbolink": "true"})[0].string, link=soup.contents[x].find_all( attrs={"data-no-turbolink": "true"})[0].get('href'), comments=soup.contents[x].find_all( attrs={"data-no-turbolink": "true"})[0].get('href') + "#comments", pubDate=datetime.datetime.now(), description=soup.contents[x].p.string) myrss.items.append(rss) return myrss
def feed(): prefix = '://'.join(request.urlparts[:2]) title = 'Malaysian Bill Watcher' link = prefix+'/' description = ''' This is an app for Malaysian to see bill being passed by the Parliament ''' lastBuildDate = datetime.datetime.utcnow() li = [] bls = select([bills,bill_revs],bills.c.id==bill_revs.c.bill_id).\ order_by('update_date') conn = engine.connect() result = conn.execute(bls) bill = result.fetchall() for i in bill: i_title = i['long_name'] i_description = "year:%s \nstatus: %s" % (i['year'],i['status']) i_link = prefix+'/detail/%s/' % (i['bill_id']) i_pubDate = i['update_date'] i_guid = PyRSS2Gen.Guid(i_link) itm = PyRSS2Gen.RSSItem(title=i_title,description=i_description, link=i_link,guid=i_guid,pubDate=i_pubDate) li.append(itm) rss = PyRSS2Gen.RSS2(title=title,link=link,description=description, items = li) output = cStringIO.StringIO() rss.write_xml(output) response.content_type = 'application/rss+xml' return output.getvalue()
def filter_feed(name): try: feed = known_feeds[name] except KeyError: return abort(404) fifteen_minutes_ago = dt.datetime.utcnow() - dt.timedelta(minutes=15) if name not in feed_cache or feed_cache[ name].lastBuildDate < fifteen_minutes_ago: logging.info("feed_cache miss") input_feed = feedparser.parse(feed.url) output_feed = rss.RSS2( title=input_feed["feed"]["title"], link=input_feed["feed"]["link"], description=input_feed["feed"]["subtitle"], lastBuildDate=dt.datetime.utcnow(), items=[ build_rss_item(entry) for entry in include_items( remove_items(input_feed["entries"], title_includes=feed.title_disqualifiers), title_includes=feed.title_qualifiers, ) ], ) feed_cache[name] = output_feed else: logging.info("feed_cache hit") return feed_cache[name].to_xml()
def generate_feed(self): xml_path = os.path.join(XML_DIR, 'caixin_rss.xml') # Find latest articles and convert into rss format articles_of_this_issue = list( db.articles.find({'date': self.latest_issue_date})) for article in articles_of_this_issue: article['description'] = article['content_html'] article['pubDate'] = datetime.datetime.strptime( article['date'], '%Y-%m-%d') del article['date'] del article['content'] del article['content_html'] del article['_id'] del article['length'] rss_items = [ PyRSS2Gen.RSSItem(**item) for item in articles_of_this_issue ] rss = PyRSS2Gen.RSS2( title="Caixin Weekly {}".format(self.latest_issue_date), link="Somewhere", description="Caixin Weekly full text", lastBuildDate=datetime.datetime.now(), items=rss_items, ) with open(xml_path, "wb") as rss_path: rss.write_xml(rss_path)
def buildFeed(feed_title, feed_link, feed_desc, feed_posts, feed_path): rss = PyRSS2Gen.RSS2(title=feed_title, link=feed_link, description=feed_desc, lastBuildDate=datetime.datetime.now(), items=feed_posts) rss.write_xml(open(feed_path + "/rss.xml", "w+"))
def all_posts_rss(): plist = posts.select_posts(private=False, author_private=False, deny_anonymous=False, blacklist=True, limit=settings.page_limit * 4) feed = PyRSS2Gen.RSS2(title="Point.im", link='http://%s/' % (settings.domain), description="Point.im") for p in plist: if 'comment_id' in p and p['comment_id']: title = '#%s/%s' % (p['post'].id, p['comment_id']) link = 'http://%s/%s#%s' % \ (settings.domain, p['post'].id, p['comment_id']) else: title = '#%s' % p['post'].id link = 'http://%s/%s' % (settings.domain, p['post'].id) feed.items.append( PyRSS2Gen.RSSItem(author=env.owner.login, title=title, link=link, guid=link, pubDate=p['post'].created, categories=p['post'].tags, description=render_string('/rss-text.html', p=p))) return Response(feed.to_xml(), mimetype='application/rss+xml')
def __init__(self): self.myrss = PyRSS2Gen.RSS2( title='MyFeed', link='http://my.webserver.net', description=str(datetime.date.today()), pubDate=datetime.datetime.now(), lastBuildDate = datetime.datetime.now(), items=[] ) self.xmlpath=r'/usr/share/nginx/kodexplorer/MyFeed1.xml' self.baseurl="https://www.youtube.com/feed/subscriptions?flow=2" self.homepage="https://www.youtube.com" self.proxies = { 'http': 'http://127.0.0.1:8087', 'https': 'http://127.0.0.1:8087' } self.cookies = { "LOGIN_INFO" : "AFmmF2swRQIhAJPGsor9NtKhUeObwZBpB0hRmLztAmb2VCRwnbwynOIPAiAaEspBwqvQOpzYq0E235he7lCSGwFwyZq6gXvk-T8lfw:QUQ3MjNmeFZJSGhFVjAtcjI4RDExY3Z4aGM3c2dpUV9xTE1LaUNYbkM5RmxBcVZvaktyNkdhYjFuSnZNVXBRNEVhX25EQkJPU3pCbDZ5eE1SMjF6V0I2WjZXcnBOR20tSHJPWmJJNXZ5UHN1dFFaS3hkUDU2bnVuX3ZnZHdoTlVkUFFIeFpnUHRqMnJmYk91OG54VVZXQ1VpZk0wc2lFZ1FGZFpsVEpGRTFlTGFyVHB2cW8yRXFn", "SSID" : "ARVUYoQRS4jgCnOSM", "PREF" : "cvdm=grid&gl=RU&hl=zh-CN&al=zh-CN&f5=30010&f3=8&f1=50000000", "APISID" : "pzgp73ur0ncYC5_J/AXc30is2ZtkrrT92N", "SID" : "dQeUixcwYgp0gLhHCtM-pPCkqFmqefZSEiGX5_JGd--IpXhBnhHNZiKxNWeNHxsqhA93bA.", "SAPISID" :"b3rc-b0aeLqIsiq8/A5lOZ81fbgz6IgtoL", "HSID" : "AuckWm5oDP-hZftQ7", "VISITOR_INFO1_LIVE" :"B3Yo-e7P-Os", "YSC" : "a9uVrHIIxVg", "_ga" : "GA1.2.306650520.1543678480", "s_gl" : "1d69aac621b2f9c0a25dade722d6e24bcwIAAABVUw==", }
def get_rss2_from_feed(self, feed, entries): rss_feed = PyRSS2Gen.RSS2( title=feed.get('title'), link=feed.get('link'), description=feed.get('subtitle'), language=feed.get('language'), copyright=feed.get('rights'), managingEditor=self.get_first( self.get_keys(feed.get('contributors'), 'name')), webMaster=feed.get('publisher'), pubDate=self.date_tuple_to_datetime(feed.get('published_parsed')), lastBuildDate=self.date_tuple_to_datetime( feed.get('updated_parsed')), categories=self.get_keys(feed.get('tags'), 'term'), generator=feed.get('generator'), docs=feed.get('docs'), cloud=feed.get('cloud'), ttl=feed.get('ttl'), image=feed.get('image'), rating=None, textInput=feed.get('textinput'), skipHours=None, skipDays=None, items=[self.get_rss_item_for_entry(entry) for entry in entries], ) rss_feed.source_entity = feed return rss_feed
def _create_rss_file(resultslist): failureitems = [] for (runnumber, revision, resulttext) in resultslist: if resulttext[0].strip() != "SUCCESS": datestr = resulttext[1].strip() dateobj = datetime.datetime.strptime(datestr, "%Y-%m-%d %H:%M:%S") # The PyRSS2Gen module expects this to be in GMT, and python is a pain # for timezone conversion. I'll just hard code assuming the system's in # PST and ignore daylight savings time. dateobj += datetime.timedelta(hours=8) item = PyRSS2Gen.RSSItem( title="Test failure on run number " + str(runnumber) + " using " + revision, link=config.TESTLOG_URL, description="\n".join(resulttext), # Spaces aren't valid in a guid. guid=PyRSS2Gen.Guid(config.TESTLOG_URL + str(runnumber)), pubDate=dateobj) failureitems.append(item) rss = PyRSS2Gen.RSS2( title="Test Failures on " + config.SYSTEM_DESCRIPTION, link=config.TESTLOG_URL, description="Seattle test failures for continuous build on " + config.SYSTEM_DESCRIPTION, lastBuildDate=datetime.datetime.now() + datetime.timedelta(hours=8), items=failureitems) rss.write_xml(open(config.RSS_FILE_NAME + ".new", "w")) os.rename(config.RSS_FILE_NAME + ".new", config.RSS_FILE_NAME)
def generate(self): md = markdown.Markdown() items = [] for row in (Comment.select().where( Comment.published).order_by(-Comment.published).limit(10)): item_link = "%s://%s%s" % (self._rss_proto, self._site_url, row.url) items.append( PyRSS2Gen.RSSItem( title="%s - %s://%s%s" % (self._rss_proto, row.author_name, self._site_url, row.url), link=item_link, description=md.convert(row.content), guid=PyRSS2Gen.Guid("%s/%d" % (item_link, row.id)), pubDate=row.published, )) rss_title = 'Commentaires du site "%s"' % self._site_name rss = PyRSS2Gen.RSS2( title=rss_title, link="%s://%s" % (self._rss_proto, self._site_url), description=rss_title, lastBuildDate=datetime.now(), items=items, ) rss.write_xml(open(self._rss_file, "w"), encoding="utf-8")
def generic_rss_renderer(lang, title, link, description, timeline, output_path): """Takes all necessary data, and renders a RSS feed in output_path.""" items = [] for post in timeline[:10]: args = { 'title': post.title(lang), 'link': post.permalink(lang), 'description': post.text(lang, teaser_only=True), 'guid': post.permalink(lang), 'pubDate': post.date, } items.append(rss.RSSItem(**args)) rss_obj = rss.RSS2( title=title, link=link, description=description, lastBuildDate=datetime.datetime.now(), items=items, generator='nikola', ) dst_dir = os.path.dirname(output_path) if not os.path.isdir(dst_dir): os.makedirs(dst_dir) with open(output_path, "wb+") as rss_file: rss_obj.write_xml(rss_file)
def rss(): """ RSS2 Support. support xml for RSSItem with 12 diaries. Args: none Return: diaries_object: list site_settings: title, link, description """ articles = Diary.objects.order_by('-publish_time')[:12] items = [] for article in articles: content = article.html url = Config.SITE_URL + '/diary/' + str(article.pk) + '/' + \ article.title items.append( PyRSS2Gen.RSSItem( title=article.title, link=url, description=content, guid=PyRSS2Gen.Guid(url), pubDate=article.publish_time, )) rss = PyRSS2Gen.RSS2(title=Config.MAIN_TITLE, link=Config.SITE_URL, description=Config.DESCRIPTION, lastBuildDate=datetime.datetime.now(), items=items).to_xml('utf-8') return rss
def buildRssLevel1(folder,xml,list): #Creation of the rss rss = PyRSS2Gen.RSS2( title = "TV Show Paradize RSS Feed : "+folder.capitalize(), link = "https://fi08.us.to/"+folder, description = "The latest "+xml.capitalize()+" of the server", lastBuildDate = datetime.datetime.now(), ) #Construction de la liste avec les items for item in list: # extract just the filename folder, file_name = os.path.split(item[1]) # convert date tuple to MM/DD/YYYY HH:MM:SS format file_date = time.strftime("%m/%d/%y %H:%M:%S", item[0]) rss.items.append( PyRSS2Gen.RSSItem( title = file_name.capitalize(), link = http_dir + folder + "/" + file_name, description = "", guid = PyRSS2Gen.Guid(http_dir + folder + "/" + file_name), pubDate = file_date ) ) rss.write_xml(open(xml_dir+xml+".xml", "w"))
def generic_rss_renderer(lang, title, link, description, timeline, output_path, rss_teasers): """Takes all necessary data, and renders a RSS feed in output_path.""" items = [] for post in timeline[:10]: args = { 'title': post.title(lang), 'link': post.permalink(lang, absolute=True), 'description': post.text(lang, teaser_only=rss_teasers), 'guid': post.permalink(lang, absolute=True), # PyRSS2Gen's pubDate is GMT time. 'pubDate': (post.date if post.date.tzinfo is None else post.date.astimezone(pytz.timezone('UTC'))), 'categories': post._tags.get(lang, []), } items.append(rss.RSSItem(**args)) rss_obj = rss.RSS2( title=title, link=link, description=description, lastBuildDate=datetime.datetime.now(), items=items, generator='nikola', ) dst_dir = os.path.dirname(output_path) if not os.path.isdir(dst_dir): os.makedirs(dst_dir) with codecs.open(output_path, "wb+", "utf-8") as rss_file: data = rss_obj.to_xml(encoding='utf-8') if isinstance(data, bytes_str): data = data.decode('utf-8') rss_file.write(data)
def generate_feed(md_files, output_extension, feedfile, feed_url, title='', description=''): articles = [ parse_markdown_file(md_file, output_extension) for md_file in md_files ] articles.sort(key=itemgetter('date'), reverse=True) for article in articles: relative_path = file_relpath(article['link'], feedfile) article['url'] = urljoin(feed_url, relative_path) rss = PyRSS2Gen.RSS2( title=title, link=feed_url, description=description, lastBuildDate=datetime.now(), items=[ PyRSS2Gen.RSSItem(title=article['title'], link=article['url'], description=article['html'], guid=PyRSS2Gen.Guid(article['url']), pubDate=article['date']) for article in articles ]) with open(feedfile, 'w') as f: rss.write_xml(f)