映画の評判に関するデータベースの内容をブラウザに表示する
いよいよ大詰めに入ってきましたね。
データベースの内容をブラウザに表示するプログラムを作成する。
前回までで映画データベースは出来上がっているので、後はこれをユーザーに見せるだけ。
楽勝ですね、ささーっと一時間くらいでできてしまいました。
【mainpage.py】
#!/usr/bin/env python # -*- coding: utf-8 -*- import movies query = movies.Movies.gql('ORDER BY update_date DESC,tweet_count DESC') first_movie = query.get() fetched_movies = query.fetch(20) print '''<html> <head> <title>Movitter</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link type="text/css" rel="stylesheet" href="/stylesheets/mainpage.css" /> </head> <body> <img src="images/movitter_logo.png" alt="MovitterLogo" border="0"> <br>''' for fetched_movie in fetched_movies: print 'タイトル:' + '<a href="http://movie.nifty.com/' + fetched_movie.detail_url.encode('utf-8') + '" target="_blank" >' + fetched_movie.title.encode('utf-8') +'</a>' print '<br>' print 'スコア:' + str(fetched_movie.tweet_count) print '<br>' print 'good:' + str(fetched_movie.score_good) + '/bad:' + str(fetched_movie.score_bad) + '/other:' + str(fetched_movie.score_other) print '<br>' if fetched_movie.tweet_count > 0: graph_length = 300 * fetched_movie.tweet_count / first_movie.tweet_count graph_good = fetched_movie.score_good * 100 / fetched_movie.tweet_count graph_bad = fetched_movie.score_bad * 100 / fetched_movie.tweet_count graph_other = fetched_movie.score_other * 100 / fetched_movie.tweet_count print '<img src="http://chart.apis.google.com/chart?chs=' + str(graph_length) + 'x30&chd=t:' + str(graph_good) + '|' + str(graph_bad) + '|' + str(graph_other) + '&cht=bhs&chco=00FF7F,ff0000,FFD700" alt="chart" border="0">' print '<br>' print '<hr>' print '''</body> </html>'''
データベースから最新タイトルを20件取得して、Twitterでつぶやかれている回数が多い順に並べています。
さらに、各タイトルについて、つぶやきの内容(良い/悪い/その他)の割合で色分けした積み上げ棒グラフを描画するようにしています。
これは、ちょっとした算数と「google chart api」の力で、簡単に実現できてしまいました。
後はこのプログラムを、ルートのurlと紐付けておしまいです。
【app.yaml】
application: movie-twitter version: 1 runtime: python api_version: 1 handlers: - url: /stylesheets static_dir: stylesheets - url: /images static_dir: images - url: /get_movie_title script: get_movie_title.py login: admin - url: /get_tweet script: get_tweet.py login: admin - url: /.* script: mainpage.py
画像とかスタイルシートとかの静的ファイルの扱いも、ここで指定するようですね。
このあたりは独特かも。
それでは早速デプロイして、結果を見てみましょう。
Twitterをスキャンする処理は、本番環境でずっと回し続けているので、それなりの結果が表示されてくるはずです。
おーバッチリではないですか!
予想通り、今はアバターがダントツ首位なんですね。
他の映画についても、世間で話題になっている順にきちんと並んでいるような気がします。
次週までに、レイアウトが見苦しいのをなんとかしたいですね。
あとは、まとめエントリを書くことで今回の連載プログラミングMovitter編を終わりにしたいと思います。