• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python oauth.read_token_file函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twitter.oauth.read_token_file函数的典型用法代码示例。如果您正苦于以下问题:Python read_token_file函数的具体用法?Python read_token_file怎么用?Python read_token_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: login

def login():

    # Go to http://twitter.com/apps/new to create an app and get these items
    # See also http://dev.twitter.com/pages/oauth_single_token

    APP_NAME = ''
    CONSUMER_KEY = '2JRLM23QHyLyBABuqg4tqQ'
    CONSUMER_SECRET = 'avpoP356DDKbHtTRiicjKBC01yXqfaI8QCgfZebmjA'
    TOKEN_FILE = 'auth/twitter.oauth'

    '''
        consumer_key = '2JRLM23QHyLyBABuqg4tqQ'
        consumer_secret = 'avpoP356DDKbHtTRiicjKBC01yXqfaI8QCgfZebmjA'
        access_token = '20692466-4kkQfaO8V0e2cVBDzfYg4EkFdQO9u0CNZLoP8Xma5'
        access_token_secret = '0bUGan28R0Dt2f0NIIjA2AcCkNUelANx674aWUH9Oj08f'
    '''
    try:
        (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE)
    except IOError, e:
        (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY,
                CONSUMER_SECRET)

        if not os.path.isdir('auth'):
            os.mkdir('auth')

        write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
开发者ID:weikengary,项目名称:CS4242AS3,代码行数:26,代码来源:twitter__login.py


示例2: __init__

    def __init__(self, connection):
        self.logger = logging.getLogger(self.__name)
        self.dbconnection = connection.dbconnection

        self.output_channel = "#%s" % connection.config.get(
            "lowflyingrocks",
            "channel")

        # OAUTH_FILENAME = os.environ.get(
        #    'HOME',
        #    '') + os.sep + '.lampstand_oauth'
        OAUTH_FILENAME = connection.config.get("twitter", "oauth_cache")
        CONSUMER_KEY = connection.config.get("twitter", "consumer_key")
        CONSUMER_SECRET = connection.config.get("twitter", "consumer_secret")

        try:
            if not os.path.exists(OAUTH_FILENAME):
                oauth_dance(
                    "Lampstand", CONSUMER_KEY, CONSUMER_SECRET,
                    OAUTH_FILENAME)

            self.oauth_token, self.oauth_token_secret = read_token_file(
                OAUTH_FILENAME)

            self.twitter = Twitter(
                auth=OAuth(
                    self.oauth_token,
                    self.oauth_token_secret,
                    CONSUMER_KEY,
                    CONSUMER_SECRET),
                secure=True,
                domain='api.twitter.com')
        except:
            self.twitter = False
开发者ID:aquarion,项目名称:lampstand,代码行数:34,代码来源:lowflying.py


示例3: oauth_url_dance

def oauth_url_dance(
    consumer_key, consumer_secret, callback_url, oauth_verifier, pre_verify_token_filename, verified_token_filename
):
    # Verification happens in two stages...

    # 1) If we haven't done a pre-verification yet... Then we get credentials
    # from Twitter that will be used to sign our redirect to them, find the
    # redirect, and instruct the Javascript that called us to do the redirect.
    if not os.path.exists(CREDS_PRE_VERIFIY):
        twitter = Twitter(auth=OAuth("", "", consumer_key, consumer_secret), format="", api_version=None)
        oauth_token, oauth_token_secret = parse_oauth_tokens(twitter.oauth.request_token(oauth_callback=callback_url))
        write_token_file(pre_verify_token_filename, oauth_token, oauth_token_secret)

        oauth_url = "https://api.twitter.com/oauth/authorize?" + urllib.urlencode({"oauth_token": oauth_token})
        return oauth_url

    # 2) We've done pre-verification, hopefully the user has authed us in
    # Twitter and we've been redirected to. Check we are and ask for the
    # permanent tokens.
    oauth_token, oauth_token_secret = read_token_file(CREDS_PRE_VERIFIY)
    twitter = Twitter(
        auth=OAuth(oauth_token, oauth_token_secret, consumer_key, consumer_secret), format="", api_version=None
    )
    oauth_token, oauth_token_secret = parse_oauth_tokens(twitter.oauth.access_token(oauth_verifier=oauth_verifier))
    write_token_file(verified_token_filename, oauth_token, oauth_token_secret)
    return oauth_token, oauth_token_secret
开发者ID:scraperwiki,项目名称:twitter-search-tool,代码行数:26,代码来源:twsearch.py


示例4: get_twitter

