]>
<< テクニカルエンジニア(データベース)の解答 | main | Python Challenge(1) >>
はじめての Django アプリ作成,その 3を参考にさせていただき、外部公開用のViewをつくる。データベースから情報をひっぱってくるのはすぐにできた。次は各サイトごとにRSSに含まれている記事を展開したい。そのためにはDjangoのテンプレート言語を勉強する必要がありそうだ。
>>> from django.template import Context,Template
>>> import feedparser
>>> rss = "http://www.panopticon.jp/blog/index.xml"
>>> c = Context({"entries":feedparser.parse(rss).entries})
>>> t = Template("{% for entry in entries %} \
... {{ entry.title }} \
... {% endfor %}")
>>> t.render(c)
とやるとRSS中の記事タイトル一覧が表示される。要するにTemplate中で使いたい変数をContextの中にしまっておけば、あとはDjangoが勝手に展開してくれるというわけですね。
とりあえずこんな感じでTemplateを作ってみる。site.titleとsite.rssにはデータベースの値がそのまま入る。rss_getタグは指定されたRSSから記事のリストを取得しentriesによって参照できるようにする。それぞれの記事を表示するにはentriesについてループを回してやればよい。
<html>
<head>
<title>Admin's RSS Reader</title>
</head>
<body>
{% for site in object_list %}
<h1>{{ site.title }}</h1>
<p>{{ site.rss }}</p>
{% rss_get site.rss as entries %}
{% for entry in entries %}
<h2>{{ entry.title }}</h2>
{% endfor %}
{% endfor %}
</body>
</html>
Python プログラマのための Django テンプレート言語ガイドを見ながらrss_getタグを作る……がうまくいかない。何も表示されない。
from django import template
from rss.site.models import Site
import feedparser
register = template.Library()
def do_rss_get(parser, token):
bits = token.contents.split()
if len(bits) != 4:
raise template.TemplateSyntaxError, "'%s' requires 3 arguments" % bits[0]
if bits[2] != "as":
raise template.TemplateSyntaxError, "'%s' 's 2nd argument must
be 'as'" % bits[0]
return RSSNode(bits[3], bits[1])
class RSSNode(template.Node):
def __init__(self, variable, rss):
self.variable = variable
self.rss = rss
def render(self, context):
f = feedparser.parse(self.rss).entries
context[self.variable] = f
RSSNodeを
def render(self, context):
f = feedparser.parse(self.rss)
context[self.variable] = f
としてやると、Feed, Encoding,Bozo, Version, Namespaces, Entries, Bozo_ExceptionとRSSの各属性を拾って来た。いちおうタグとして動いてはいるようだ。
>>> c = Context({"entries":feedparser.parse(rss)})
>>> t.render(c)
' Feed Status Updated Version Encoding Bozo Headers Etag Href Namespaces Entries '
とインタープリタで実行した時のほうが多くの属性を拾ってくる。なぜ。続く。
http://www.panopticon.jp/mt/mt-tb.cgi/71
コメントする