本文整理汇总了Python中tweepy.OAuthHandler.get_access_token方法的典型用法代码示例。如果您正苦于以下问题:Python OAuthHandler.get_access_token方法的具体用法?Python OAuthHandler.get_access_token怎么用?Python OAuthHandler.get_access_token使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tweepy.OAuthHandler
的用法示例。
在下文中一共展示了OAuthHandler.get_access_token方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SanchanOAuthHandler
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
class SanchanOAuthHandler():
def __init__(self, config):
self.config = config
self.keys = self.config.OAuthKeys()
self.oauth = OAuthHandler(self.keys['consumer_key'],
self.keys['consumer_secret'],
secure = True
)
self.oauth.set_access_token(self.keys['access_token_key'], self.keys['access_token_secret'])
def authenticate(self):
return self.oauth
def request(self):
print "Authorize this app via this URL: "
print self.oauth.get_authorization_url()
pincode = raw_input('Then, input the proposed PIN: ')
try:
self.oauth.get_access_token(verifier=pincode)
except error.TweepError, e:
print e
print "[EMERG] Authentication error!"
sys.exit(1)
print "Put these access keys into your config.yml:"
print "access_token: " + self.oauth.access_token.key
print "access_token_secret: " + self.oauth.access_token.secret
sys.exit(0)
示例2: _get_twitter_access
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
def _get_twitter_access(self, username):
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
url = auth.get_authorization_url()
print 'Go here: %s and enter the corresponding PIN' % url
pin = raw_input('PIN:')
auth.get_access_token(pin)
return (auth.access_token.key, auth.access_token.secret)
示例3: Twit
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
class Twit(object):
def __init__(self,consumer_token, access_token=None):
if not isinstance(consumer_token, Token): raise Exception("consumer_token is invalid type!")
self.auth = OAuthHandler(consumer_token.key, consumer_token.secret)
self.api = None
if access_token != None and isinstance(access_token, Token):
# ok
self.auth.set_access_token(access_token.key, access_token.secret)
self.api = self._get_api(self.auth)
def _get_api(self, auth):
return API(auth,retry_count=3,cache=tweepy.MemoryCache(timeout=60))
def get_auth_url(self):
return self.auth.get_authorization_url()
def get_access_token(self, pin):
self.auth.get_access_token(pin)
self.api = self._get_api(self.auth)
return Token(self.auth.access_token.key, self.auth.access_token.secret)
@classmethod
def get_msg_length(cls, msg):
"""
https://dev.twitter.com/docs/api/1.1/get/help/configuration
"""
msg = re.sub(RegexHttpUrl, "0123456789012345678901", msg)
msg = re.sub(RegexHttpsUrl, "01234567890123456789012", msg)
return len(msg)
@classmethod
def validate_msg(cls, msg):
"""
Args:
msg: str, 投稿するメッセージ
Return:
(is_valid:bool, reminder:int)
"""
max_msg_length = 140
is_valid = False
msg_length = cls.get_msg_length(msg)
reminder = 140 - msg_length
if 0 < msg_length <= max_msg_length: is_valid = True
return (is_valid, reminder)
def post(self, msg):
return self.api.update_status(status=msg)
def verify_credentials(self, include_entities=True, skip_status=False):
return self.api.verify_credentials(include_entities=include_entities, skip_status=skip_status)
def get_user_timeline(self, screen_name, count=50):
return self.api.user_timeline(screen_name=screen_name, count=count)
def destroy_status(self, status_id):
return self.api.destroy_status(id=status_id)
示例4: __init__
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
class WTweetUser:
def __init__(self):
_CONSUMER_KEY = '9o4scrLHTFt7NzyVxD5Q'
_CONSUMER_SECRET = 'xlrPmai1QgNTRQTf86inp1bzEFLgEXD7XuN5ZENKAU'
self.__auth_handler = OAuthHandler(_CONSUMER_KEY, _CONSUMER_SECRET)
self.__access_token = None
def set_access_token(self, access_token):
self.__access_token = self.__auth_handler.set_access_token(key=access_token['key'], secret=access_token['secret'])
def get_auth_handler(self):
return self.__auth_handler
def logout(self):
with loadfile('w') as f:
f.truncate()
f.close()
print 'logout successful!'
def login(self):
try:
auth_url = self.__auth_handler.get_authorization_url()
print 'give me a pin code from url: {0}'.format(auth_url)
verifier = raw_input('enter a pin code: ').strip()
self.__auth_handler.get_access_token(verifier=verifier)
access_token = { 'key': self.__auth_handler.access_token.key, 'secret': self.__auth_handler.access_token.secret }
with loadfile('w+') as f:
f.truncate()
f.write(JSONEncoder().encode(access_token))
f.close()
except TweepError as err:
print err.__str__()
return WTweetTimeline(self)
def is_login(self):
with loadfile('r') as f:
cfg = f.readline()
f.close()
access_token = JSONDecoder().decode(cfg)
if 'key' in access_token and 'secret' in access_token:
self.set_access_token(access_token=access_token)
return True
else:
return False
def get_timeline(self):
with loadfile('r') as f:
cfg = f.readline()
f.close()
self.set_access_token(JSONDecoder().decode(cfg))
return WTweetTimeline(self)
示例5: run
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
def run():
print 'Input your application info.'
consumer_key = raw_input('Consumer Key: ')
consumer_secret = raw_input('Consumer Secret: ')
auth = OAuthHandler(consumer_key,
consumer_secret)
print "Visit the following url and allow TweetHandler to access."
print '>>> %s' % auth.get_authorization_url()
print ''
vcode = raw_input('Enter verification code: ')
token = auth.get_access_token(vcode)
print 'OK. You can setup TweetHander with following code.'
print """ ----
from tweethandler import TweetHandler
import logging
th = TweetHandler('%s',
'%s',
'%s',
'%s')
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
th.setLevel(logging.DEBUG)
logger.addHandler(th)
logger.info('Your log message')
""" % (consumer_key, consumer_secret,
token.key, token.secret)
示例6: accessToken
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
def accessToken(self):
if self.session.access_token:
# return the token (TODO: does it expire?)
auth = OAuthHandler(self.client_id, self.client_secret);
auth.set_access_token( self.session.access_token.key
, self.session.access_token.secret)
return auth
if self.session.request_token:
# Exchange the request token with an authorization token.
token = self.session.request_token
self.session.request_token = None
auth = OAuthHandler( self.client_id, self.client_secret )
auth.set_request_token(token.key, token.secret)
try:
self.session.access_token = auth.get_access_token(self.request.vars.oauth_verifier)
except tweepy.TweepError:
print 'Error! Failed to get access token.'
print self.session.access_token
return auth
return None
示例7: callback
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
def callback(request):
"""
Receive the Oauth token back from Twitter
"""
verifier = request.GET.get('oauth_verifier')
if verifier is None:
response = HttpResponseRedirect(reverse('experiment_main'))
return response
oauth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
token = request.session.get('unauthed_token_twitterexp', None)
if token is None:
request.session['auth_error'] = True
return HttpResponseRedirect(ROOT_URL)
request.session['auth_error'] = False
# remove the request token now we don't need it
request.session.delete('unauthed_token_twitterexp')
oauth.set_request_token(token[0], token[1])
# get the access token and store
try:
oauth.get_access_token(verifier)
except TweepError:
print 'Error, failed to get access token'
request.session['auth_error'] = True
return HttpResponseRedirect(ROOT_URL)
request.session['access_key_twitterexp'] = oauth.access_token.key
request.session['access_secret_twitterexp'] = oauth.access_token.secret
api = get_api(request)
twitter_user = api.me()
twitter_user = add_or_update_twitter_user(twitter_user)
experiment_user, user = get_or_add_user(twitter_user)
user.set_password('')
user = authenticate(username=twitter_user.twitter_id, password='')
login(request, user)
response = HttpResponseRedirect(reverse('experiment_start'))
return response
示例8: get_auth
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
def get_auth():
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
if not os.path.exists(CREDENTIALS_FILE):
authorization_url = auth.get_authorization_url()
webbrowser.open_new(authorization_url)
pin = input('PIN: ')
auth.get_access_token(pin)
cred = {
'ACCESS_TOKEN': auth.access_token,
'ACCESS_SECRET': auth.access_token_secret
}
fp = open(CREDENTIALS_FILE, 'wb')
pickle.dump(cred, fp)
fp.close()
else:
fp = open(CREDENTIALS_FILE, 'rb')
cred = pickle.load(fp)
fp.close()
auth.set_access_token(cred['ACCESS_TOKEN'], cred['ACCESS_SECRET'])
return auth
示例9: twitter_oauth_verify
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
def twitter_oauth_verify(request):
redirect_url = reverse('landing')
request_token_key = request.session.pop('request_token_key', '')
request_token_secret = request.session.pop('request_token_secret', '')
handler = OAuthHandler(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
handler.set_request_token(request_token_key, request_token_secret)
verifier = request.GET.get('oauth_verifier', '')
try:
handler.get_access_token(verifier)
except TweepError:
pass
else:
user = authenticate(access_token_key=handler.access_token.key, access_token_secret=handler.access_token.secret, consumer_key=settings.CONSUMER_KEY, consumer_secret=settings.CONSUMER_SECRET)
login(request, user)
redirect_url = request.session.pop('next', redirect_url)
return redirect(redirect_url)
示例10: testoauth
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
def testoauth(self):
auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
# test getting access token
auth_url = auth.get_authorization_url()
print('Please authorize: ' + auth_url)
verifier = raw_input('PIN: ').strip()
self.assert_(len(verifier) > 0)
access_token = auth.get_access_token(verifier)
self.assert_(access_token is not None)
# build api object test using oauth
api = API(auth)
s = api.update_status('test %i' % random.randint(0, 1000))
api.destroy_status(s.id)
示例11: twitter_callback
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
def twitter_callback(request):
"""
Twitterからのコールバック時に呼び出される。
:param request: リクエストオブジェクト
:type request: django.http.HttpRequest
:return: 遷移先を示すレスポンスオブジェクト
:rtype: django.http.HttpResponse
"""
# セッションからリクエストトークンを取得する
request_token = request.session.get('request_token')
if not request_token:
request.session.clear()
return HttpResponse('Unauthorized', status=401)
# Twitterからの返却値を取得する
oauth_token = request.GET.get('oauth_token')
oauth_verifier = request.GET.get('oauth_verifier')
# セッションの値とTwitterからの返却値が一致しない場合は処理を中断する
if request_token.get('oauth_token') != oauth_token:
request.session.clear()
return HttpResponse('Unauthorized', status=401)
# アクセストークンを取得する
oauth_handler = OAuthHandler(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
oauth_handler.request_token = request_token
access_token = oauth_handler.get_access_token(oauth_verifier)
# 認証処理を実行する
authenticated_user = authenticate(access_token=access_token)
if authenticated_user:
login(request, authenticated_user)
else:
request.session.clear()
return HttpResponse('Unauthorized', status=401)
# ログイン後に遷移すべき画面にリダイレクトする
url = request.session.get('next', getattr(settings, 'AFTER_LOGIN_URL', '/'))
return HttpResponseRedirect(url)
示例12: OAuthHandler
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
from tweepy import OAuthHandler
CONSUMER_KEY = 'place key here'
CONSUMER_SECRET = 'place secret here'
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth_url = auth.get_authorization_url()
print('Please authorize: ' + auth_url)
verifier = input('PIN: ').strip()
auth.get_access_token(verifier)
print("ACCESS_KEY = '%s'" % auth.access_token.key)
print("ACCESS_SECRET = '%s'" % auth.access_token.secret)
示例13: open
# 需要导入模块: from tweepy import OAuthHandler [as 别名]
# 或者: from tweepy.OAuthHandler import get_access_token [as 别名]
import tweepy
import json
from tweepy import AppAuthHandler
from tweepy import OAuthHandler
with open("private/oauth-config.json", "r") as config:
oauth_config = (json.loads(config.read()))
consumer_key = oauth_config.get('consumer-key')
consumer_secret = oauth_config.get('consumer-secret')
oauth = OAuthHandler(consumer_key, consumer_secret)
try:
redirect_url = oauth.get_authorization_url()
except tweepy.TweepError:
print('Error: failed to get the redirect URL.')
access_token = oauth.get_access_token(verifier='enter pin here')