def get_twitter(debug=False):
    # This is secret and key of my app "ibread"
    # this is set up on twitter.com
    CONSUMER_KEY = "NXdiUFv7ZqhO5Ojr8GocA"
    CONSUMER_SECRET = "CMRgb7BHpHLlcZ0NqHF06pWbFtv1zPqV98KTaFxV2YQ"
    #oauth_filename = os.environ.get('HOME', '') + os.sep + '.my_twitter_oauth'
    oauth_filename = sys.path[0] + os.sep + 'my_twitter_oauth'
    
    if debug:
        print oauth_filename
    
    # if did not found the auth file, create one
    if not os.path.exists(oauth_filename):
        oauth_dance("ibread", CONSUMER_KEY, CONSUMER_SECRET, oauth_filename)

    oauth_token, oauth_token_secret = read_token_file(oauth_filename)
    
    if debug:
        print oauth_token, oauth_token_secret

    tw = Twitter(
        auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET),
        secure=True,
        api_version='1',
        domain='api.twitter.com')
    
    return tw
开发者ID:ibread,项目名称:ibread,代码行数:27,代码来源:report.py


示例5: login_and_get_twitter

def login_and_get_twitter():

    # Go to http://twitter.com/apps/new to create an app and get these items
    # See also http://dev.twitter.com/pages/oauth_single_token

    CREDENTIALS_FILE = './twitter_credentials.txt'
    TOKEN_FILE = './twitter_token.oauth'  # in the current directory
#     try:
    (app_name, consumer_key, consumer_secret) = read_credentials_file(CREDENTIALS_FILE)
#     except IOError:
#         print(TOKEN_FILE + " not found")
    
    try:
        (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE)
        logging.info('read token from file success')
    except IOError as e:
        logging.info('read token from file failed, requesting new token')
        (oauth_token, oauth_token_secret) = oauth_dance(app_name, consumer_key,
                consumer_secret)
  
        write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)

    return twitter.Twitter(domain='api.twitter.com', api_version='1.1',
                        auth=twitter.oauth.OAuth(oauth_token, oauth_token_secret,
                        consumer_key, consumer_secret))
开发者ID:Baphomet1105,项目名称:twitMiner-tweet-collector.py,代码行数:25,代码来源:login.py


示例6: __init__

    def __init__(self, bot):
        config = ConfigParser.RawConfigParser()
        config.read(os.path.dirname(__file__) + os.sep + bot + os.sep + "omni.cfg")

        consumer_key = config.get(bot, 'consumer_key')
        consumer_secret = config.get(bot, 'consumer_secret')

        oauth = config.get(bot, 'oauth')
        oauth_filename = os.path.dirname(__file__) + os.sep + bot + os.sep + oauth
        oauth_token, oauth_token_secret = read_token_file(oauth_filename)

        self.handle = config.get(bot, 'handle')
        self.corpus = os.path.dirname(__file__) + os.sep + bot + os.sep + config.get(bot, 'corpus')
        self.method = config.get(bot, 'tweet_method')
        self.twitter = Twitter(domain='search.twitter.com')
        self.twitter.uriparts = ()
        self.poster = Twitter(
            auth=OAuth(
                oauth_token,
                oauth_token_secret,
                consumer_key,
                consumer_secret
            ),
            secure=True,
            api_version='1.1',
            domain='api.twitter.com')
开发者ID:carriercomm,项目名称:omnibot,代码行数:26,代码来源:bot.py


示例7: login

def login():

    config = ConfigParser.ConfigParser()
    config.readfp(open("twitter.config","rb"))

    # Go to http://twitter.com/apps/new to create an app and get these items
    # See also http://dev.twitter.com/pages/oauth_single_token

    APP_NAME = config.get('account', 'appname')
    CONSUMER_KEY = config.get('account', 'consumerkey')
    CONSUMER_SECRET = config.get('account', 'consumersecret')
    ACCESS_TOKEN = config.get('account', 'accesstoken')
    ACCESS_TOKEN_SECRET = config.get('account', 'accesstokensecret')
    TOKEN_FILE = 'out/twitter.oauth'

    try:
        (oauth_token, oauth_token_secret) = read_token_file(TOKEN_FILE)
    except IOError, e:
        if ACCESS_TOKEN != None and ACCESS_TOKEN_SECRET != None:
            oauth_token = ACCESS_TOKEN
            oauth_token_secret = ACCESS_TOKEN_SECRET
        else:
            (oauth_token, oauth_token_secret) = oauth_dance(APP_NAME, CONSUMER_KEY,
                CONSUMER_SECRET)

        if not os.path.isdir('out'):
            os.mkdir('out')

        write_token_file(TOKEN_FILE, oauth_token, oauth_token_secret)
