9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Twitter の OAuth認証 (Python3)

Posted at

次の記事にある内容をなぞってみました。
[Python] OAuth認証でTwitter連携/ログインを実装する

consumer_token と consumer_secret から redirect_url を得ます

get_redirect_url.py
#! /usr/bin/python
#
#	get_redirect_url.py
#
#					Nov/29/2018
# ------------------------------------------------------------------
import tweepy
consumer_token = ""
consumer_secret = ""

auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
redirect_url = auth.get_authorization_url()
print(redirect_url)
# ------------------------------------------------------------------

実行結果

$ ./get_redirect_url.py 
https://api.twitter.com/oauth/authorize?oauth_token=7w-KbQAA12345BBAA8ABZ16_S1g

Twitter にログインした状態で
このアドレスにアクセスすると、次のような画面になります。
twitter_nov2901.png

Authorize app をクリックすると、
別の画面に飛び、アドレスバーに、oauth_token と oauth_verifier が表示されます。
次のような感じです。

https://ekzemplaro.org/?oauth_token=FqyTcwAABBBA9AA8AACCZ16ZAiM&oauth_verifier=86cg6dZPbAAplhikGWk12XHnSDbOSIHC

oauth_token と oauth_verifier から access_token を得ます。

get_access_token.py
#! /usr/bin/python
#
#	get_access_token.py
#
#						Nov/29/2018
# ------------------------------------------------------------------
import	sys

from requests_oauthlib import OAuth1Session
from urllib.parse import parse_qsl

base_url = 'https://api.twitter.com/'
access_token_url = base_url + 'oauth/access_token'

consumer_key = ""
consumer_secret = ""

oauth_token = ""
oauth_verifier = ""

sys.stderr.write("*** 開始 ***\n")

twitter = OAuth1Session(
		consumer_key,
		consumer_secret,
		oauth_token,
		oauth_verifier,
	)

response = twitter.post(
		access_token_url,
		params={'oauth_verifier': oauth_verifier}
	)

access_token = dict(parse_qsl(response.content.decode("utf-8")))

print(access_token)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行結果

$ ./get_access_token.py 
{'oauth_token': '1066884441803311104-UXNebbb9Hg7wTVanxTv9UoHQ7dRqG6', 'oauth_token_secret': 'yfNZjqAZbwMFrvqlkI9GaaaaAEw3BMq3whGJadQibegYU', 'user_id': '3166889501999311104', 'screen_name': 'testabcd001'}

ここで得られた oauth_token と oauth_token_secret を使って testabcd001 の timeline を読んだりできます。

 

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?