Last Update: 28.11.2006. By azarai in python | snipplet
i’ve got some time to continue my python and feed example
MyFeedsConfig.feeds contains a list of feed urls and we just try to receive, aggreate and sort them. pretty self explaining. The article class is also one of ours and does only contain some attributes. If we get the host and domain part of the url we look for the favicon and display it later. if not found look if theres some set in the feed. maybe we should switch that and look for the image url in feed first.
feeds = []
for feed in MyFeedsConfig.feeds:
feeds.append(feedparser.parse(feed))
entries = []
urlPattern = re.compile("(https?://(\w*\.)?\w*\.\w{2,3})/.*")
for feed in feeds:
for item in feed[ "items" ]:
article = Article()
match = urlPattern.match(feed.url)
if match:
article.feedImage = match.group(1) + "/favicon.ico"
else:
article.feedImage = feed.url
article.feedTitle = feed.feed.title
article.article= item
article.date = strftime('%d.%m.%Y', item.updated_parsed)
entries.append( article )
decorated = [(entry.article["date_parsed"], entry) for entry in entries]
decorated.sort()
decorated.reverse() # for most recent entries first
sorted = [entry for (date,entry) in decorated]
The next step would be to print eg a nice xhtml page. I dont like generating them via print …, so i looked for a easy to use template engine in python. I found two i liked and surprisingly have the same syntax. The template engine of django and jinja. For further learning i recommend their examples and tutorial.
Calling the template and passing some parameters are, guess what, pretty easy. Just need to send the Content Type first so the browser knows what comes.
t = Template('feed', FileSystemLoader('our templates dir'))
c = Context({
'articles': sorted
})
print "Content-Type: text/html;charset=utf-8\n"
print t.render(c)
The relevant part of our template looks like:
<div id="main">
{% if articles %}
{% for article in articles %}
<div class="feed">
<div class="item" id="IITEM-{{ article.title }}">
<img src="{{ article.feedImage }}" alt="{{ article.feedTitle }}" title="Source favicon" width="16" height="16" />
<span class="time">{{ article.date }}</span>
<span class="title"><a href="{{ article.article.link }}?phpMyAdmin=fe01160aa628cd6af7fe0d52b0e458f1">{{ article.article.title }}</a></span>
</div>
</div>
{% endfor %}
{% else %}
<p>No feeds are available.</p>
{% endif %}
</div>
The output looks like:
I was trying to get the same output as the Lilina News Aggregator and using their stylesheet. Works for this example. Not sure if i will extend the whole thingy.