开发者ID:jinpeng,项目名称:TwitterHavest,代码行数:29,代码来源:twitter__login.py


示例8: from_oauth_file

    def from_oauth_file(cls, filepath=None):
        """Get an object bound to the Twitter API using your own credentials.

        The `twitter` library ships with a `twitter` command that uses PIN
        OAuth. Generate your own OAuth credentials by running `twitter` from
        the shell, which will open a browser window to authenticate you. Once
        successfully run, even just one time, you will have a credential file
        at ~/.twitter_oauth.

        This factory function reuses your credential file to get a `Twitter`
        object. (Really, this code is just lifted from the `twitter.cmdline`
        module to minimize OAuth dancing.)
        """
        if filepath is None:
            # Use default OAuth filepath from `twitter` command-line program.
            home = os.environ.get("HOME", os.environ.get("USERPROFILE", ""))
            filepath = os.path.join(home, ".twitter_oauth")

        oauth_token, oauth_token_secret = read_token_file(filepath)

        twitter = cls(
            auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET),
            api_version="1.1",
            domain="api.twitter.com",
        )

        return twitter
开发者ID:Parsely,项目名称:birding,代码行数:27,代码来源:twitter.py


示例9: oauth_login_ecig

def oauth_login_ecig(
    app_name=APP_NAME, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, token_file="out/twitter.ecig.oauth"
):

    try:
        (access_token, access_token_secret) = read_token_file(token_file)
    except IOError, e:
        print >>sys.stderr, "Cannot get tokens"
开发者ID:kimjeong,项目名称:FDA_Social_Media_Hbase_Python,代码行数:8,代码来源:oauth_login_ecig.py


示例10: main

def main():
    oauth_filename = os.environ.get('HOME', '') + os.sep + '.twitter_oauth'
    oauth_filename = os.path.expanduser(oauth_filename)

    oauth_token, oauth_token_secret = read_token_file(oauth_filename)
    auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)
    twitter = Twitter(
        auth=auth,
        secure=True,
        api_version='1',
        domain='api.twitter.com'
    )

    try:
        tweets = pickle.load(open('tweets.pickle'))
    except:
        tweets = []
    print "Horay! I've got %s tweets from the file!" % len(tweets)

    # используем nltk
    featuresets = [(get_features(tweet), tweet['good']) for tweet in tweets]
    total = len(featuresets)
    train_set, test_set = featuresets[total/2:], featuresets[:total/2]

    classifier = nltk.NaiveBayesClassifier.train(train_set)
    #tree_classifier = nltk.DecisionTreeClassifier.train(train_set)
    print nltk.classify.accuracy(classifier, test_set)
    classifier.show_most_informative_features(10)
    #print nltk.classify.accuracy(tree_classifier, test_set)


    if MILK:
        # используем milk
        learner = milk.defaultclassifier()
        get_milk_keys(get_features(tweet) for tweet in tweets)
        features = [get_milk_features(tweet) for tweet in tweets]
        labels = [tweet['good'] for tweet in tweets]
        model = learner.train(features, labels)


    ids = set(tweet['id'] for tweet in tweets)

    tweet_iter = twitter.statuses.friends_timeline(count=COUNT)
    for tweet in tweet_iter:
        if tweet.get('text') and tweet['id'] not in ids:
            print '%s: %s' % (tweet['user']['name'], tweet['text'])
            print '[nltk] I think, this tweet is interesting with probability', classifier.prob_classify(get_features(tweet)).prob(True)
            if MILK:
                print '[milk] I think, this tweet is interesting with probability', model.apply(get_milk_features(tweet))
            good = raw_input('Interesting or not?\n(y/n): ') in ('y', 'Y', 'G', 'g')
            tweet['good'] = good
            tweets.append(tweet)



    pickle.dump(tweets, open('tweets.pickle', 'w'))
开发者ID:svetlyak40wt,项目名称:tweet-filter,代码行数:56,代码来源:client.py


示例11: oauth_login

def oauth_login(
    app_name=APP_NAME,
    consumer_key=CONSUMER_KEY,
    consumer_secret=CONSUMER_SECRET,
    token_file="/home/hadoop/proj/social_media/py/out/twitter.oauth",
):

    try:
        (access_token, access_token_secret) = read_token_file(token_file)
    except IOError, e:
        print >> sys.stderr, "Cannot get tokens"
