折角なので簡単なRSSリーダーでも作ってみようか。
※その前に、、、
ここでの説明は GAE for Python な開発の基本が分かっていることが前提になっているので、もしよく分かってないならこちらで予習しておこう。
では始めようか。
まず、いつもの helloworld.py を以下のように編集する。
# -*- coding: utf-8 -*-
import cgi
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from xml.dom import minidom
class MainHandler(webapp.RequestHandler):
def get(self):
url = 'http://sunabako.sblo.jp/index.rdf'
result = urlfetch.fetch(url)
dom = minidom.parseString(result.content)
# ブログ題名取得
blogTitle = dom.getElementsByTagName('channel')[0].getElementsByTagName('title')[0].firstChild.data
# エントリ情報(エントリ題名、URL、作成日の連想配列)のリスト作成
elems = dom.getElementsByTagName('item')
entries = []
for elem in elems:
entry = {}
entry['title'] = elem.getElementsByTagName('title')[0].firstChild.data
entry['link'] = elem.getElementsByTagName('link')[0].firstChild.data
entry['date'] = elem.getElementsByTagName('dc:date')[0].firstChild.data
entries.append(entry)
template_values = {'blogTitle':blogTitle, 'entries':entries}
path = os.path.join(os.path.dirname(__file__), 'rss_reader.html')
self.response.out.write(template.render(path, template_values))
dom.unlink()
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
そしてデザインHTMLのテンプレートは以下の通りだ。
rss_reader.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>{{ blogTitle }}のRSS</title>
</head>
<body>
<ul>
{% for entry in entries %}
<li>{{ entry.date }} <a href="{{ entry.link }}" target="_blank">{{ entry.title }}</a></li>
{% endfor %}
</ul>
</body>
</html>
今回のポイントは、以下の通り。
- google.appengine.api.urlfetch でRSSのXMLデータ取得
- 取得したXMLを xml.dom.minidom で解析
- getElementsByTagName() で該当タグのリスト取得
今回利用したXML解析用の標準モジュール xml.dom.minidom はI/FがJavascriptに似ていて直感的に理解しやすく、尚且つ軽いので、ちょっとしたXML解析には適していると思う。
サードパーティ製モジュールを使えば、ソースコードをもっとスッキリさせることも可能なんだけど、まずは標準モジュールを使ってやる方法を理解しておくことも大切だよね。
ここはひとつポチっとよろしく。

プログラミング Google App Engine
posted with amazlet at 11.05.16
Dan Sanderson
オライリージャパン
売り上げランキング: 48590
オライリージャパン
売り上げランキング: 48590