Python-twoauthでTwitterのOAuth認証
こんばんは。gumi の濱咲です。
Twitter の Basic 認証が終了したので、OAuth 認証の方法を紹介いたします。
使用するライブラリは「Python-twoauth」にします。
Basic 認証は非対応です。SearchAPI がありませんが、その辺は適宜。
Applicationの作成
- dev.twitter.comで「Register an app」を選択します。
- NewTwitterApplicationで作成するアプリの情報を入力します。Application Typeは「Client」で作成します。全ての情報はあとから変更できるので、今は適当でもかまいません。
- 登録が完了すると、Consumer Key と Consumer Secret が発行されます。
PIN から Access Token, Access Token Secret の取得
Python-twoauth の git に例があるので、そのまま使用します。
http://github.com/techno/python-twoauth/blob/master/sample/get_access_token.py
get_access_token.pyを実行します。
$ python get_access_token.py
Consumer Key, Consumer Secret を聞いてきますので入力。
Consumer Key: [your application's consumer key] Consumer secret: [your application's consumer secret]
PIN 取得用の URL が表示されるので、アクセスして「許可」。
Authorize URL: http://twitter.com/oauth/authorize?oauth_token=[your request oauth token]
許可したあとのページで表示される PIN(7桁の数字)を入力します。
PIN: [your PIN]
認証が成功すると Access Token と Access Token Secret が表示されるので保存しておきます。
Access token: [your access token] Access token secret: [your access token secret]
OAuth認証でTwitterに投稿してみる
「twoauth」フォルダと同じ階層に「PostOAuthTest.py」というファイルを作って以下のように記述します。
# -*- coding: utf-8 -*- import twoauth class PostOAuthTest(): # Login twitter = twoauth.api( " your application's consumer key " , " your application's consumer secret " , " your access token ", " your access token secret ") # Post twitter.status_update(u"Test Post") def main(): PostOAuthTest() if __name__ == "__main__": main()
実行は以下で出来ます。
$ python PostOAuthTest.py
以上の 結果、投稿した Tweet には
日本語環境なら「[your application's name]から」
英語環境なら「via [your application's name]」
と表記されているはずです!