开发者ID:kimjeong,项目名称:FDA_Social_Media_Hbase_Python,代码行数:11,代码来源:collect_twitter_search_terms_ver2.py


示例12: oauth_login

def oauth_login(app_name=APP_NAME,consumer_key=CONSUMER_KEY,consumer_secret=CONSUMER_SECRET,token_file='out/twitter_oauth'):

	try:
		(oauth_token, oauth_token_secret) = read_token_file(token_file)
	except IOError, e:
		(oauth_token, oauth_token_secret) = oauth_dance('deathcape', consumer_key, consumer_secret)

		if not os.path.isdir('out'):
			os.mkdir('out')
		write_token_file(token_file,oatuh_token,oauth_token_secret)
		print >> sys.stderr, "OAuth Success. Token file stored to", token_file
开发者ID:deathcape,项目名称:deathcapeProject,代码行数:11,代码来源:friends_followers__get_friends.py


示例13: get_twitter_stream

def get_twitter_stream():

	try:
		(oauth_token, oauth_token_secret)= read_token_file(token_file)
	except IOError, e:
		(oauth_token, oauth_token_secret)=oauth_dance (app_name, consumer_key, consumer_secret)

		if not os.path.isdir(token_path):
			os.mkdir(token_path)
	
		write_token_file(token_file, oauth_token, oauth_token_secret)
开发者ID:mrazakhan,项目名称:tweetlog,代码行数:11,代码来源:pt2.py


示例14: __init__

    def __init__(self, connection):
        self.channelMatch = [
            re.compile(
                '%s: Shorten that( URL)?' %
                connection.nickname,
                re.IGNORECASE),
            # 0
            re.compile(
                '%s: Shorten (.*?)\'s? (link|url)' %
                connection.nickname,
                re.IGNORECASE),
            # 1
            re.compile(
                '%s: Shorten this (link|url): (.*)$' %
                connection.nickname,
                re.IGNORECASE),
            # 2
            re.compile('.*https?\:\/\/', re.IGNORECASE)]  # 3
        self.dbconnection = connection.dbconnection
        self.bitly = bitly_api.Connection(
            connection.config.get(
                "bitly", "username"), connection.config.get(
                "bitly", "apikey"))

        self.yt_service = gdata.youtube.service.YouTubeService()
        self.yt_service.ssl = True

        self.lastlink = {}

        OAUTH_FILENAME = os.environ.get(
            'HOME',
            '') + os.sep + '.lampstand_oauth'
        CONSUMER_KEY = connection.config.get("twitter", "consumer_key")
        CONSUMER_SECRET = connection.config.get("twitter", "consumer_secret")

        if not os.path.exists(OAUTH_FILENAME):
            oauth_dance(
                "Lampstand", CONSUMER_KEY, CONSUMER_SECRET,
                OAUTH_FILENAME)

        self.oauth_token, self.oauth_token_secret = read_token_file(
            OAUTH_FILENAME)

        self.twitter = Twitter(
            auth=OAuth(
                self.oauth_token,
                self.oauth_token_secret,
                CONSUMER_KEY,
                CONSUMER_SECRET),
            secure=True,
            domain='api.twitter.com')
开发者ID:scraperdragon,项目名称:lampstand,代码行数:51,代码来源:weblink.py


示例15: create_oauth

def create_oauth(oauthfile, consumer_key, consumer_secret):
    """
    Creates and OAuth object using the tokens from the oauthfile and the
    consumer_key and consumer_secret. If the file doesn't exists we prompt the
    user to initiate the oauth dance, and save the token and token secret in
    the oauthfile
    """
    try:
        token, token_secret = read_token_file(oauthfile)
    except IOError:
        token, token_secret = do_oauth_dance(oauthfile, consumer_key,
                                                         consumer_secret)

    return OAuth(token, token_secret, consumer_key, consumer_secret)
开发者ID:domroselli,项目名称:twitterspy,代码行数:14,代码来源:twitterspy.py


示例16: main

def main() :
	'''
		main needs a description...

	'''
	import codecs
	import datetime
	import os.path
	import traceback

	options = doOptions()

	olsonName = getOlsonName()
	if None is not olsonName :
		from pytz import timezone
		global _timeZone
		_timeZone = timezone( olsonName )

	oauthFile = tweePath( options, 'auth' )
	# should add code to handle the handshake...
	# from twitter.oauth_dance import oauth_dance
	# oauth_dance( "the Command-Line Tool", CONSUMER_KEY, CONSUMER_SECRET, options['oauth_filename'])
	oauth_token, oauth_token_secret = read_token_file( oauthFile )

	if options.saveLog :
		options.outFile = codecs.open( options.outFilePath, mode='a', encoding='utf8' )

	twitter = Twitter( auth=OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET ),
						api_version='1.1', )

	printText( '-=-=' * 10, options )
	printText( 'Starting @ %s\n' % datetime.datetime.utcnow(), options )

	myLists = twitter.lists.list()
	for aList in myLists :
		if options.list == aList[ 'slug' ] :
			options.listId = aList[ 'id' ]

	setattr( options, 'screen_name', twitter.account.verify_credentials()[ 'screen_name' ] )

	try :
		run( twitter, options )
	except KeyboardInterrupt :
		pass
	except :
		traceback.print_exc()

	if None != options.outFile :
		if not options.outFile.closed :
			options.outFile.close()
开发者ID:dijatool,项目名称:twee,代码行数:50,代码来源:twee.py


示例17: do_tool_oauth

def do_tool_oauth():
    if not os.path.exists(CREDS_VERIFIED):
        if len(sys.argv) < 3:
            result = "need-oauth"
        else:
            (callback_url, oauth_verifier) = (sys.argv[1], sys.argv[2])
            result = oauth_url_dance(CONSUMER_KEY, CONSUMER_SECRET, callback_url, oauth_verifier, CREDS_PRE_VERIFIY, CREDS_VERIFIED)
        # a string means a URL for a redirect (otherwise we get a tuple back with auth tokens in)
        if type(result) == str:
            set_status_and_exit('auth-redirect', 'error', 'Permission needed from Twitter', { 'url': result } )

    oauth_token, oauth_token_secret = read_token_file(CREDS_VERIFIED)
    tw = twitter.Twitter(auth=twitter.OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET))
    return tw
开发者ID:scraperdragon,项目名称:twitter-follows-tool,代码行数:14,代码来源:twfollow.py


示例18: __init__

   def __init__(self, consumer_uri, token_uri):
      # TODO: deal with storing in a database
      self.consumer_key, self.consumer_secret = load_consumer_from_file(consumer_uri)

      if not os.path.exists(token_uri):
         raise EasyTwitterError(u"Run %s.__init__ manually to authorize this application" % __package__)

      self.token_key, self.token_secret = oauth.read_token_file(token_uri)

      self.twitter = Twitter(
        auth=oauth.OAuth(self.token_key, self.token_secret, self.consumer_key, self.consumer_secret),
        secure=True,
        api_version='1',
        domain='api.twitter.com')
开发者ID:pfoley,项目名称:yot,代码行数:14,代码来源:__init__.py


示例19: __init__

 def __init__(self):
     """If the user is not authorized yet, do the OAuth dance and save the
     credentials in her home folder for future incovations.
     Then read the credentials and return the authorized Twitter API object."""
     if not os.path.exists(OAUTH_FILENAME):
         oauth_dance("@swissbolli's Monday Twitter Backup",
             CONSUMER_KEY, CONSUMER_SECRET, OAUTH_FILENAME
         )
     oauth_token, oauth_token_secret = read_token_file(OAUTH_FILENAME)
     self.api = Twitter(
         auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET),
         retry=5
     )
     user = self.api.account.settings(_method='GET')
     self.screen_name = user['screen_name']
开发者ID:bbolli,项目名称:twitter-monday,代码行数:15,代码来源:monday.py


示例20: oauth_helper

def oauth_helper():
    oauth_verifier = request.args.get("oauth_verifier")
    # Pick back up credentials from ipynb_oauth_dance
    oauth_token, oauth_token_secret = read_token_file(OAUTH_FILE)
    _twitter = twitter.Twitter(
        auth=twitter.OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), format="", api_version=None
    )
    oauth_token, oauth_token_secret = parse_oauth_tokens(_twitter.oauth.access_token(oauth_verifier=oauth_verifier))
    # This web server only needs to service one request, so shut it down
    shutdown_after_request = request.environ.get("werkzeug.server.shutdown")
    shutdown_after_request()
    # Write out the final credentials that can be picked up after the following
    # blocking call to webserver.run().
    write_token_file(OAUTH_FILE, oauth_token, oauth_token_secret)
    return "%s %s written to %s" % (oauth_token, oauth_token_secret, OAUTH_FILE)
开发者ID:paudan,项目名称:python-scripts,代码行数:15,代码来源:production_api.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python oauth.write_token_file函数代码示例发布时间:2022-05-27
下一篇:
Python clock.ThreadedClock类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap