Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PyYoshi/940267 to your computer and use it in GitHub Desktop.
Save PyYoshi/940267 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Twiter-OAUTHのWebクライアント形式で認証サンプル
#
# 設定ファイルの書式 (ConfigParser)
# [TOKENS]
# ACCESS_TOKEN=HOGE
# ACCESS_SECRET_TOKEN=FUGA
# "#"や";"が最初につく行はスキップ
#
# 必須:Tweepy
from tweepy import OAuthHandler, TweepError
from wsgiref.simple_server import make_server
import threading
import ConfigParser
import webbrowser
import os
CONSUMER_KEY = "HOGE"
CONSUMER_SECRET = "FUGA"
CALLBACK_URL = "http://127.0.0.1:8923/login/"
SETTINGS_FILE = "settings.ini"
SETTINGS_FILE_PATH = os.path.join(os.path.dirname(__file__), SETTINGS_FILE)
config = ConfigParser.ConfigParser()
def get_atoken(env,res):
if env['PATH_INFO']=='/login/':
if env['REQUEST_METHOD']=='GET':
QUERY_STRING = env['QUERY_STRING']
if QUERY_STRING:
tmp = QUERY_STRING.split('&')
oauth_token = tmp[0].split('=')[1]
oauth_verifier = tmp[1].split('=')[1]
#魔法の1行(笑
threading.Thread(target=httpd.shutdown).start()
auth.set_request_token(auth.request_token.key, auth.request_token.secret)
try:
auth.get_access_token(oauth_verifier)
config.add_section('TOKENS')
config.set('TOKENS', 'ACCESS_TOKEN', auth.access_token.key)
config.set('TOKENS', 'ACCESS_SECRET_TOKEN', auth.access_token.secret)
#設定の書き出し
fp = open(SETTINGS_FILE_PATH, 'w')
config.write(fp)
fp.close()
print 'Authenticated Successfully!'
res('200 OK',[('Content-type','text/html')])
html = """
<html>
<head>
<title>Authenticated Successfully!</title>
</head>
<body>
Authenticated Successfully!
</body>
</html>
"""
return html
except TweepError:
print 'Error! Failed to get access token.'
res('401 Unauthorized',[('Content-type','text/html')])
html = """
<html>
<head>
<title>Unauthorized!</title>
</head>
<body>
Unauthorized!
</body>
</html>
"""
return html
try:
config.read(SETTINGS_FILE_PATH)
atoken = config.get('TOKENS', 'ACCESS_TOKEN')
astoken = config.get('TOKENS', 'ACCESS_SECRET_TOKEN')
except ConfigParser.NoSectionError:
atoken = None
astoken = None
if atoken != None:
if astoken != None:
print 'Authenticated Successfully!'
print 'atoken: '+ atoken
print 'astoken: '+ astoken
else:
try:
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK_URL)
redirect_url = auth.get_authorization_url()
#ここの処理は認証用URLをウェブブラウザで開くようにしている。適宜要変更
try:
if webbrowser.open(redirect_url) == False:
raise webbrowser.Error
except webbrowser.Error:
sys.exit(1)
httpd = make_server('',8923,get_atoken)
httpd.serve_forever()
except TweepError:
print 'Error! Failed to get request token.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment