まずは画面HTMLを以下のとおり記述する。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Twitter Search API - 俺の砂箱</title>
</head>
<body>
<form action="/" method="get">
<input type="text" name="q" value="{{ q }}"/>
<input type="submit" value="検索"/>
</form>
{% for tweet in results %}
<div>
<a href="http://twitter.com/#!/{{ tweet.from_user }}" target="_blank"><img src="{{ tweet.profile_image_url }}" width="50" height="50"/></a>
<p class="from_user"><a href="http://twitter.com/#!/{{ tweet.from_user }}" target="_blank">{{ tweet.from_user }}</p></a>
<p class="text">{{ tweet.text }}</p>
<p class="created_at"><a href="http://twitter.com/#!/{{ tweet.from_user }}/status/{{ tweet.id_str }}" target="_blank">{{ tweet.created_at }}</a></p>
</div>
{% endfor %}
</body>
</html>
次にハンドラだ。
# -*- coding: utf-8 -*-
import cgi
import os
import simplejson
import urllib2, urllib
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
#
# メインハンドラ
#
class MainHandler(webapp.RequestHandler):
def get(self):
# 検索文字列をURLエンコード
q_encoded = urllib.quote_plus(cgi.escape(self.request.get('q')).encode('utf-8'))
# リクエストURLを作成
url = 'http://search.twitter.com/search.json?q=%s' % q_encoded
# リクエストヘッダの作成
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)' }
# リクエストを作成
req = urllib2.Request(url, None, headers)
# レスポンスをディクショナリ形式で取得
dict = simplejson.load(urllib2.urlopen(req))
# ツイート一覧は 'results' というキーの中に格納されている。
template_values = {
"results" : dict['results'],
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication([('/', MainHandler)],
debug=False)
def main():
logging.getLogger().setLevel(logging.DEBUG)
run_wsgi_app(application)
if __name__ == "__main__":
main()
上記は簡単な例だが、もう少し条件を細かく指定してリクエストを投げることも当然可能である。Twitter API の詳細はこちらを参照のこと。
ここはひとつポチっとよろしく。

Twitter API ポケットリファレンス (POCKET REFERENCE)
posted with amazlet at 11.09.05
山本 裕介
技術評論社
売り上げランキング: 19589
技術評論社
売り上げランキング: 19589