昨日、
Google App Engine Hackathon Disc.3 に参加してきました。わたくしはTutorial Aで外部データとの連携をがむばることに。
テーマは、
Python Twitterというライブラリーを使って、GAEからTwitter API(JSON)をコールしてみようというもの。必要なライブラリーは、
Python Twitterと
simplejsonの2つです。
Python Twitterはデフォルトのままでは動きません。動作するように書き換えたやつを、
ハカソンリポにコミットしております。だいぶひどい修正です。主な変更点は以下のとおり。
- 1487行目のDiff
def _GetUsername(self):
- return os.getenv('USER') or \
- os.getenv('LOGNAME') or \
- os.getenv('USERNAME') or \
- os.getlogin() or \
- 'nobody'
+ return 'nobody'
- 1394行目のDiff
def _FetchUrl(self,
url,
post_data=None,
parameters=None,
no_cache=None):
- # Build the extra parameters dict
- extra_params = {}
- if self._default_params:
- extra_params.update(self._default_params)
- if parameters:
- extra_params.update(parameters)
-
- # Add key/value parameters to the query string of the url
- url = self._BuildUrl(url, extra_params=extra_params)
-
- # Get a url opener that can handle basic auth
- opener = self._GetOpener(url, username=self._username, password=self._password)
-
- encoded_post_data = self._EncodePostData(post_data)
-
- # Open and return the URL immediately if we're not going to cache
- if encoded_post_data or no_cache or not self._cache or not self._cache_timeout:
- url_data = opener.open(url, encoded_post_data).read()
- opener.close()
- else:
- # Unique keys are a combination of the url and the username
- if self._username:
- key = self._username + ':' + url
- else:
- key = url
-
- # See if it has been cached before
- last_cached = self._cache.GetCachedTime(key)
-
- # If the cached version is outdated then fetch another and store it
- if not last_cached or time.time() >= last_cached + self._cache_timeout:
- url_data = opener.open(url, encoded_post_data).read()
- opener.close()
- self._cache.Set(key, url_data)
- else:
- url_data = self._cache.Get(key)
-
- # Always return the latest version
- return url_data
+ method = urlfetch.GET
+ data = {}
+ if post_data:
+ method = urlfetch.POST
+ data.update(post_data)
+ params = {}
+ if parameters:
+ params.update(parameters)
+ url = self._BuildUrl(url, extra_params=params)
+ headers = {}
+ encoded_post_data = self._EncodePostData(post_data)
+ base64string = base64.encodestring('%s:%s' % (self._username,
self._password))[:-1]
+ headers = {'Authorization': "Basic %s" % base64string}
+ if post_data:
+ headers.update({'Content-type':'application/x-www-form-urlencoded'})
+ return urlfetch.fetch(url, encoded_post_data, method,
headers, False).content
これで一通り動きます。
import twitter
api = twitter.Api(username='[Twitterのユーザ名]', password=[Twitterのパスワード])
mystatuses = api.GetFriendsTimeline()
for status in mystatuses :
print status.text
allstatuses = api.GetPublicTimeline()
for status in allstatuses :
print status.text
GAE上で使った例も
ハカソンリポにコミットしています。ハカソンでは、このライブラリーを使って個別に色々と遊びました。ただしマージできているのが、
PyAMFを使ってFlashにエコーをはくやつだけです。あとはフレンドの写真をひたすら表示していくなどの面白いアプリを作っていらっしゃる方もいたので、できればマージしたい・・・。
事務局の皆様、参加者の皆様お疲れ様でした!ハッピーコーディング(
松尾さんの格言w)できました。
0 comments: