私のWebサイトはY!ジオシティーズで、Blogははてなダイアリーを使ってるんですが、ジオシティーズにブログのヘッドラインをJavaScriptで埋め込んでいます。
先日Google Developer Day 2010 Japanに参加させてもらったので、AppEngineでなにかやりたいなーということで、いままでは別のレンタルサーバで動かしていた変換CGIをAppEngineに移行しました。
よし作ろう!と思ってちょっとググったところ(ここもGoogle先生)あっさりソースサンプルが見つかってしまいました。
パラメータやテンプレートをちょいちょいと修正して30分ほどで完成、簡単すぎてスキルが上がりませんね…
で、appspotにDeployしてもう運用開始です。他から利用されてもトラフィック的に困るので元RSSは私のBlog固定です。通信した結果は10分キャッシュします。なのでブログを更新しても10分程度は反映されません。
直接ブラウザで開くとこんな感じです。
Webサイトにはヘッダ部分でRSSを変換したJavaScriptを読み込んでおきます。
するとこんな感じでばっちり組み込めます。
main.py
main.pyのソースコードです。
from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import webapp from google.appengine.api import urlfetch import logging import cgi import datetime import time import templates import feedparser import webapp2 import sys class GetFeed(webapp2.RequestHandler): def outJSONP(self, data): self.response.headers['Content-Type'] = 'text/javascript;charset=UTF-8' self.response.headers['pragma'] = 'no-cache' self.response.headers['Cache-Control'] = 'no-cache, must-revalidate' self.response.out.write(data) def get(self): finaloutput = "" feedinput = None now_date = datetime.datetime.utcnow() + datetime.timedelta(hours=9) feed_url = "http://koleben.hatenablog.com/feed?dt="+str(time.time()) #feed_url = "https://forcetrekblog.wordpress.com/feed/?dt=" + \ # str(time.time()) #feed_url = "http://lab.ekitan.com/cgi-bin/env.cgi" try: feedinput = urlfetch.fetch(feed_url) #feedinput = urlfetch.fetch(feed_url,headers={'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8','Accept-Encoding':'gzip'}) except Exception as e: logging.info("EXCEPTION") logging.info(str(e)) self.outJSONP(finaloutput) return status = str(feedinput.status_code) finaloutput = templates.read_html % dict(feed_url=cgi.escape( feed_url), contents='', date=now_date, httpstatus=status) # connection error if feedinput.status_code != 200: logging.info("CODE:" + status) logging.info("URL:" + feed_url) logging.info("HEAD:\n" + str(feedinput.header_msg)) logging.info("DATA:\n" + feedinput.content) self.outJSONP(finaloutput) return # json parse error d = feedparser.parse(feedinput.content) if d.bozo == 1: self.outJSONP(finaloutput) return # ok contents = "" for entry in d.entries: contents += templates.contents % dict( link=cgi.escape(entry.link), title=cgi.escape(entry.title)) finaloutput = templates.read_html % dict(feed_url=cgi.escape( feed_url), contents=contents, date=now_date, httpstatus=status) expires_date = datetime.datetime.utcnow() + datetime.timedelta(1) #logging.info( "DATA:aaaaa" ) self.outJSONP(finaloutput) app = webapp2.WSGIApplication([('/', GetFeed)], debug=True)