コード例 #1
0
ファイル: getFriends.py プロジェクト: chengjun/Research
class test(unittest.TestCase):
    
    consumer_key=''
    consumer_secret=''
    
    def __init__(self):
            """ constructor """
    
    def getAtt(self, key):
        try:
            return self.obj.__getattribute__(key)
        except Exception as e:
            print(e)
            return ''
    
    def setAccessToken(self, key, secret):
        self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
        self.auth.setAccessToken(key, secret)
        self.api = API(self.auth)
        
    def basicAuth(self, source, username, password):
        self.auth = BasicAuthHandler(username, password)
        self.api = API(self.auth,source=source)
        
    def friends(self):
        timeline = self.api.friends()
        for line in timeline:
            self.obj = line
            fid = self.getAtt("id")
            name = self.getAtt("screen_name")
            print("friends---"+ str(fid) +":"+ name)
コード例 #2
0
ファイル: getFriends.py プロジェクト: shunsunsun/Research
class test(unittest.TestCase):

    consumer_key = ''
    consumer_secret = ''

    def __init__(self):
        """ constructor """

    def getAtt(self, key):
        try:
            return self.obj.__getattribute__(key)
        except Exception as e:
            print(e)
            return ''

    def setAccessToken(self, key, secret):
        self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
        self.auth.setAccessToken(key, secret)
        self.api = API(self.auth)

    def basicAuth(self, source, username, password):
        self.auth = BasicAuthHandler(username, password)
        self.api = API(self.auth, source=source)

    def friends(self):
        timeline = self.api.friends()
        for line in timeline:
            self.obj = line
            fid = self.getAtt("id")
            name = self.getAtt("screen_name")
            print("friends---" + str(fid) + ":" + name)
コード例 #3
0
ファイル: web.py プロジェクト: wangsongf/python
    def GET(self):
        try:
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
            auth.access_token = session['access_token']
            api = API(auth)
            user = api.verify_credentials()
            fan = []
            next_cursor = -1
            while next_cursor != 0:
                timeline = api.followers(user.id, '', '', '', next_cursor)
                if isinstance(timeline, tuple):
                    next_cursor = timeline[1]
                    for line in timeline[0]:
                        fid = line.__getattribute__("id")
                        fname = line.__getattribute__("screen_name")
                        fan.append((fid, fname))

                else:
                    next_cursor = 0
                    for line in timeline:
                        fid = line.__getattribute__("id")
                        fname = line.__getattribute__("screen_name")
                        fan.append((fid, fname))

            friend = []
            next_cursor = -1
            while next_cursor != 0:
                timeline = api.friends(user.id, '', '', '', next_cursor)
                if isinstance(timeline, tuple):
                    next_cursor = timeline[1]
                    for line in timeline[0]:
                        frid = line.__getattribute__("id")
                        frname = line.__getattribute__("screen_name")
                        friend.append((frid, frname))
                else:
                    next_cursor = 0
                    for line in timeline:
                        frid = line.__getattribute__("id")
                        frname = line.__getattribute__("screen_name")
                        friend.append((frid, frname))
            #获取我的粉丝中还不是我的关注对象
            fanNotAttention = list(set(fan).difference(set(friend)))
            nu = len(fanNotAttention)
            if nu == 0:
                return render_template('noattentionok.html', nu=nu)
            else:
                return render_template('noattention.html',
                                       nu=nu,
                                       fanNotAttention=fanNotAttention)

        except:
            info = "亲,系统繁忙,请稍后再试......,系统在3秒后自动返回..."
            return render_template('error.html', info=info.decode('utf-8'))
コード例 #4
0
ファイル: sina_twitter.py プロジェクト: luo123qwe/djproject
 def GET(self):
     access_token=session.get('access_token',None)
     if not access_token:
         auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET,web.ctx.get('homedomain')+'/callback')
         #获得新浪微博的认证url地址
         auth_url = auth.get_authorization_url()
         logger.debug("认证地址为:%s"%auth_url)
         #在session中保存request_token,用于在新浪微博认证通过后换取access_token
         session.request_token=auth.request_token
         web.seeother(auth_url)
     else:
         auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
         auth.access_token=access_token
         api=API(auth)
         user=api.verify_credentials()
         friends=api.friends()
         return render_template('index.html',friends=friends,user=user)
