本文整理汇总了Python中feedgen.feed.FeedGenerator.rss_str方法的典型用法代码示例。如果您正苦于以下问题:Python FeedGenerator.rss_str方法的具体用法?Python FeedGenerator.rss_str怎么用?Python FeedGenerator.rss_str使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类feedgen.feed.FeedGenerator
的用法示例。
在下文中一共展示了FeedGenerator.rss_str方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def generate_feed(output_file, exclude_highlights=True):
# Parse RSS feed
d = feedparser.parse(ESPN_RSS_FEED)
IMAGE_URL = d.feed.image["href"]
# RSS feed generation
fg = FeedGenerator()
fg.load_extension("podcast", rss=True)
## RSS tags
# Required
fg.title(d.feed.title)
fg.link(href="https://github.com/aaearon/lebatard-show-rss")
fg.description(d.feed.description)
# Optional
fg.language(d.feed.language)
fg.image(IMAGE_URL)
fg.subtitle(d.feed.subtitle)
# iTunes
fg.podcast.itunes_author(d.feed.author)
fg.podcast.itunes_category(itunes_category=d.feed.category)
fg.podcast.itunes_image(itunes_image=IMAGE_URL)
fg.podcast.itunes_explicit(itunes_explicit="clean")
fg.podcast.itunes_owner(name=CONTACT["name"], email=CONTACT["email"])
tz = pytz.timezone("America/Los_Angeles")
for e in d.entries:
if exclude_highlights and episode_duration_string_to_int(e["itunes_duration"]) > 3600:
pass
else:
fe = fg.add_entry()
fe.id(e.id)
fe.title(e.title)
fe.description(e.description)
fe.enclosure(url=e.enclosures[0]["href"], length=e.enclosures[0]["length"], type=e.enclosures[0]["type"])
fe.podcast.itunes_summary(e.description)
fe.podcast.itunes_subtitle(e.description)
fe.podcast.itunes_duration(e["itunes_duration"])
dt = datetime.fromtimestamp(time.mktime(e.published_parsed))
date = tz.localize(dt)
# Local hour
if "Show: " in e.title:
fe.published(date)
elif "Hour 1" in e.title:
fe.published(date + timedelta(hours=1))
elif "Hour 2" in e.title:
fe.published(date + timedelta(hours=2))
elif "Hour 3" in e.title:
fe.published(date + timedelta(hours=3))
else:
fe.published(date + timedelta(hours=-1))
fg.rss_str(pretty=True)
fg.rss_file(output_file)
示例2: write_podcast
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def write_podcast(show, podcast_dir, base_public_url, showlocal_tz):
"""Create the podcast file."""
fg = FeedGenerator()
fg.load_extension('podcast')
url = "{}{}.xml".format(base_public_url, show.id)
fg.id(url.split('.')[0])
fg.title(show.name)
fg.image(show.image_url)
fg.description(show.description)
fg.link(href=url, rel='self')
# collect all mp3s for the given show
all_mp3s = glob.glob(os.path.join(podcast_dir, "{}_*.mp3".format(show.id)))
for filepath in all_mp3s:
filename = os.path.basename(filepath)
mp3_date = _get_date_from_mp3_path(filepath, showlocal_tz)
mp3_size = os.stat(filepath).st_size
mp3_url = base_public_url + filename
mp3_id = filename.split('.')[0]
title = "Programa del {0:%d}/{0:%m}/{0:%Y}".format(mp3_date)
# build the rss entry
fe = fg.add_entry()
fe.id(mp3_id)
fe.pubdate(mp3_date)
fe.title(title)
fe.enclosure(mp3_url, str(mp3_size), 'audio/mpeg')
fg.rss_str(pretty=True)
fg.rss_file(os.path.join(podcast_dir, '{}.xml'.format(show.id)))
示例3: export_feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def export_feed(self, output):
fg = FeedGenerator()
fg.load_extension('podcast')
fg.podcast.itunes_category('Religion & Spirituality', 'Christianity')
fg.podcast.itunes_image("%s/icon.png" % URL_BASE)
fg.title('JW.ORG Magazines')
fg.description('Combined Feed of Watchtower (public), Watchtower (study), and Awake! in English from jw.org.')
fg.link(href="%s/%s" % (URL_BASE, output), rel='self')
manifest = self._load()
entries = []
for lang, mnemonics in manifest.items():
for mnemonic, issues in mnemonics.items():
for issue, data in issues.items():
entries.append((issue, data))
for issue, entry in sorted(entries, key=lambda i: i[0], reverse=True):
fe = fg.add_entry()
fe.id( entry['hash'] )
fe.title( entry['title'] )
fe.description( entry['title'] )
fe.published( pytz.utc.localize( entry['created_on'] ) )
url = "%s/%s" % (URL_BASE, os.path.basename(entry['file']))
mime = 'audio/mpeg'
fe.enclosure(url, str(entry['duration']), mime)
fe.link(href=url, type=mime)
fg.rss_str(pretty=True)
fg.rss_file(os.path.join(CACHE_DIR, output))
示例4: TestExtensionSyndication
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
class TestExtensionSyndication(unittest.TestCase):
SYN_NS = {'sy': 'http://purl.org/rss/1.0/modules/syndication/'}
def setUp(self):
self.fg = FeedGenerator()
self.fg.load_extension('syndication')
self.fg.title('title')
self.fg.link(href='http://example.com', rel='self')
self.fg.description('description')
def test_update_period(self):
for period_type in ('hourly', 'daily', 'weekly', 'monthly', 'yearly'):
self.fg.syndication.update_period(period_type)
root = etree.fromstring(self.fg.rss_str())
a = root.xpath('/rss/channel/sy:UpdatePeriod',
namespaces=self.SYN_NS)
assert a[0].text == period_type
def test_update_frequency(self):
for frequency in (1, 100, 2000, 100000):
self.fg.syndication.update_frequency(frequency)
root = etree.fromstring(self.fg.rss_str())
a = root.xpath('/rss/channel/sy:UpdateFrequency',
namespaces=self.SYN_NS)
assert a[0].text == str(frequency)
def test_update_base(self):
base = '2000-01-01T12:00+00:00'
self.fg.syndication.update_base(base)
root = etree.fromstring(self.fg.rss_str())
a = root.xpath('/rss/channel/sy:UpdateBase', namespaces=self.SYN_NS)
assert a[0].text == base
示例5: podcast_feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def podcast_feed():
logo_url = url_for("static", filename="wpclogo_big.png", _external=True)
fg = FeedGenerator()
fg.load_extension('podcast')
fg.podcast.itunes_category('Technology', 'Podcasting')
fg.podcast.itunes_image(logo_url)
fg.author({'name': 'Nathan Kellert', 'email': '[email protected]'})
fg.link(href='http://watchpeoplecode.com/podcast_feed.xml', rel='self')
fg.title('WPC Coders Podcast')
fg.description('WPC Coders Podcast is a weekly peek into the lives of developers and the WatchPeopleCode community. Our goal is to keep our listeners entertained by giving them new and interesting insights into our industry as well as awesome things happening within our own community. Here, you can expect hear about some of the latest news, tools, and opportunities for developers in nearly every aread of our industry. Most importantly, we hope to have some fun and a few laughs in ways only other nerds know how.') # NOQA
episodes = [('ep1.mp3', 'Episode 1', datetime(2015, 02, 21, 23), 'Learn all about the WPC hosts, and where we came from in Episode 1!'),
('ep2.mp3', 'Episode 2', datetime(2015, 02, 28, 23), 'This week we cover your news, topics and questions in episode 2!'),
('ep3.mp3', 'Episode 3', datetime(2015, 03, 07, 23), "On todays podcast we talk to WatchPeopleCode's founder Alex Putilin. Hear about how the reddit search engine thousands watched him write. Also, hear the inside scoop of how WatchPeopleCode got started!"), # NOQA
('ep4.mp3', 'Episode 4', datetime(2015, 03, 14, 23), "This week we talk to FreeCodeCamps Quincy Larson(http://www.freecodecamp.com) about their project that combines teaching new developers how to code and completing projects for non-profits! Lets find out how this group of streamers code with a cause!")] # NOQA
for epfile, eptitle, epdate, epdescription in episodes[::-1]:
epurl = "https://s3.amazonaws.com/wpcpodcast/{}".format(epfile)
fe = fg.add_entry()
fe.id(epurl)
fe.title(eptitle)
fe.description(epdescription)
fe.podcast.itunes_image(logo_url)
fe.pubdate(epdate.replace(tzinfo=pytz.UTC))
fe.enclosure(epurl, 0, 'audio/mpeg')
return Response(response=fg.rss_str(pretty=True),
status=200,
mimetype='application/rss+xml')
示例6: latestRss
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def latestRss(userID):
userID = userID.lower()
shows = {}
episodes = []
today = date.today().strftime('%Y-%m-%d')
for showID in series.getUserShowList(userID):
shows[showID] = series.getShowInfo(userID, showID, withEpisodes=True, onlyUnseen=True)
episodes.extend((showID, episode) for episode in shows[showID]['episodes'] if episode['airdate'] and airdateKey(episode['airdate']) < today)
episodes.sort(key=episodeAirdateKey, reverse=True)
feed = FeedGenerator()
feed.id(userID)
feed.title('%s\'s shows' % userID)
feed.description('Unseen episodes')
feed.link(href=request.url_root)
feed.language('en')
for showID, episode in episodes:
entry = feed.add_entry()
entry.id('%s/%s' % (showID, episode['episode_id']))
entry.title('%s S%02dE%02d: %s' % (shows[showID]['name'], episode['season'], episode['episode'], episode['title']))
return feed.rss_str(pretty=True)
示例7: TestExtensionTorrent
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
class TestExtensionTorrent(unittest.TestCase):
def setUp(self):
self.fg = FeedGenerator()
self.fg.load_extension('torrent')
self.fg.title('title')
self.fg.link(href='http://example.com', rel='self')
self.fg.description('description')
def test_podcastEntryItems(self):
fe = self.fg.add_item()
fe.title('y')
fe.torrent.filename('file.xy')
fe.torrent.infohash('123')
fe.torrent.contentlength('23')
fe.torrent.seeds('1')
fe.torrent.peers('2')
fe.torrent.verified('1')
assert fe.torrent.filename() == 'file.xy'
assert fe.torrent.infohash() == '123'
assert fe.torrent.contentlength() == '23'
assert fe.torrent.seeds() == '1'
assert fe.torrent.peers() == '2'
assert fe.torrent.verified() == '1'
# Check that we have the item in the resulting XML
ns = {'torrent': 'http://xmlns.ezrss.it/0.1/dtd/'}
root = etree.fromstring(self.fg.rss_str())
filename = root.xpath('/rss/channel/item/torrent:filename/text()',
namespaces=ns)
assert filename == ['file.xy']
示例8: get_feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def get_feed(atom=False):
fg = FeedGenerator()
domain = get_domain()
items = get_posts({"limit": "10"}, full=True)["results"]
fg.id("http://%s/"%domain)
fg.title("Blog do MatrUFSC2")
fg.description("Feed do blog do MatrUFSC2, onde noticias e novos recursos sao anunciados primeiro!")
fg.language('pt-BR')
fg.link({"href":"/blog/feed","rel":"self"})
fg.updated(items[0]["posted_at"].replace(tzinfo=pytz.UTC))
for item in items:
entry = fg.add_entry()
entry.title(item["title"])
tree = html.fromstring(item["summary"])
cleaner = Cleaner(allow_tags=[])
tree = cleaner.clean_html(tree)
text = tree.text_content()
entry.description(text, True)
entry.link({"href":item["link"],"rel":"self"})
entry.content(item["body"])
entry.published(item["posted_at"].replace(tzinfo=pytz.UTC))
entry.updated(item["posted_at"].replace(tzinfo=pytz.UTC))
entry.category({"label": item["category"]["title"], "term": item["category"]["slug"]})
entry.id(item["id"])
if atom:
return fg.atom_str(pretty=True)
else:
return fg.rss_str(pretty=True)
示例9: add_feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def add_feed(self, feed_id, yt_playlist):
feed = FeedGenerator()
feed.load_extension("podcast")
feed.id(feed_id)
feed.title(yt_playlist["snippet"]["title"])
feed.author({"name": yt_playlist["snippet"]["channelTitle"]})
feed.description(yt_playlist["snippet"]["description"])
feed.logo(yt_playlist["snippet"]["thumbnails"]["standard"]["url"])
feed.link(href="https://www.youtube.com/playlist?list=%s" % (yt_playlist["id"]))
feed.rss_str(pretty=True)
feed.last_updated = 0
self.feeds[feed_id] = feed
return feed
示例10: generate_rss
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def generate_rss(language, since):
url = "{0}?since={1}".format(language["url"], since)
file_name = "github_trends_{0}_{1}.rss".format(language["key"], since)
title = "GitHub Trends - {0} - {1}".format(language["name"], since.capitalize())
print(url)
page = requests.get(url)
tree = html.fromstring(page.content)
lis = tree.cssselect("ol.repo-list li")
fg = FeedGenerator()
fg.title(title)
fg.link(href="http://github-trends.ryotarai.info/rss/{0}".format(file_name))
fg.description(title)
index = 1
for li in lis:
a = li.cssselect("h3 a")[0]
description = ""
ps = li.cssselect("p")
if len(ps) > 0:
description = ps[0].text_content().strip()
fe = fg.add_entry()
fe.link(href="https://github.com{0}".format(a.get("href")))
fe.title("{0} (#{1} - {2} - {3})".format(
a.text_content().strip().replace(" / ", "/"),
index,
language["name"],
since.capitalize(),
))
fe.description(description)
index += 1
rssfeed = fg.rss_str(pretty=True)
s3.Object(bucket, 'rss/{0}'.format(file_name)).put(Body=rssfeed, ContentType="application/xml")
示例11: GET
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def GET(self):
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
fg = FeedGenerator()
#TODO create icon
# fg.icon('http://www.det.ua.pt')
fg.id(config.get('rss','id'))
fg.title(config.get('rss','title'))
fg.subtitle(config.get('rss','subtitle'))
fg.description(config.get('rss','description'))
fg.author({'name': config.get('rss','author_name'), 'email':config.get('rss','author_email')})
fg.language(config.get('rss','language'))
fg.link(href=config.get('rss','href'), rel='related')
client = EmailClient()
for msgn in reversed(client.listBox(config.get('imap','mailbox'))[:config.getint('rss','maxitems')]):
cherrypy.log("RSS Entry: "+msgn)
em = client.getEMail(msgn)
entry = fg.add_entry()
entry.title(em['subject'])
entry.author({'name': em['From']['name'], 'email': em['From']['email']})
entry.guid(config.get("main","baseurl")+'news/'+msgn)
entry.link({'href':config.get("main","baseurl")+'news/'+msgn, 'rel':'alternate'})
entry.pubdate(em['date'])
entry.content(em['body'])
return fg.rss_str(pretty=True)
示例12: TestExtensionDc
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
class TestExtensionDc(unittest.TestCase):
def setUp(self):
self.fg = FeedGenerator()
self.fg.load_extension('dc')
self.fg.title('title')
self.fg.link(href='http://example.com', rel='self')
self.fg.description('description')
def test_entryLoadExtension(self):
fe = self.fg.add_item()
try:
fe.load_extension('dc')
except ImportError:
pass # Extension already loaded
def test_elements(self):
for method in dir(self.fg.dc):
if method.startswith('dc_'):
m = getattr(self.fg.dc, method)
m(method)
assert m() == [method]
self.fg.id('123')
assert self.fg.atom_str()
assert self.fg.rss_str()
示例13: makeRss
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def makeRss(self):
fg = FeedGenerator()
fg.load_extension('podcast')
fg.id('http://hypecast.blackmad.com/' + self.mode)
fg.title('Hype Machine Robot Radio: ' + self.mode)
fg.author( {'name':'David Blackmad','email':'[email protected]'} )
fg.logo('http://dump.blackmad.com/the-hype-machine.jpg')
fg.language('en')
fg.link(href='http://hypecast.blackmad.com/' + self.mode)
fg.description('Hype Machine Robot Radio: ' + self.mode)
description = ' <br/>'.join(['%s. %s' % (index + 1, self.mk_song_id(s)) for index, s in enumerate(self.songs)])
fe = fg.add_entry()
fe.title(self.track_name)
fe.description(description)
fe.id(self.filename)
# add length
print(self.relative_dir)
print(self.filename)
fe.enclosure(url = 'http://hypecast.blackmad.com/%s' % (self.filename), type="audio/mpeg")
rss_str = fg.rss_str()
newItem = ET.fromstring(rss_str)[0].find('item')
out = open(self.get_filename('xml'), 'w')
out.write(ET.tostring(newItem))
out.close()
self.updateRss()
示例14: rss
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def rss():
config = public_app.config['feed']
fg = FeedGenerator()
fg.id('%s/blog' % Config.BASE_URL)
fg.title(config['title'])
fg.author( {'name': config['author'],'email': config['email']} )
fg.description(config['desc'])
fg.link( href=Config.BASE_URL, rel='alternate' )
query = {
'id': { '$regex': 'blog' },
'current': True,
'meta.hide': { '$ne': True }
}
posts = db.pages.find(query).sort('meta.created', -1)[:20]
for post in posts:
fe = fg.add_entry()
fe.title(post['meta']['title'])
if 'author' in post['meta']:
fe.author( {'name': post['meta']['author'],'email': config['email']} )
else:
fe.author( {'name': config['author'],'email': config['email']} )
fe.description(do_truncate(post['content'], 300))
fe.link(href="%s/%s" % (Config.BASE_URL, post['id']), rel='alternate')
fe.pubdate(utc.localize(post['meta']['created']))
fe.content(post['content'])
response.headers['Content-Type'] = 'application/rss+xml'
return fg.rss_str(pretty=True)
示例15: feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import rss_str [as 别名]
def feed(self, feed_title, title, content, url, published=None, summary=None,
enclosure=None, media_thumbnail=None):
feed = FeedGenerator()
feed.title(feed_title)
feed.description(faker.sentence())
feed.link({'href': WP_FEED_URL})
entry = feed.add_entry()
entry.title(title)
entry.link({'href': url})
entry.author(name=faker.name())
entry.content(content, type="cdata")
if summary:
entry.description(summary)
if enclosure:
entry.enclosure(url=enclosure['url'],
type=enclosure['type'],
length=str(faker.pyint()))
if media_thumbnail:
feed.load_extension('media')
entry.media.thumbnail({'url': media_thumbnail})
tz = pytz.timezone(faker.timezone())
published = published or faker.date_time(tzinfo=tz)
entry.published(published)
entry.updated(faker.date_time_between(start_date=published, tzinfo=tz))
return feed.rss_str().decode('utf8')