-
Notifications
You must be signed in to change notification settings - Fork 0
/
feed2atom.py
57 lines (47 loc) · 1.5 KB
/
feed2atom.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# encoding: utf-8
from time import strftime
import xmltramp
def isodate(time):
return strftime('%Y-%m-%dT%H:%M:%SZ', time)
class FeedToAtom:
"""Convert a feedparser feed to an Atom 1.0 XML document"""
atom = xmltramp.Namespace('http://www.w3.org/2005/Atom')
def convert(self, feed):
f = self.feed = xmltramp.Element(self.atom.feed, prefixes=self.atom._prefix(None))
if 'title' not in feed.feed:
return ''
f.title = feed.feed.title
f.link = feed.feed.link
u = feed.get('updated') or feed.feed.get('updated_parsed')
if u:
f.updated = isodate(u)
f.id = feed.href
f.link = {'rel': 'self', 'href': feed.href}
for entry in feed.entries:
if not self.filter(entry):
continue
e = self.entry = f._new('entry')
if 'author' in entry:
e._new('author').name = entry.author
e.title = entry.title
e.updated = isodate(entry.updated_parsed)
e.id = entry.id
e.link = {'rel': 'alternate', 'type': 'text/html', 'href': entry.link}
if 'summary' in entry:
e.summary = entry.summary
if 'tags' in entry:
for t in entry.tags:
e['category':] = {'scheme': t.scheme, 'term': t.term}
self.post_process(entry)
return f.__repr__(1, 1)
def filter(self, entry):
"""Override to filter the entries"""
return True
def post_process(self, entry):
"""Override to post-process the entries"""
pass
if __name__ == '__main__':
import sys, feedparser
c = FeedToAtom()
for url in sys.argv[1:]:
print c.convert(feedparser.parse(url)).encode('utf-8')