当前位置: 首页>>代码示例>>Python>>正文


Python Twython.obtain_access_token方法代码示例

本文整理汇总了Python中twython.Twython.obtain_access_token方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.obtain_access_token方法的具体用法?Python Twython.obtain_access_token怎么用?Python Twython.obtain_access_token使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twython.Twython的用法示例。


在下文中一共展示了Twython.obtain_access_token方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TwythonAuthTestCase

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [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)
开发者ID:FRKodes,项目名称:twython,代码行数:59,代码来源:test_auth.py

示例2: SearchTweets

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
    def SearchTweets(self):
        APP_KEY = 'PpFTrSSEFiW8QD6CrQTjw'
        APP_SECRET = 'ka6YXiNPGNDLYqdpAaTqFb70Rp6qVqzZCLLiK7tSKI'
        twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
        ACCESS_TOKEN = twitter.obtain_access_token()
        twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)

        term = str(self.ui.tweet_search_line.text())
        if not term == '':
            tweetcount = self.ui.tweetspinBox.value()
            search = twitter.search(q=term, result_type='recent', count=tweetcount)
            #for tweet in search['statuses']:
            for tweetnum, tweet in enumerate(search['statuses']):
                print tweet
                # {u'contributors': None, u'truncated': False, u'text': u'In our third of five LCS games this week, we face scoreboard leaders Cloud 9 http://t.co/Hg1ouV1Ihn', u'in_reply_to_status_id': None, u'id': 368076075248545792L, u'favorite_count': 0, u'source': u'web', u'retweeted': False, u'coordinates': None, u'entities': {u'symbols': [], u'user_mentions': [], u'hashtags': [], u'urls': [{u'url': u'http://t.co/Hg1ouV1Ihn', u'indices': [77, 99], u'expanded_url': u'http://www.team-dignitas.net/articles/news/League-of-Legends/3794/LCS-Team-Dignitas-vs.-Cloud-9/', u'display_url': u'team-dignitas.net/articles/news/\u2026'}]}, u'in_reply_to_screen_name': None, u'in_reply_to_user_id': None, u'retweet_count': 0, u'id_str': u'368076075248545792', u'favorited': False, u'user': {u'follow_request_sent': None, u'profile_use_background_image': True, u'default_profile_image': False, u'id': 20734751, u'verified': False, u'profile_text_color': u'0C3E53', u'profile_image_url_https': u'https://si0.twimg.com/profile_images/958663238/fullcolor-head_normal.jpg', u'profile_sidebar_fill_color': u'FFF7CC', u'entities': {u'url': {u'urls': [{u'url': u'http://t.co/9oS5fsRQyt', u'indices': [0, 22], u'expanded_url': u'http://www.team-dignitas.net', u'display_url': u'team-dignitas.net'}]}, u'description': {u'urls': []}}, u'followers_count': 45843, u'profile_sidebar_border_color': u'000000', u'id_str': u'20734751', u'profile_background_color': u'BADFCD', u'listed_count': 486, u'profile_background_image_url_https': u'https://si0.twimg.com/profile_background_images/378800000040895525/bde7e8dc3837d2737376336a13fb0dac.jpeg', u'utc_offset': 3600, u'statuses_count': 13908, u'description': u'Team Dignitas - The official twitter page for one of the worlds leading professional gaming companies.', u'friends_count': 430, u'location': u'Surrey', u'profile_link_color': u'FF0000', u'profile_image_url': u'http://a0.twimg.com/profile_images/958663238/fullcolor-head_normal.jpg', u'following': None, u'geo_enabled': True, u'profile_banner_url': u'https://pbs.twimg.com/profile_banners/20734751/1352062186', u'profile_background_image_url': u'http://a0.twimg.com/profile_background_images/378800000040895525/bde7e8dc3837d2737376336a13fb0dac.jpeg', u'screen_name': u'TeamDignitas', u'lang': u'en', u'profile_background_tile': False, u'favourites_count': 25, u'name': u'Team Dignitas', u'notifications': None, u'url': u'http://t.co/9oS5fsRQyt', u'created_at': u'Fri Feb 13 00:20:50 +0000 2009', u'contributors_enabled': False, u'time_zone': u'London', u'protected': False, u'default_profile': False, u'is_translator': False}, u'geo': None, u'in_reply_to_user_id_str': None, u'possibly_sensitive': False, u'lang': u'en', u'created_at': u'Thu Aug 15 18:25:49 +0000 2013', u'in_reply_to_status_id_str': None, u'place': None, u'metadata': {u'iso_language_code': u'en', u'result_type': u'recent'}}
                tweetitem = Tweet(tweet['created_at'], tweet['user']['name'], tweet['user']['screen_name'],
                                  tweet['text'], tweet['entities']['hashtags'], tweet['id_str'], tweet['user']['id'],
                                  tweet['metadata']['iso_language_code'], tweet['user']['profile_image_url'])
                if tweet['metadata']['iso_language_code'] == 'en':
                    print 'nope'
                    self.TweetList.append(tweetitem)
                # for index, detail in enumerate(tweetdetails):
                #     print tweetnum, index, detail
                #
                # self.ui.tweet_table.setItem(tweetnum, index, QtGui.QTableWidgetItem(detail))

            #print Tweet.get_tweet_count()
            #print tweetlist
            # self.ui.tweet_table.setRowCount(len(search))

            # self.updateSignal.emit()
            self.BuildTweetXML()
