本文整理汇总了Python中twython.Twython.get_authentication_tokens方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.get_authentication_tokens方法的具体用法?Python Twython.get_authentication_tokens怎么用?Python Twython.get_authentication_tokens使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twython.Twython
的用法示例。
在下文中一共展示了Twython.get_authentication_tokens方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TwythonAuthTestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
class TwythonAuthTestCase(unittest.TestCase):
def setUp(self):
self.api = Twython(app_key, app_secret)
self.bad_api = Twython('BAD_APP_KEY', 'BAD_APP_SECRET')
self.bad_api_invalid_tokens = Twython('BAD_APP_KEY', 'BAD_APP_SECRET',
'BAD_OT', 'BAD_OTS')
self.oauth2_api = Twython(app_key, app_secret, oauth_version=2)
self.oauth2_bad_api = Twython('BAD_APP_KEY', 'BAD_APP_SECRET',
oauth_version=2)
def test_get_authentication_tokens(self):
"""Test getting authentication tokens works"""
self.api.get_authentication_tokens(callback_url='http://google.com/',
force_login=True,
screen_name=screen_name)
def test_get_authentication_tokens_bad_tokens(self):
"""Test getting authentication tokens with bad tokens
raises TwythonAuthError"""
self.assertRaises(TwythonAuthError, self.bad_api.get_authentication_tokens,
callback_url='http://google.com/')
def test_get_authorized_tokens_bad_tokens(self):
"""Test getting final tokens fails with wrong tokens"""
self.assertRaises(TwythonError, self.bad_api.get_authorized_tokens,
'BAD_OAUTH_VERIFIER')
def test_get_authorized_tokens_invalid_or_expired_tokens(self):
"""Test getting final token fails when invalid or expired tokens have been passed"""
self.assertRaises(TwythonError, self.bad_api_invalid_tokens.get_authorized_tokens,
'BAD_OAUTH_VERIFIER')
def test_get_authentication_tokens_raises_error_when_oauth2(self):
"""Test when API is set for OAuth 2, get_authentication_tokens raises
a TwythonError"""
self.assertRaises(TwythonError, self.oauth2_api.get_authentication_tokens)
def test_get_authorization_tokens_raises_error_when_oauth2(self):
"""Test when API is set for OAuth 2, get_authorized_tokens raises
a TwythonError"""
self.assertRaises(TwythonError, self.oauth2_api.get_authorized_tokens,
'BAD_OAUTH_VERIFIER')
def test_obtain_access_token(self):
"""Test obtaining an Application Only OAuth 2 access token succeeds"""
self.oauth2_api.obtain_access_token()
def test_obtain_access_token_bad_tokens(self):
"""Test obtaining an Application Only OAuth 2 access token using bad app tokens fails"""
self.assertRaises(TwythonAuthError,
self.oauth2_bad_api.obtain_access_token)
def test_obtain_access_token_raises_error_when_oauth1(self):
"""Test when API is set for OAuth 1, obtain_access_token raises a
TwythonError"""
self.assertRaises(TwythonError, self.api.obtain_access_token)
示例2: TwythonAuthTestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
class TwythonAuthTestCase(unittest.TestCase):
def setUp(self):
self.api = Twython(app_key, app_secret)
def test_get_authentication_tokens(self):
'''Test getting authentication tokens works'''
self.api.get_authentication_tokens(callback_url='http://google.com/',
force_login=True,
screen_name=screen_name)
示例3: twitter_auth
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def twitter_auth():
_logout()
twitter = Twython(app.config['TWITTER_KEY'], app.config['TWITTER_SECRET'])
auth = twitter.get_authentication_tokens(callback_url=url_for("twitter_auth_callback", _external=True))
session['OAUTH_TOKEN'] = auth['oauth_token']
session['OAUTH_TOKEN_SECRET'] = auth['oauth_token_secret']
return redirect(auth['auth_url'])
示例4: create_tokens
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def create_tokens(objConfig, app_key, app_secret):
"""
Gets new auth tokens and writes them in 'config.ini' file
"""
twitter = Twython(app_key, app_secret)
auth = twitter.get_authentication_tokens()
OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
print "To get your PIN number please go to: "
print auth['auth_url']+"\n"
oauth_verifier = raw_input('Please enter your PIN number: ')
twitter = Twython(app_key, app_secret,
OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
final_step = twitter.get_authorized_tokens(oauth_verifier)
OAUTH_TOKEN = final_step['oauth_token']
OAUTH_TOKEN_SECRET = final_step['oauth_token_secret']
try:
twitter = Twython(app_key, app_secret,
OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
user = twitter.verify_credentials()['screen_name']
print "Login successful."
print "Account: "+user
# save oauth_tokens in file
cfgfile = open("tokens.ini",'w')
objConfig.add_section('user')
objConfig.set('user','OAUTH_TOKEN', OAUTH_TOKEN)
objConfig.set('user','OAUTH_TOKEN_SECRET', OAUTH_TOKEN_SECRET)
objConfig.write(cfgfile)
cfgfile.close()
return twitter
except TwythonError as e:
print e
示例5: get_url
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def get_url():
app_key = 'LvMwTBueTS3IsN7sLIoaIA'
app_secret = '0cdq8IZwccRMBPrwH9odVoCUaeLSH4RSx9df4'
access_token = '295398619-lSehg93ixJJ80M4DyOtwpSsmnFzP70Ld4bpRInXm'
access_token_secret = 'BttSbnwFY14Ysa68d5Xxcy3ZKi8eUgevNLgxq9Xo'
t = Twython(app_key=app_key,
app_secret=app_secret,
callback_url='http://127.0.0.1:5000/register')
auth_props = t.get_authentication_tokens()
oauth_token = auth_props['oauth_token']
print "Oauth_token:" + oauth_token
oauth_token_secret = auth_props['oauth_token_secret']
#a = auth_props['oauth_verifier']
print 'Connect to Twitter via: %s' % auth_props['auth_url']
auth_url = auth_props['auth_url']
t = Twython(app_key=app_key,
app_secret=app_secret,
oauth_token=oauth_token,
oauth_token_secret=oauth_token_secret)
#user_timeline = t.getUserTimeline(screen_name='nytimes')
return auth_url
示例6: retrieve_access_token
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def retrieve_access_token (self):
output.speak(_("Please wait while an access token is retrieved from Twitter."), True)
httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), Handler)
twitterDataOrig = str(self.config['oauth']['twitterData'])
trans = maketrans("-_~", "+/=")
twitterDataTrans = twitterDataOrig.translate(trans)
twitterData = b64decode(twitterDataTrans)
twitterData = literal_eval(twitterData)
tw = Twython(twitterData[0], twitterData[1], auth_endpoint='authorize', client_args = {'verify': False})
try:
auth = tw.get_authentication_tokens("http://127.0.0.1:8080")
except Exception as e:
logging.exception("Unable to get authentication tokens: %s" % str(e))
output.speak(_("Unable to get access token. Something went wrong, please call the developers."))
try:
webbrowser.open_new_tab(auth['auth_url'])
except Exception as e:
logging.exception("Unable to open web browser: %s" % str(e))
global logged, verifier
logged = False
while logged == False:
httpd.handle_request()
self.auth_handler = Twython(twitterData[0], twitterData[1], auth['oauth_token'], auth['oauth_token_secret'], client_args = {'verify': False})
token = self.auth_handler.get_authorized_tokens(verifier)
output.speak(_("Retrieved access token from Twitter."), True)
httpd.server_close()
data = [token['oauth_token'], token['oauth_token_secret']]
eData = dumps(data)
trans = maketrans("+/=", "-_~")
eData = b64encode(eData)
eData = eData.translate(trans)
self.config['oauth']['userData'] = eData
self.login()
del (httpd, auth, tw, token, logged, verifier, twitterData, twitterDataOrig, data, edata, self.auth_handler)
示例7: user_timeline
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def user_timeline(screenname, index=0):
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
twitter = Twython (APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
#OAUTH_TOKEN = auth['oauth_token']
#OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
#print OAUTH_TOKEN
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
#ACCESS_TOKEN = twitter.obtain_access_token()
#print twitter.verify_credentials()
#ACCESS_TOKEN = '701759705421639681-nutlNGruF7WZjq0kXZUTcKVbrnXs3vD'
#twitter = Twython(APP_KEY, access_token = ACCESS_TOKEN)
response = twitter.get_user_timeline(screen_name = screenname, count= 200, exclude_replies = True, include_rt = False)
L = []
for r in response:
L.append(r['text'])
'''
d = {}
d['text'] = r['text']
d['screenname'] = r['user']['screen_name']
d['date'] = r['created_at']
L.append(d)
'''
return L
示例8: retrieve_access_token
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def retrieve_access_token (self):
output.speak(_("Please wait while an access token is retrieved from Twitter."), True)
httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), Handler)
twitterDataOrig = str(self.config['oauth']['twitterData'])
trans = maketrans("-_~", "+/=")
twitterDataTrans = twitterDataOrig.translate(trans)
twitterData = b64decode(twitterDataTrans)
twitterData = literal_eval(twitterData)
tw = Twython(twitterData[0], twitterData[1], auth_endpoint='authorize')
try:
auth = tw.get_authentication_tokens("http://127.0.0.1:8080")
except SSLError:
output.speak(_("Sorry, we can't connect to Twitter. You may want to adjust your firewall or antivirus software appropriately"), True)
webbrowser.open_new_tab(auth['auth_url'])
global logged, verifier
logged = False
while logged == False:
httpd.handle_request()
self.auth_handler = Twython(twitterData[0], twitterData[1], auth['oauth_token'], auth['oauth_token_secret'])
token = self.auth_handler.get_authorized_tokens(verifier)
output.speak(_("Retrieved access token from Twitter."), True)
httpd.server_close()
data = [token['oauth_token'], token['oauth_token_secret']]
eData = dumps(data)
trans = maketrans("+/=", "-_~")
eData = b64encode(eData)
eData = eData.translate(trans)
self.config['oauth']['userData'] = eData
self.login()
del (httpd, auth, tw, token, logged, verifier, twitterData, twitterDataOrig, data, edata, self.auth_handler)
示例9: personalAuthentication
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def personalAuthentication():
allKeys = fileToList(TOKEN_FILE)
if len(allKeys[0]) > 4: # we've already saved the personal token
for key in authentication_keys.keys():
# The 4th item of the list of key data will be the key for a
# personal account
authentication_keys[key] = readToken(allKeys, key, 4)
else:
twitter = Twython(authentication_keys['APP_KEY'],
authentication_keys['APP_SECRET'])
auth = twitter.get_authentication_tokens()
import webbrowser
# Open a webpage with your twitter code
webbrowser.open(auth['auth_url'])
try:
auth_pin = input("Please enter the code from twitter: ")
except: # python 2.7
auth_pin = raw_input("Please enter the code from twitter: ")
# These are temporary, part of the overall authentication process
OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
twitter = Twython(authentication_keys['APP_KEY'],
authentication_keys['APP_SECRET'], OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
final_step = twitter.get_authorized_tokens(auth_pin)
authentication_keys['OAUTH_KEY'] = final_step['oauth_token']
authentication_keys['OAUTH_SECRET'] = final_step['oauth_token_secret']
writeKeys(authentication_keys, TOKEN_FILE)
示例10: Authentication
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def Authentication():
APP_KEY = 'b1WTyzKmLnG7KwnDcYpiQ'
APP_SECRET = 'gzKci8Gys0i831zt7gPq3fEpG4qq9kgOINfbKhS8'
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
OAUTH_TOKEN = auth ['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
webbrowser.open(auth['auth_url'])
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
final_step = twitter.get_authorized_tokens(str(raw_input("Please enter the PIN: "))) #atm pin must be entered through the terminal
OAUTH_TOKEN = final_step['oauth_token']
OAUTH_TOKEN_SECRET = final_step['oauth_token_secret']
print APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
return twitter
示例11: getRetweetCount
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def getRetweetCount(twe_id):
index=0
while (index <len(APP_KEYS)):
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
try:
twitter = Twython (APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
result = twitter.show_status(id=twe_id)
'''
#print result['user']['screen_name'] + " " + result['user']['description']
tweet['Usr_Screename'] = result['user']['screen_name']
tweet['Usr_Description'] = result['user']['description']
tweet['FavoriteCount'] = int(result['favorite_count'])
'''
return int(result['retweet_count'])
except Exception as e:
if "429 (Too Many Requests)" in str(e):
index += 1
print "App Exceeded: index = %d"%(index)
pass
elif "404 (Not Found)" in str(e):
return -1
elif "403 (Forbidden)" in str(e):
return -1
else:
print e
return ''
示例12: __oauth
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def __oauth(Rate_id):
""" twitter로부터 인증토큰을 받기 위한 함수 """
try:
twitter = Twython(current_app.config['TWIT_APP_KEY'],
current_app.config['TWIT_APP_SECRET'])
callback_svr = current_app.config['TWIT_CALLBACK_SERVER']
auth = twitter.get_authentication_tokens(
callback_url= callback_svr + \
url_for('.callback', Rate_id=Rate_id))
# 중간단계로 받은 임시 인증토큰은 최종인증을 위해 필요하므로 세션에 저장한다.
session['OAUTH_TOKEN'] = auth['oauth_token']
session['OAUTH_TOKEN_SECRET'] = auth['oauth_token_secret']
except TwythonError as e:
Log.error("__oauth(): TwythonError , "+ str(e))
session['TWITTER_RESULT'] = str(e)
return redirect(url_for('.show_all'))
# 트위터의 사용자 권한 인증 URL로 페이지를 리다이렉트한다.
return redirect(auth['auth_url'])
示例13: fetchTweets
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def fetchTweets(self, initialDate, finalDate, keywordCollection):
twitter = Twython(self._APP_KEY, self._APP_SECRET)
auth = twitter.get_authentication_tokens()
OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
twitterFinal = Twython(self._APP_KEY, self._APP_SECRET,
OAUTH_TOKEN,
OAUTH_TOKEN_SECRET)
sinceDate = initialDate.strftime("%Y-%m-%d")
untilDate = finalDate.strftime("%Y-%m-%d")
#query = keyword + ' since:' + initialDate.strftime("%Y/%m/%d") + ' until:' + finalDate.strftime("%Y/%m/%d")
keyword = ' OR '.join(keywordCollection)
keyword = urllib.parse.quote_plus(keyword)
# print(keyword)
query = keyword + ' since:' + sinceDate + ' until:' + untilDate
try:
search_results = twitter.search(q=query, count=100)
except TwythonError as e:
print(e)
return search_results
示例14: generate
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def generate(request):
context = RequestContext(request)
if request.method == 'POST':
form = BotTokenForm(request.POST)
if form.is_valid():
global yellow
yellow = Bot.objects.get(id=request.POST.get('user'))
twitter = Twython(settings.API, settings.API_SECRET)
# Request an authorization url to send the user to...
callback_url = request.build_absolute_uri(reverse('grabber.views.thanks'))
auth_props = twitter.get_authentication_tokens(callback_url)
# Then send them over there, durh.
request.session['request_token'] = auth_props
return HttpResponseRedirect(auth_props['auth_url'])
else:
print form.errors
else:
form = BotTokenForm()
return render_to_response('grabber/generate.html',{'form': form}, context)
示例15: twitter_token
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_authentication_tokens [as 别名]
def twitter_token(request):
## Tomamos el absolute path de donde esta corriendo
callback = request.build_absolute_uri()
if request.GET:
auth = request.session['twitter_auth']
ttoken = auth['oauth_token']
tsecret = auth['oauth_token_secret']
verifier = request.GET['oauth_verifier']
twitter = Twython(settings.TW_KEY, settings.TW_SECRET, ttoken, tsecret)
oauth = twitter.get_authorized_tokens(verifier)
token = oauth['oauth_token']
secret = oauth['oauth_token_secret']
else:
twitter = Twython(settings.TW_KEY, settings.TW_SECRET)
## Se arma la URL para autenticar
auth = twitter.get_authentication_tokens(callback_url=callback)
url = auth['auth_url']
request.session['twitter_auth'] = auth
template = 'twitter_token.html'
return render(request, template, locals())