LoginSignup
1
1

More than 5 years have passed since last update.

Python2.7でTwitter APIのoauth_tokenとoauth_token_secretを取得するコードのサンプル

Last updated at Posted at 2012-12-26
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# oauth2モジュールをインストールする必要がある。
import oauth2 as oauth
from urlparse import parse_qs
import sys

CONSUMER_KEY = 'YOUR-CONSUMER-KEY'        # CONSUMER_KEYを指定する。
CONSUMER_SECRET = 'YOUR-CONSUMER-SECRET'  # CONSUMER_SECRETを指定する。
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
AUTHORIZE_URL = 'https://api.twitter.com/oauth/authorize'
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'

consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
client = oauth.Client(consumer)
resp, content = client.request(REQUEST_TOKEN_URL, 'GET')
request_token = parse_qs(content)
authorize_url = "%s?oauth_token=%s" % (
        AUTHORIZE_URL,
        request_token['oauth_token'][0]
        )
message = 'Authorize this app at %s and enter the PIN#' % (authorize_url)
oauth_verifier = ''
while len(oauth_verifier) <= 0:
    oauth_verifier = raw_input(message)
else:
    token = oauth.Token(
            request_token['oauth_token'][0],
            request_token['oauth_token_secret'][0]
            )
    client = oauth.Client(consumer, token)
    resp, content = client.request(
            ACCESS_TOKEN_URL,
            "POST",
            body="oauth_verifier=%s" % oauth_verifier
            )
    access_token = parse_qs(content)
    if 'oauth_token' in access_token and 'oauth_token_secret' in access_token:
        print "oauth_token: %s\noauth_token_secret: %s" % (
                access_token['oauth_token'][0],
                access_token['oauth_token_secret'][0]
                )
    else:
        sys.stderr.write('PIN is invalid.\n')
1
1
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
1
1