开发者ID:eknowles,项目名称:CasparCGEsportsClient,代码行数:34,代码来源:client.py

示例3: Twitter

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
class Twitter(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.app_key = 'BLqRs3ajA0A621p1Yojo1gVFj'
        self.app_secret = 'A7Xa43LiJTaLvFVUVRRsm8yqF48sJd6RJ0kCUDOh8yJXTxyIjL'

        self.twitter = Twython(self.app_key, self.app_secret, oauth_version=2)
        self.twitter = Twython(self.app_secret, access_token=self.twitter.obtain_access_token())

    def run(self):
        self.get_tweets()

    def get_tweets(self):
        while True:
            result = self.twitter.search(q='#gdgssa', count=10)
            cur = Database.get_instance().get_cursor()
            for tweet in result['statuses']:
                cur.execute('SELECT count(*) as total FROM tweets WHERE id=' + str(tweet['id']))
                data = cur.fetchone()

                if data[0] <= 0:
                    cur.execute(
                        "INSERT INTO tweets (id, text, user, sent) values (" + str(tweet['id']) + ",'" + tweet['text'] + "','" +
                        tweet['user']['name'] + "', 0)")
            time.sleep(10)
开发者ID:marloncarvalho,项目名称:candy-dispenser,代码行数:28,代码来源:twitter.py

示例4: twitter_auth2

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
def twitter_auth2(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET):
    """
    Returns a Twython object that is fully logged in and ready to go.
    """
    twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET, oauth_version=2)
    ACCESS_TOKEN = twitter.obtain_access_token()
    return Twython(CONSUMER_KEY, CONSUMER_SECRET, access_token=ACCESS_TOKEN)
开发者ID:lexwraith,项目名称:barhack,代码行数:9,代码来源:twitter.py

示例5: startTwitter

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
def startTwitter():
  global APP_KEY
  APP_KEY= 'UO1UHczEF8XCyYNJ1PMZtFfR0'
  APP_SECRET='5JhKexPUEceWxPlfdzM6b1aRLR1ZTQ18vU9zUvAWnJZ4YZ4uIr'
  twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
  global ACCESS_TOKEN 
  ACCESS_TOKEN = twitter.obtain_access_token()
开发者ID:Kadhim,项目名称:low-pass,代码行数:9,代码来源:twitter.py

示例6: index

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
def index():
	try:
		APP_KEY = "KEY";
		APP_SECRET = "SECRET";

		twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
		ACCESS_TOKEN = twitter.obtain_access_token()
		text = request.form['text']

		twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)

		
		search = twitter.cursor(twitter.search,q=text,count=1000)
		
			
		totalSent = 0
		i = 0 
		for result in search:
			if i > 500:
				break;
			totalSent += TextBlob(result['text']).sentiment.polarity
			i += 1

		return render_template('index.html',name = "the twitter gods rated " + text, finding = str(wordOfIt(round(totalSent/i,2))),errorThing = None)
	except:	
		return render_template('index.html',name = None, finding = None, errorThing =  "There was an error with your input. Please try something else!")
