本文整理汇总了Python中feedgen.feed.FeedGenerator.atom_str方法的典型用法代码示例。如果您正苦于以下问题:Python FeedGenerator.atom_str方法的具体用法?Python FeedGenerator.atom_str怎么用?Python FeedGenerator.atom_str使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类feedgen.feed.FeedGenerator
的用法示例。
在下文中一共展示了FeedGenerator.atom_str方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_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)
示例2: TestExtensionDc
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_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()
示例3: feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def feed():
"""
Generate atom feed
"""
entries = parse_posts(0, C.feed_count)
fg = FeedGenerator()
fg.id(str(len(entries)))
fg.title(C.title)
fg.subtitle(C.subtitle)
fg.language(C.language)
fg.author(dict(name=C.author, email=C.email))
fg.link(href=C.root_url, rel='alternate')
fg.link(href=make_abs_url(C.root_url, 'feed'), rel='self')
for entry in entries:
fe = fg.add_entry()
fe.id(entry.get('url'))
fe.title(entry.get('title'))
fe.published(entry.get('date'))
fe.updated(entry.get('updated') or entry.get('date'))
fe.link(href=make_abs_url(C.root_url, entry.get('url')), rel='alternate')
fe.author(dict(name=entry.get('author'), email=entry.get('email')))
fe.content(entry.get('body'))
atom_feed = fg.atom_str(pretty=True)
return atom_feed
示例4: feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def feed(column_id):
api = Api(column_id)
with request.urlopen(api.info) as stream:
result = stream.read().decode('utf-8')
if not result:
return '', 404
info = json.loads(result)
with request.urlopen(api.posts) as stream:
result = stream.read().decode('utf-8')
entries = json.loads(result)
fg = FeedGenerator()
fg.id(str(entries[0]['slug']))
fg.title(info['name'])
fg.language('zh_CN')
fg.icon(info['avatar']['template'].replace('{id}', info['avatar']['id']).replace('{size}', 's'))
fg.logo(info['avatar']['template'].replace('{id}', info['avatar']['id']).replace('{size}', 'l'))
fg.description(info['intro'])
fg.author(dict(name=info['creator']['name']))
fg.link(href=api.base_url + info['url'], rel='alternate')
for entry in entries:
fe = fg.add_entry()
fe.id(entry['url'])
fe.title(entry['title'])
fe.published(entry['publishedTime'])
fe.updated(entry['publishedTime'])
fe.author(dict(name=entry['author']['name']))
fe.link(href=api.base_url + entry['url'], rel='alternate')
fe.content(entry['content'])
return fg.atom_str(pretty=True)
示例5: _filter_fb_rss_feeed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def _filter_fb_rss_feeed(url):
parsed_feed = feedparser.parse(url)
filtered_entries = filter(
lambda x: ' shared a link: "' in x.title, parsed_feed.entries)
fg = FeedGenerator()
fg.id('https://fb-notifications-to-pocket.herokuapp.com/')
fg.title('Facebook Notifications to Pocket')
fg.author({'name': 'Pankaj Singh', 'email': '[email protected]'})
fg.description(
'''Filter FB notifications which contain a link and generate a new rss feed which will be used by IFTTT''')
fg.link(href='https://fb-notifications-to-pocket.herokuapp.com/')
for entry in filtered_entries:
root = etree.HTML(entry.summary_detail.value)
title = entry.title.split(" shared a link: ")[1].strip()[1:-2]
author_name = entry.title.split(" shared a link: ")[0].strip()
url = urlparse.parse_qs(
urlparse.urlparse(root.findall(".//a")[-1].attrib["href"]).query)["u"][0]
title = get_title_for_url(url) or title
fe = fg.add_entry()
fe.id(entry.id)
fe.link(href=url)
fe.published(entry.published)
fe.author({'name': author_name})
fe.title(title)
return fg.atom_str(pretty=True)
示例6: render_atom
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def render_atom(self):
fg = FeedGenerator()
fg.id(self.site_url)
fg.title(self.site_title)
fg.link(href = self.site_url,rel = 'alternate')
fg.link(href = self.site_url + 'atom.xml',rel = 'self')
fg.language('zh-cn')
link_list = ArticleManager.sharedManager().link_list()
for link in link_list:
article = ArticleManager.sharedManager().article_for_link(link)
if not article:
continue
fe = fg.add_entry()
fe.id(article.article_link)
fe.link(link = {'href':self.site_url + article.article_link})
fe.title(article.article_title)
fe.description(article.article_subtitle or '')
fe.author(name = article.author or '',
email = article.author_email or '')
d = datetime.strptime(article.article_publish_date,'%Y-%m-%d')
pubdate = datetime(year = d.year, month = d.month, day = d.day,tzinfo = UTC(8))
fe.pubdate(pubdate)
article.render_content_html()
fe.content(content = article._content_html,
type = 'html')
atom_feed = fg.atom_str(pretty = True)
return atom_feed
示例7: Feeder
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
class Feeder():
def __init__( self, url, title='', feedURL='' ):
scraper = None
if url.startswith( "https://twitter.com/" ):
scraper = TwitterScraper( url )
if title == '':
title = "Twitter: @" + url.split('/')[3]
elif url.startswith( "http://www.lindwurm-linden.de/termine" ):
scraper = LindwurmScraper( url )
if title == '':
title = "Lindwurm: Termine"
else:
raise UnsupportedService( "No scraper found for this URL." )
self.feed = FeedGenerator()
self.feed.id( url )
self.feed.title( title )
self.feed.author( { "name": url } )
if feedURL != '':
self.feed.link( href=feedURL, rel='self' )
for entry in scraper.entries:
fe = self.feed.add_entry()
fe.id( entry['url'] )
fe.title( entry['title'] )
fe.link( href=entry['url'], rel='alternate' )
fe.content( entry['text'] )
def GetAtom( self ):
return self.feed.atom_str( pretty=True ).decode()
示例8: test_content_cdata_type
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def test_content_cdata_type(self):
fg = FeedGenerator()
fg.title('some title')
fg.id('http://lernfunk.de/media/654322/1')
fe = fg.add_entry()
fe.id('http://lernfunk.de/media/654322/1')
fe.title('some title')
fe.content('content', type='CDATA')
result = fg.atom_str()
assert b'<content type="CDATA"><![CDATA[content]]></content>' in result
示例9: main
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def main(argv):
ap = argparse.ArgumentParser(
description='''
Render RSS and Atom feeds from a CSV of food inspection data.
''')
ap.add_argument(
'-v', '--verbose', action='count', dest='verbosity', default=0,
help='increase global logging verbosity; can be used multiple times')
ap.add_argument(
'-f', '--format', choices=['rss', 'atom'], default='atom',
help='''
specify the format to use when rendering the feed (default: %(default)s)')
''')
ap.add_argument(
'-n', '--num_incidents', metavar='<num>', type=int, default=10,
help='render <num> recent incidents in the feed (default: %(default)s)')
ap.add_argument(
'flavor', nargs='?', default='all', choices=['all', 'failures'],
help='select the flavor of feed to render (default: %(default)s)')
args = ap.parse_args()
logging.basicConfig(
level=logging.ERROR - args.verbosity * 10,
style='{',
format='{}: {{message}}'.format(ap.prog))
fg = FeedGenerator()
fg.id('http://pgriess.github.io/dallas-foodscores/')
fg.link(href=fg.id(), rel='self')
fg.title('Dallas Food Inspection Scores')
fg.subtitle('''
Food inspection scores from the official City of Dallas dataset; updated daily
''')
fg.description(fg.subtitle())
fg.language('en')
fg.author(
name='Peter Griess',
email='[email protected]',
uri='https://twitter.com/pgriess')
for i in get_inspections_to_feed(sys.stdin, args.num_incidents,
args.flavor):
fe = fg.add_entry()
fe.title('{name} at {address} scored {score}'.format(
name=i.name, address=i.address, score=i.score))
fe.id(fg.id() + '#!/' + str(abs(hash(i))))
fe.link(href=fe.id(), rel='alternate')
fe.content(fe.title())
fe.published(TZ.localize(i.date))
if args.format == 'atom':
print(fg.atom_str(pretty=True))
else:
print(fg.rss_str(pretty=True))
示例10: render_feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def render_feed(text_paths, outpath):
# http://rhodesmill.org/brandon/feed
# http://rhodesmill.org/brandon/category/python/feed
# http://rhodesmill.org/brandon/feed/atom/
t0 = datetime.min.time()
def fix(d):
dt = datetime.combine(d, t0)
return timezone('US/Eastern').localize(dt)
posts = [post_info(path) for path in text_paths if date_of(path)]
posts = sorted(posts, key=lambda post: post['date'])
posts = posts[-1:]
most_recent_date = max(post['date'] for post in posts)
def full(url):
return 'http://rhodesmill.org/' + url.lstrip('/')
fg = FeedGenerator()
fg.id(full('/'))
fg.author({'name': 'Brandon Rhodes'})
fg.language('en')
fg.link(href=full('/brandon/'), rel='alternate')
if 'python' in outpath:
fg.link(href=full('/brandon/category/python/feed/'), rel='self')
else:
fg.link(href=full('/brandon/feed/'), rel='self')
fg.subtitle('Thoughts and ideas from Brandon Rhodes')
fg.title("Let's Discuss the Matter Further")
fg.updated(fix(most_recent_date))
for post in posts:
url = full(post['url_path'])
excerpt = truncate_at_more(post['body_html'], url)
fe = fg.add_entry()
fe.content(excerpt, type='html')
fe.guid(url, permalink=True)
fe.id(url)
fe.link({'href': url})
fe.published(fix(post['date']))
fe.title(post['title'])
fe.updated(fix(post['date']))
rss = fg.rss_str(pretty=True)
fg.link(href=full('/brandon/feed/atom/'), rel='self', replace=True)
atom = fg.atom_str(pretty=True)
return rss, atom
示例11: feedAtom
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def feedAtom():
todos = session.query(Todo).join(Todo.images).all()
fg = FeedGenerator()
fg.title('CityTodo Atom-Feed')
fg.language('en')
fg.id('http://localhost:5000/feed/rss')
fg.link( href='http://localhost:5000/feed/rss', rel='self' )
for todo in todos:
fe = fg.add_entry()
fe.id(str(todo.id))
fe.link(href='http://localhost:5000/todo/'+str(todo.id), rel='self' )
fe.title(todo.name)
fe.content(todo.description)
atomfeed = fg.atom_str(pretty=True)
return atomfeed
示例12: serve_filter
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def serve_filter(type, filtername):
try:
fil = trn.select_unique(Filter, name=filtername, insert=False)
except:
logging.exception("serve_filter failed for filter %s" % (filtername,))
raise
out_feed = FeedGenerator()
out_feed.title(fil.title)
out_feed.subtitle(fil.subtitle)
out_feed.id(filtername)
for entry in fil.entries():
d = entry.definition
out_entry = out_feed.add_entry()
out_entry.title(d.title)
out_entry.published(getattr(d, "published", None))
out_entry.updated(getattr(d, "updated", None))
out_entry.id(d.id)
out_entry.summary(d.summary)
for c in getattr(d, "content", []):
out_entry.content(content=c.value, type=c.type) #, src=c.base
for l in getattr(d, "links", []):
out_entry.link(link=l)
try:
if type == "atom":
mimetype = "application/atom+xml"
result = out_feed.atom_str()
else:
mimetype = "application/rss+xml"
result = out_feed.rss_str()
except:
logging.exception("%s error", type)
mimetype = "text/plain"
result = """
An error occurred while trying to produce this feed.
You could try using %s instead.
""" % ("rss" if type == "atom" else "atom",)
response.content_type = mimetype
return result
示例13: _transform_twitrss_feed_to_link_feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def _transform_twitrss_feed_to_link_feed(url):
# Add timestamp to url
# This will disable caching
url = "{}&replies={}&replies=off".format(url, datetime.now().toordinal())
parsed_feed = feedparser.parse(url)
fg = FeedGenerator()
fg.id('https://fb-notifications-to-pocket.herokuapp.com/')
fg.title('Twitter Feed to Pocket')
fg.author({'name': 'Pankaj Singh', 'email': '[email protected]'})
fg.description(
'''Transform TwitRSS.me feed to a new rss feed which will be used by IFTTT''')
fg.link(href='https://fb-notifications-to-pocket.herokuapp.com/')
all_links = []
for entry in parsed_feed.entries:
links = extract_links_from_a_tweet(entry.link)
if not links:
continue
for link in links:
if link in all_links:
continue
else:
all_links.append(link)
title = get_title_for_url(link) or entry.title
# content = get_content_for_url(link) or entry.content
author_name = get_twitter_handle_from_twitrss_cdata(entry.title)
fe = fg.add_entry()
id = generate_key_for_text(link)
fe.id(id)
fe.link(href=link)
fe.published(entry.published)
fe.author({'name': author_name})
fe.title(title)
# fe.content(content)
return fg.atom_str(pretty=True)
示例14: create_feed
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def create_feed(episodes, output_filepath=None):
woe_feed = FeedGenerator()
woe_feed.load_extension('podcast', atom=True)
woe_feed.title(u"Willkommen Österreich")
woe_feed.id(EPISODES_SCRAPING_URL)
woe_feed.link(href=BASE_URL, rel='self')
woe_feed.description(u"Inoffizieller RSS-Feed für 'Willkommen Österreich'-Episoden")
woe_feed.language('de')
for episode in episodes:
episode_entry = woe_feed.add_entry()
episode_entry.id(episode.page)
episode_entry.link(href=episode.page, rel='alternate')
episode_entry.title(u"Folge {0} - {1}: {2}".format(episode.num, episode.date, episode.description))
for video in episode.videos:
episode_entry.enclosure(url=video, length=0, type='mp4')
if output_filepath:
woe_feed.atom_file(output_filepath)
else:
print(woe_feed.atom_str(pretty=True))
示例15: get
# 需要导入模块: from feedgen.feed import FeedGenerator [as 别名]
# 或者: from feedgen.feed.FeedGenerator import atom_str [as 别名]
def get(self, login, format_):
feed = yield self.thread_pool.submit(
self.db.fetch, "SELECT * FROM feeds WHERE login = ? AND is_enabled = TRUE", login)
if not feed:
raise HTTPError(404)
if feed["password"] and not self.http_basic_auth(feed["login"], feed["password"]):
return # request HTTP basic authentication to protect the feed
files = yield self.thread_pool.submit(
self.db.fetch_all,
"SELECT `key`, login, name, size, folder, caption, expires_at, created_at FROM files "
"WHERE login = ? AND is_public = TRUE AND (expires_at IS NULL OR expires_at > NOW()) "
"ORDER BY name", login)
if format_ == "json":
self.write({"feed": files})
elif format_.endswith(".xml"):
fg = FeedGenerator()
fg.title(feed["title"] or login)
fg.description(login + ": Sharedown")
fg.id(self.reverse_url("feed_index", login, absolute=True))
fg.link(href=self.reverse_url("feed_export", login, format_, absolute=True), rel="self")
for file_ in files:
fe = fg.add_entry()
fe.id(self.reverse_url("download_index", file_["key"], absolute=True))
fe.link(href=self.reverse_url("download_index", file_["key"], absolute=True), rel="alternate")
fe.title(file_["caption"] or file_["name"])
fe.author(name=file_["login"])
fe.published(utils.timezone_localize(file_["created_at"]))
if file_["folder"]:
fe.category(term=file_["folder"])
if format_ == "atom.xml":
self.set_header("Content-Type", "application/xml; charset=UTF-8")
self.write(fg.atom_str(True))
elif format_ == "rss.xml":
self.set_header("Content-Type", "application/xml; charset=UTF-8")
self.write(fg.rss_str(True))