コード例 #5
0
ファイル: test_influence.py プロジェクト: alexdiao/3805
def compute(str_inf_pk):
    try:
        inf = Influence.objects.get(pk=str_inf_pk)
        auth = OAuthHandler(settings.SINA_CONSUMER_KEY, settings.SINA_CONSUMER_SECRET)
        #auth.setToken(inf.sina_key, inf.sina_secret)
        auth.setToken('128021658f2bfdae185d89bdffb3cede', '1713185d5c8208e8f1ef27a1f484ebc9')  #Calculating for celebrity
        api = API(auth)
        
        followed_dict = {}
        if inf.follower_count > 1000: #only for popular users that have too many people retweet his status
            followed, cursors  = api.friends(count=200, cursor=-1)
            while True:
                for f in followed:
                    followed_dict[getAtt(f, 'screen_name')] = 1
                if cursors[1] == 0:
                    break
                followed, cursors  = api.friends(count=200, cursor=cursors[1])

        """TODO:This part seems to be unstable;Sometimes it doens work"""
        #Calculate the most influenced friends through mentions api 
        mentions = api.mentions(count=200)
        friends_dict = {}
        friends_image_dict = {}
        for m in mentions:
            user = getAtt(m, 'user')
            screen_name = getAtt(user, 'screen_name')
            if screen_name in friends_dict:
                friends_dict[screen_name] += 1
            else:
                if screen_name == inf.screen_name:
                    continue
                friends_dict[screen_name] = 1
                friends_image_dict[screen_name] = getAtt(user, 'profile_image_url')
        friends = sorted(friends_dict.iteritems(), key=operator.itemgetter(1), reverse=True)
        if followed_dict:
            friends_list = []
            backup_list = []
            for f in friends:
                if f[0] in followed_dict:
                    friends_list.append(f[0])
                else:
                    backup_list.append(f[0])
                if len(friends_list) == 4:
                    break
            friends_list.extend(backup_list[:4-len(friends_list)])
        else:
            friends_list = [f[0] for f in friends[:4]]
        influence_friends = ','.join(friends_list)
        if influence_friends:
            inf.influence_friends = influence_friends
            friends_images = [friends_image_dict[f] for f in friends_list]
        else:
            friends_images = []
        
        #Calculates the quality of followers; Also get average followers count of sampled followers
        total = 0
        active_count = 0
        counted = 0      
        followers, cursors = api.followers(user_id=inf.sina_account, cursor=-1, count=200)
        while True: #next_cursor is not zero means not the end
            for f in followers:
                counted += 1
                f_follower_count = getAtt(f, 'followers_count')
                #f_friends_count = getAtt(f, 'friends_count')
                f_status_count = getAtt(f, 'statuses_count')
                if ((f_follower_count > 50 or f_status_count > 50) and  f_follower_count + f_status_count > 75
                or f_follower_count + f_status_count > 150):
                    active_count += 1
                total += f_follower_count
            break #200 samples should be enough
            #if cursors[1] == 0:
            #    break
            #followers, cursors = api.followers(user_id=inf.sina_account, cursor=cursors[1], count=200)
        avg_follower_of_followers = total*1.0/counted if counted !=0 else 0
        active_follower_ratio = active_count * 1.0 /counted if counted !=0 else 0
        inf.active_follower_count = int(math.ceil(active_follower_ratio*inf.follower_count))
        
        
        #Calculates the average rt_count of each tweet based on 200 samples
        mid_list = []
        rt_count = 0 #Count of status that retweet my status
        ids_list = []
        timeline = api.user_timeline(user_id=inf.sina_account, count=200)
        for line in timeline:    
            mid_list.append(str(getAtt(line, "id")))
            if len(mid_list) == 20:
                ids_list.append(','.join(mid_list))
                mid_list = []
        if mid_list: #append the remaining ids
            ids_list.append(','.join(mid_list))
        if inf.status_count > 0 and not ids_list:
            raise Exception('weibo api fails') 
        for ids in ids_list:
            counts = api.counts(ids=ids)
            for obj in counts:
                rt_count += getAtt(obj, 'rt')
        sample_size = (len(ids_list)-1)*20 + len(ids_list[-1]) if ids_list else 0
        average_rt_count = rt_count*1.0/sample_size if sample_size != 0 else 0
        inf.average_rt_count = average_rt_count
            
        
        influence_count = long(average_rt_count * inf.status_count * avg_follower_of_followers)
        influence_count += inf.status_count * inf.follower_count #plus this so that it won't be zero
        inf.influence_count = influence_count
        magic_constant = 4.07 #99/math.log(36613694013) for YangMi
        inf.influence_score = magic_constant * math.log(inf.influence_count+0.1) if inf.influence_count > 0 else 0
        inf.influence_score = int(math.ceil(math.sqrt(inf.influence_score)*10)) #To make the score larger
        if inf.influence_score > 99:
            inf.influence_score = 99
        print inf.influence_count 
        if inf.influence_count > 250000000: #To avoid huge number exceeding the number of users on weibo
            inf.influence_count = 250000000 + long(random.random()*1000000)
        
        #img_url = settings.MEDIA_URL + 'apps/influence/sample.gif'
        """TODO: check whether the profile is complete; But this may be not necessary"""
        inf.last_use_date = datetime.now()
        inf.error = 'success'  #Erase the error message last time
        inf.save() 
    except Exception, e:
        try:
            inf.error = str(e)
            inf.save()
        except:
            pass
        print str(e)