开发者ID:ColdSauce,项目名称:bestr,代码行数:28,代码来源:hello.py

示例7: getFeatures

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
def getFeatures(filename):
    csvfile = pd.read_csv(filename)  # Reading .csv files containing tweets.
    tweet_ids = csvfile["id_str"]  # Copying the 'id_str' attribute values to a item.
    length = len(tweet_ids)  # Getting the length of 'tweet_ids'.

    df = DataFrame(d, index=[0])  # Creating a DataFrame

    twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
    ACCESS_TOKEN = twitter.obtain_access_token()
    twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
    # Generating Access Token

    for i in range(0, length):
        status = twitter.show_status(id=tweet_ids[i])
        d["id"] = status["id_str"].encode("utf-8")
        d["created_at"] = status["created_at"].encode("utf-8")
        d["from_user"] = status["user"]["screen_name"].encode("utf-8")
        d["followers_count"] = status["user"]["followers_count"]
        d["friends_count"] = status["user"]["friends_count"]
        d["statuses_count"] = status["user"]["statuses_count"]
        d["verified"] = status["user"]["verified"]
        d["location"] = 0 if (len(status["user"]["location"].encode("utf-8")) == 0) else 1
        d["text"] = status["text"].encode("utf-8")
        d["retweet_count"] = status["retweet_count"]
        d["favorite_count"] = status["favorite_count"]
        d["hashtag_count"] = len(status["entities"]["hashtags"])
        d["url_count"] = len(status["entities"]["urls"])
        d["mentions_count"] = len(status["entities"]["user_mentions"])
        if len(status["entities"]["urls"]) > 0:
            for x in range(0, len(status["entities"]["urls"])):
                d["links"] += status["entities"]["urls"][x]["expanded_url"].encode("utf-8") + "  "
        df = df.append(d, ignore_index=True)
        df.to_csv("NSamples.csv")  # Saving file to disk
        d["links"] = ""
    print "\nAll Done!"
开发者ID:abhisesh,项目名称:TweetCred,代码行数:37,代码来源:getfeatures.py

示例8: scrape

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
def scrape(arg):
	results = {}
	twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
	ACCESS_TOKEN = twitter.obtain_access_token()

	twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
	friends = twitter.get_friends_ids(screen_name = arg)
	#hard cap for time
	limit = 10

	for follower_id in friends['ids']:
		if limit > 0 :
			params = {'user_id':follower_id, 'count':3 }
			tweets = twitter.get_user_timeline(**params)
			for tweet in tweets:
				encoded = tweet['text'].encode("utf8")
				results = dict(Counter(results) + Counter(text_tags(encoded)))
				#random.choice(news)
				#f.write(str(text_tags(encoded)))
			limit = limit - 1
		else:
			break
		#print results
	key = max(results.iteritems(), key=operator.itemgetter(1))[0]
	n = random.choice(news)
	return [key, n]
开发者ID:jpchen,项目名称:CrazyCorrelations,代码行数:28,代码来源:twitter.py

示例9: __init__

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
    def __init__(self, *args, **kwargs):
        logger.info(kwargs)
        import copy

        apikeys = copy.copy(kwargs.pop('apikeys', None))

        if not apikeys:
            raise MissingArgs('apikeys is missing')

        self.apikeys = copy.copy(apikeys)  # keep a copy
        # self.crawler_id = kwargs.pop('crawler_id', None)

        oauth2 = kwargs.pop('oauth2', False)  # default to use oauth2 (application level access, read-only)

        if oauth2:
            # apikeys.pop('oauth_token')
            # apikeys.pop('oauth_token_secret')
            twitter = Twython(apikeys['app_key'], apikeys['app_secret'], apikeys['oauth_token'],
                              apikeys['oauth_token_secret'], oauth_version=1)
            access_token = twitter.obtain_access_token()
            kwargs['access_token'] = access_token
            apikeys.pop('app_secret')

        kwargs.update(apikeys)

        super(TwitterAPI, self).__init__(*args, **kwargs)
开发者ID:aschattney,项目名称:tweetf0rm,代码行数:28,代码来源:twitter_api.py

示例10: home

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
def home(request):
    try:
        access_object = TwitterAccess.objects.get()
    except:
        connection = Twython(APP_KEY, APP_SECRET, oauth_version=2)
        access_token = connection.obtain_access_token()
        ta = TwitterAccess(token=access_token)
        ta.save()
    else:
        access_token = access_object.token
    stream = []
    twitter = Twython(APP_KEY, access_token=access_token)
    tweets = twitter.search(q="#eluna15 OR #eluna2015", count=100)

    for tweet in tweets['statuses']:
        data = {}
        data['text'] = tweet['text']
        if tweet['entities']['urls']:
            data['url'] = tweet['entities']['urls'][0]['url']
        data['created_at'] = tweet['created_at']
        # data['url'] = tweet['entities']['urls']['url']
        data['screen_name'] = tweet['user']['screen_name']
        data['profile_image_url_https'] = tweet['user']['profile_image_url_https']
        stream.append(data)
    return HttpResponse(json.dumps(stream), content_type="application/json")
开发者ID:masudk,项目名称:IGeLU2014AppBackEnd,代码行数:27,代码来源:views.py

示例11: get_access_token

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
def get_access_token(self):
    TWITTER_CONSUMER_KEY = settings.TWITTER_CONSUMER_KEY
    TWITTER_CONSUMER_SECRET = settings.TWITTER_CONSUMER_SECRET

    twitter = Twython(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, oauth_version=2)
    ACCESS_TOKEN = twitter.obtain_access_token()

    return HttpResponse(ACCESS_TOKEN, status=200, content_type='application/json')
开发者ID:traversi,项目名称:smart-album-creator,代码行数:10,代码来源:api.py

示例12: get_twitter

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
def get_twitter(app_key=None, app_secret=None, search='python', location='', **kwargs):
    """Location may be specified with a string name or latitude, longitude, radius"""
    if not app_key:
        from settings_secret import TWITTER_API_KEY as app_key
    if not app_secret:
        from settings_secret import TWITTER_API_SECRET as app_secret
    twitter = Twython(app_key, app_secret, oauth_version=2)
    return Twython(app_key, access_token=twitter.obtain_access_token())
开发者ID:Redwa,项目名称:twip,代码行数:10,代码来源:tweets.py

示例13: authenticate

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
	def authenticate(self):
		twitter = Twython(self.app_key, self.app_secret, oauth_version=2)

		# Store the access token so we don't have to keep requesting Twitter for it
		if (Twitter.ACCESS_TOKEN == ''):
			Twitter.ACCESS_TOKEN = twitter.obtain_access_token()

		api = Twython(self.app_key, access_token=Twitter.ACCESS_TOKEN)

		return api
开发者ID:imclab,项目名称:PhotoFlow-server,代码行数:12,代码来源:twitter.py

示例14: get

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
    def get(self, request):
        APP_KEY = '5SraJUH4d4H2b5LjADeWhC3wW'
        APP_SECRET = 'FyPxiCPeHPtr6dxll6bgRi0xlnQGIKonATxkibv5SakP5jJbIS'

        twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
        ACCESS_TOKEN = twitter.obtain_access_token()
        twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
        sRes = twitter.search(
                q='guwahati #guwahati :)', result_type='mixed', count=1)
        return Response(sRes, status=200)
开发者ID:kunalbhagawati,项目名称:startupguwahati,代码行数:12,代码来源:restViews.py

示例15: search_for

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import obtain_access_token [as 别名]
def search_for(str):
	oauth = get_oauthentication()
	twitter = Twython(oauth['APP_KEY'], oauth['APP_SECRET'], oauth_version=2)
	ACCESS_TOKEN = twitter.obtain_access_token()
	twitter = Twython(oauth['APP_KEY'], access_token=ACCESS_TOKEN)
	
	search = twitter.search_gen(str)
	# search = twitter.get_home_timeline()
			
	for result in search:
		print result['text']
开发者ID:bryanjimenez,项目名称:empanada,代码行数:13,代码来源:chatbox.py


注:本文中的twython.Twython.obtain_access_token方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。