Example #1
0
def addFavorite(status_id):
    auth = OAuthHandler(APP_KEY, APP_SECRET)
    # Get currrent user access token from session
    access_token = session['oauth_access_token']
    auth.setToken(access_token.key, access_token.secret)
    api = API(auth)
    api.create_favorite(status_id)
Example #2
0
 def init_2nd_step(self, verifier_num):
     info = user.get_app('sina', self.email)
     auth = OAuthHandler(APP_KEY, APP_SECRET)
     auth.set_request_token(info.get('request_token'), info.get('request_secret'))
     access = auth.get_access_token(verifier_num)
     user.update_app('sina', self.email, access_token=access.key, access_secret=access.secret)
     return True
Example #3
0
def press_sina_weibo():
    ''''' 
    调用新浪微博Open Api实现通过命令行写博文,功能有待完善 
    author: socrates 
    date:2012-02-06 
    新浪微博:@没耳朵的羊 
    '''
    sina_weibo_config = configparser.ConfigParser()
    #读取appkey相关配置文件
    try:
        sina_weibo_config.readfp(open('sina_weibo_config.ini'))
    except configparser.Error:
        print('read sina_weibo_config.ini failed.')

    #获取需要的信息
    consumer_key = sina_weibo_config.get("userinfo", "CONSUMER_KEY")
    consumer_secret = sina_weibo_config.get("userinfo", "CONSUMER_SECRET")
    token = sina_weibo_config.get("userinfo", "TOKEN")
    token_sercet = sina_weibo_config.get("userinfo", "TOKEN_SECRET")

    #调用新浪微博OpenApi(python版)
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.setAccessToken(token, token_sercet)
    api = API(auth)
    return api
Example #4
0
def press_sina_weibo():  
    ''''' 
    调用新浪微博Open Api实现通过命令行写博文,功能有待完善 
    author: socrates 
    date:2012-02-06 
    新浪微博:@偶是正太 
    '''  
    sina_weibo_config = configparser.ConfigParser()  
    #读取appkey相关配置文件  
    try:  
        sina_weibo_config.readfp(open('sina_weibo_config.ini'))  
    except configparser.Error:  
        print ('read sina_weibo_config.ini failed.')  
      
    #获取需要的信息  
    consumer_key = sina_weibo_config.get("userinfo","CONSUMER_KEY")  
    consumer_secret =sina_weibo_config.get("userinfo","CONSUMER_SECRET")  
    token = sina_weibo_config.get("userinfo","TOKEN")  
    token_sercet = sina_weibo_config.get("userinfo","TOKEN_SECRET")  
  
    #调用新浪微博OpenApi(python版)  
    auth = OAuthHandler(consumer_key, consumer_secret)  
    auth.setAccessToken(token, token_sercet)  
    api = API(auth)  
  
    #通过命令行输入要发布的内容  
    weibo_content = input('Please input content:')  
    status = api.update_status(status=weibo_content)  
    print ("Press sina weibo successful, content is: %s" % status.text) 
Example #5
0
def press_sina_weibo():  
    ''''' 
    调用新浪微博Open Api实现通过命令行写博文,功能有待完善 
    author: socrates 
    date:2012-02-06 
    新浪微博:@没耳朵的羊 
    '''  
    sina_weibo_config = configparser.ConfigParser()  
    #读取appkey相关配置文件  
    try:  
        sina_weibo_config.readfp(open('sina_weibo_config.ini'))  
    except configparser.Error:  
        print ('read sina_weibo_config.ini failed.')  
      
    #获取需要的信息  
    consumer_key = sina_weibo_config.get("userinfo","CONSUMER_KEY")  
    consumer_secret =sina_weibo_config.get("userinfo","CONSUMER_SECRET")  
    token = sina_weibo_config.get("userinfo","TOKEN")  
    token_sercet = sina_weibo_config.get("userinfo","TOKEN_SECRET")  
  
  
    #调用新浪微博OpenApi(python版)  
    auth = OAuthHandler(consumer_key, consumer_secret)  
    auth.setAccessToken(token, token_sercet)  
    api = API(auth)  
    return api;   
Example #6
0
def addFavorite(status_id):
    auth = OAuthHandler(APP_KEY, APP_SECRET)
    # Get currrent user access token from session
    access_token = session['oauth_access_token']
    auth.setToken(access_token.key, access_token.secret)
    api = API(auth)
    api.create_favorite(status_id)
Example #7
0
 def GET(self):
     #获取noattentionok.html传过来的数据
     data = web.input()
     on = []
     try:
         auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
         auth.access_token = session['access_token']
         api = API(auth)
         """ 
         获取noattention.html页面传过来的uid,通过checkbox,由于有一个全选按钮,如果点击,则去掉 
         """
         for x in data:
             on.append(x)
         try:
             on.remove('checkbox2')
         except:
             pass
         nu = len(on)
         if nu == 0:
             pass
         if nu > 60:
             on = on[:60]
             nu = 60
         """ 
         一次最多加60次关注 
         """
         map(api.create_friendship, on)
         info = "恭喜您已成功关注%d位用户....." % nu
         return render_template('success.html', info=info.decode('utf-8'))
     except:
         info = "亲,系统繁忙,请稍后再试......,系统在3秒后自动返回..."
         return render_template('error.html', info=info.decode('utf-8'))
Example #8
0
    def GET(self):
        access_token=session.get('access_token',None)
        if not access_token:
            auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET,web.ctx.get('homedomain')+'/callback')
            auth_url = auth.get_authorization_url()
            session.request_token=auth.request_token
            web.seeother(auth_url)
        else:
            auth =OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
            auth.access_token=access_token
            api=API(auth)
            user=api.verify_credentials()
            user_timeline=user.timeline(count=10)

            print "current user is ",user.screen_name
            hot_list=get_hot_list()
            for user_tweet in user_timeline:
                try:
                    hot_list.append(tuple([user_tweet.user.screen_name,
                                            user_tweet.mid,
                                            user_tweet.text,
                                            user_tweet.source,
                                            user_tweet.created_at,
                                            None,
                                            None]))
                except AttributeError:
                    #no retweet_statues
                    continue
            return render.index(user.screen_name,user.id,hot_list)
Example #9
0
def oauth_sina(request):
    auth = OAuthHandler(settings.SINA_CONSUMER_KEY,
                        settings.SINA_CONSUMER_SECRET,
                        "http://www.tingwo.cc" + "/p/oauth_sina_callback")
    auth_url = auth.get_authorization_url()
    request.session['oauth_sina_request_token'] = auth.request_token
    return HttpResponseRedirect(auth_url)
Example #10
0
 def GET(self):
     #获取attentionnotfan.html传过来的数据
     data = web.input()
     on = []
     try:
         auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
         auth.access_token = session['access_token']
         api = API(auth)
         for x in data:
             on.append(x)
         try:
             #同理,由于有全选按钮.....
             on.remove('checkbox2')
         except:
             pass
         nu = len(on)
         if nu == 0:
             pass
         #取消关注
         map(api.destroy_friendship, on)
         info = "恭喜您已成功取消关注%d位用户....." % nu
         return render_template('success.html', info=info.decode('utf-8'))
     except:
         info = "亲,系统繁忙,请稍后再试......,系统在3秒后自动返回..."
         return render_template('error.html', info=info.decode('utf-8'))
Example #11
0
File: data.py Project: shch/weibo
class getData():

    def __init__(self,flaglt):
	APP_KEY = '190802369'
        APP_SECRET = 'fb4ce1e3a4b049abb75f104d7a7439d7'
        BACK_URL = ''
        self.auth = OAuthHandler(APP_KEY,APP_SECRET,BACK_URL)
        with open('entry.pickle','rb') as f:
            entry = pickle.load(f)
        self.key = entry['key']
        self.secret = entry['secret']
	
	self.followflag = flaglt[0]
	self.friendflag = flaglt[1]
	self.weiboflag = flaglt[2]

    def getFlagStatus(self):
	return (self.followflag,self.friendflag,self.weiboflag)
	
    def searchUser(self,name):
        self.auth.setToken(self.key,self.secret)
        api = API(self.auth)
        try :
            user = api.get_user(screen_name=name)
	    #print user.id
            data = (user.screen_name.encode('utf-8'),user.location.encode('utf-8'),user.followers_count,user.friends_count,user.statuses_count,user.profile_image_url)
            return data
        except Exception ,e:
            pass
Example #12
0
    def get(self):
        invitationCode = self.request.get('invitation_code')
        if not self.isValidInvitationCode(invitationCode):
            error_output(self, "<html><body>邀请码无效</body></html>", "text/html", 400)
            return
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        
        verifier = self.request.get("oauth_verifier").strip()
        twitterId = self.request.get("twitter_id").strip()
        if verifier == "" or twitterId == "":
            authUrl = auth.get_authorization_url()
            success_output(self, page_goto_sina_oauth % \
                {'url':authUrl, 
                 'invitation':invitationCode.encode('UTF-8'),
                 'token':auth.request_token.key, 
                 'secret':auth.request_token.secret})
        else:
            request_token = self.request.get("request_token")
            request_secret = self.request.get("request_secret")
            auth.set_request_token(request_token, request_secret)
            accessToken = auth.get_access_token(verifier)
            binding = SyncBinding.getOrInsertByInvitationCode(invitationCode)
            binding.lastTweetId = None
            binding.twitterId = twitterId
            binding.sinaAccessToken = accessToken.key
            binding.sinaAccessSecret = accessToken.secret
            binding.put()
            success_output(self, '''
<html><body>
<p>Twitter与新浪微博同步绑定成功</p>
<p>如需要修改绑定,请重新访问邀请链接</p>
</body></html>
            ''')
Example #13
0
def mainPage(request):
    session = get_current_session()
    access_token_key = session['access_token_key']
    access_token_secret = session['access_token_secret']
    oauth_verifier = request.GET.get('oauth_verifier', '')
    get_absolute_path(request)
    if not access_token_key:
        #params['test'] = reverse('sinaweibo.views.login', args=[], kwargs={})#, current_app=context.current_app)        
        login_url = reverse('sinaweibo.views.login', args=[], kwargs={})
        #return shortcuts.render_to_response('test.html', params)
        return http.HttpResponseRedirect(login_url)
    else:
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.setToken(access_token_key, access_token_secret)
        api = API(auth)
        
        #myself = api.get_user(id=1894001933)
        #screen_name = myself. __getattribute__('screen_name')
        myweibo = []
        myweibo_obj = api.user_timeline(count=20, page=1)
        for weibo in myweibo_obj:
            myweibo.append({'text': weibo.text, 
                            'created_at': weibo.created_at, 
                            'retweeted_status': hasattr(weibo, 'retweeted_status') and weibo.retweeted_status or None,
                            'source': weibo.source})
        wrapper__at(myweibo)
        params = {}
        
        params['user'] = api.verify_credentials()
        params['result'] = myweibo
        template = get_template_uri(appContext, 'weibo.html')
        return shortcuts.render_to_response(template, params)
Example #14
0
 def get_auth(self):
     from weibopy.auth import OAuthHandler
     from weibopy.oauth import OAuthToken
     auth = OAuthHandler(settings.SINA_CONSUMER_KEY,
                         settings.SINA_CONSUMER_SECRET)
     auth.access_token = OAuthToken(self.access_token, self.access_secret)
     return auth
Example #15
0
 def init_1st_step(self):
     auth = OAuthHandler(APP_KEY, APP_SECRET, '')
     auth_url = auth.get_authorization_url()
     user.update_app('sina', self.email, request_token=auth.request_token.key,
             request_secret=auth.request_token.secret)
     log.debug(repr(user.get(self.email)))
     return auth_url
Example #16
0
 def authorization(self):
     """ 
     开发者认证 
     """
     auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
     auth.setToken(key.TOKEN, key.TOKEN_SECRET)
     self.api = API(auth)
     self.cursor = cursor
Example #17
0
 def GET(self):
     oauth_token = web.input().oauth_token
     oauth_verifier = web.input().oauth_verifier
     auth = OAuthHandler(oauth.APP_KEY, oauth.APP_SECRET)
     auth.set_request_token(session.rtKey[web.ctx.ip], session.rtSec[web.ctx.ip])
     access_token = auth.get_access_token(oauth_verifier)
     session.atKey[web.ctx.ip] = access_token.key
     session.atSec[web.ctx.ip] = access_token.secret
     raise web.seeother('/sinaweibo/timeline')
Example #18
0
def login():
    callback = 'http://so2weibo.sinaapp.com/login_callback'

    auth = OAuthHandler(APP_KEY, APP_SECRET, callback)
    # Get request token and login url from the provider
    url = auth.get_authorization_url()
    session['oauth_request_token'] = auth.request_token
    # Redirect user to login
    return redirect(url)
Example #19
0
 def __init__(self):
     # 设定网页应用回调页面(桌面应用设定此变量为空)
     BACK_URL = ""
     # 验证开发者密钥.
     auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL)
     # 设定用户令牌密钥.
     auth.setToken(TOKEN_KEY, TOKEN_SECRET)
     # 绑定用户验证信息.
     self.api = API(auth)
Example #20
0
 def get(self):
     recordtoken = OauthInfo(states="openAccount",service="sina",emailaddr="*****@*****.**")
     recordtoken.put()
     auth = OAuthHandler(CONSUMER_KEY_SINA, CONSUMER_SECRET_SINA,self.call_back_url+"?UID="+str(recordtoken.key()))
     url = auth.get_authorization_url()
     recordtoken.states = "request_token_got"
     recordtoken.fromOauthToken(auth.request_token)
     recordtoken.put()
     self.redirect(url)
Example #21
0
def WeiboAuthV1(userinfo):
    api = None
    try:
        auth = OAuthHandler(WEIBO_APP_KEY, WEIBO_APP_SECRET)
        auth.setToken(userinfo.weibo_access_token, userinfo.weibo_access_token_secret)
        api = API(auth)
    except Exception as e:
        logging.info("WeiboAuth error %s " % e)
    return api
Example #22
0
 def newmessage(self, message, lat=None, long=None):
     log.debug('new message: %s' % message)
     auth = OAuthHandler(APP_KEY, APP_SECRET)
     info = user.get_app('sina', self.email)
     auth.setToken(info['access_token'], info['access_secret'])
     api = API(auth)
     api.update_status(message)
     log.debug('new message done.')
     return True
Example #23
0
def login():
    callback = 'http://so2weibo.sinaapp.com/login_callback'

    auth = OAuthHandler(APP_KEY, APP_SECRET, callback)
    # Get request token and login url from the provider
    url = auth.get_authorization_url()
    session['oauth_request_token'] = auth.request_token
    # Redirect user to login
    return redirect(url)
Example #24
0
 def __init__(self):
     #设定网页应用回调页面(桌面应用设定此变量为空)
     BACK_URL = ""
     #验证开发者密钥.
     auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL)
     #设定用户令牌密钥.
     auth.setToken(TOKEN_KEY, TOKEN_SECRET)
     #绑定用户验证信息.
     self.api = API(auth)
Example #25
0
def api(): 
    token=get_access_token('w..','c..')  #input your weibo id and password here#
    atKey =token['oauth_token']
    atSecret = token['oauth_token_secret']
    from weibopy.error import WeibopError
    auth = OAuthHandler(APP_KEY, APP_SECRET)
    auth.setToken( atKey, atSecret ) 
    api = API(auth) # bind the authentication information to connect to API
    return api
	
Example #26
0
def updateWeiboStatus(message):
    auth = OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
    auth.setToken(ACCESS_TOKEN_KEY,ACCESS_TOKEN_SECRET)
    api=API(auth)

    message = message.encode("utf-8")
    status = api.update_status(status=message)
    
    from time import sleep
    sleep(5)
Example #27
0
    def GET(sefl):
        ins=web.input()
        oauth_verifier=ins.get('oauth_verifier',None)
        request_token=session.get('request_token',None)
        auth=OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.request_token=request_token

        access_token=auth.get_access_token(oauth_verifier)
        session.access_token=access_token
        web.seeother("/")
Example #28
0
 def analyze(self,query):
     if query=="" or query is None:
         web.seeother("/")
     access_token=session.get('access_token',None)
     auth =OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
     auth.access_token=access_token
     api=API(auth)
     repost_timeline=api.repost_timeline(count=10)
     print repost_timeline
     logging.info("analyzing query %s " % (query))
Example #29
0
def api():
    token = get_access_token('w..',
                             'c..')  #input your weibo id and password here#
    atKey = token['oauth_token']
    atSecret = token['oauth_token_secret']
    from weibopy.error import WeibopError
    auth = OAuthHandler(APP_KEY, APP_SECRET)
    auth.setToken(atKey, atSecret)
    api = API(auth)  # bind the authentication information to connect to API
    return api
Example #30
0
 def __init__(self,app_key="3146673438",app_secret="f65a02335629c4ff5c4a5314fedfa97f"):  
     app_key=app_key
     app_secret=app_secret
     file=open("token","r")
     token_key=file.readline()
     token_secret=file.readline()
     file.close()
     auth=OAuthHandler(app_key,app_secret)
     auth.setToken(token_key[0:-1],token_secret)
     self.api=API(auth)
Example #31
0
    def get(self):
        verifier = self.request.get('oauth_verifier')
        logging.info('verify id = %s' % verifier)
        
        signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
        
        # Get token - key and secret from memcache that we set on SinaOauthPhaseOne
        tokenstr = memcache.get("PK_"+self.request.get('id'))
        memcache.delete("PK_"+self.request.get('id'))
        token = oauth.OAuthToken.from_string(tokenstr)                
               
        consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
        client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
                                   ACCESS_TOKEN_URL, AUTHORIZATION_URL)
        
        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
                            consumer,
                            token=token, verifier=verifier,
                            http_url=client.access_token_url)
        oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
        
        # Finally get access_token after verifier is matched.
        access_token = client.fetch_access_token(oauth_request)
        logging.info('Sina Authorized access_token = %s' % access_token)
        
        # Set cookie into browser in case for further use.
        self.response.headers.add_header('Set-Cookie',
                                         'oauth_key=' + access_token.key + cookie)
        self.response.headers.add_header('Set-Cookie',
                                         'oauth_secret=' + access_token.secret + cookie)
        
        # Call Sina weibopy API auth.OAuthHandler() and set access_token to
        # fetch access_resource aka:user resource.
        auth_access_resource = OAuthHandler(
                                    consumer_key=CONSUMER_KEY,
                                    consumer_secret=CONSUMER_SECRET)
        auth_access_resource.set_access_token(access_token.key,
                                              access_token.secret)
        
        # API() inherits auth_access_resource return.
        api = API(auth_access_resource)
        
        # I call api.verify_credentials instead of use auth.OAuthHandler.get_username
        username = api.verify_credentials()
 
        if username:
            self.username = username.screen_name
            self.response.headers.add_header('Set-Cookie',
                                             'sina_username='******'Sina username: %s' % self.username)
        else:
            logging.info('NO SINA USER')

        
        self.redirect('/')
Example #32
0
def get_access_token(username, password):
    auth = OAuthHandler(APP_KEY, APP_SECRET)
    auth_url = auth.get_authorization_url()
    print "Auth URL: ", auth_url
    veri_obj = GetPIN(auth_url, username, password)
    verifier = veri_obj.getPIN()
    print "VERIFIER: ", verifier
    if verifier == -1:
        raise Exception("Error Account")
    token = auth.get_access_token(verifier)
    return dict(parse_qsl(str(token)))
Example #33
0
def get_access_token(username, password):
    auth = OAuthHandler(APP_KEY, APP_SECRET)
    auth_url = auth.get_authorization_url()
    print "Auth URL: ",auth_url
    veri_obj = GetPIN(auth_url, username, password)   
    verifier = veri_obj.getPIN()
    print "VERIFIER: ",verifier
    if verifier==-1:
        raise Exception("Error Account")
    token = auth.get_access_token(verifier)
    return dict(parse_qsl(str(token)))
Example #34
0
 def wrapper(self, *args, **kwargs):
     auth = OAuthHandler(SINA_CONSUME_KEY, SINA_CONSUME_SECRET)
     request_token = self.SESSION['oauth_access_token']
     if request_token:
         auth.setToken(request_token.key, request_token.secret)
         api = API(auth)
         self.__setattr__('sapi', api)
     else:
         to_url = '/auth?to_url='+self.request.path
         self.redirect(to_url)
     return method(self, *args, **kwargs)
Example #35
0
 def auth(self):
     # Check Sina user logged in or not.
     self.sina_username =  self.request.cookies.get("sina_username")
     if self.sina_username:
         oauth_key = self.request.cookies.get("oauth_key")
         oauth_secret = self.request.cookies.get("oauth_secret")
         auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
         auth.setToken(oauth_key, oauth_secret)
         self.api = API(auth)
         return True
     return False
Example #36
0
 def auth(self):
     # Check Sina user logged in or not.
     self.sina_username = self.request.cookies.get("sina_username")
     if self.sina_username:
         oauth_key = self.request.cookies.get("oauth_key")
         oauth_secret = self.request.cookies.get("oauth_secret")
         auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
         auth.setToken(oauth_key, oauth_secret)
         self.api = API(auth)
         return True
     return False
Example #37
0
    def get(self):
        verifier = self.request.get('oauth_verifier')
        logging.info('verify id = %s' % verifier)

        signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()

        # Get token - key and secret from memcache that we set on SinaOauthPhaseOne
        tokenstr = memcache.get("PK_" + self.request.get('id'))
        memcache.delete("PK_" + self.request.get('id'))
        token = oauth.OAuthToken.from_string(tokenstr)

        consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
        client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
                                   ACCESS_TOKEN_URL, AUTHORIZATION_URL)

        oauth_request = oauth.OAuthRequest.from_consumer_and_token(
            consumer,
            token=token,
            verifier=verifier,
            http_url=client.access_token_url)
        oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)

        # Finally get access_token after verifier is matched.
        access_token = client.fetch_access_token(oauth_request)
        logging.info('Sina Authorized access_token = %s' % access_token)

        # Set cookie into browser in case for further use.
        self.response.headers.add_header(
            'Set-Cookie', 'oauth_key=' + access_token.key + cookie)
        self.response.headers.add_header(
            'Set-Cookie', 'oauth_secret=' + access_token.secret + cookie)

        # Call Sina weibopy API auth.OAuthHandler() and set access_token to
        # fetch access_resource aka:user resource.
        auth_access_resource = OAuthHandler(consumer_key=CONSUMER_KEY,
                                            consumer_secret=CONSUMER_SECRET)
        auth_access_resource.set_access_token(access_token.key,
                                              access_token.secret)

        # API() inherits auth_access_resource return.
        api = API(auth_access_resource)

        # I call api.verify_credentials instead of use auth.OAuthHandler.get_username
        username = api.verify_credentials()

        if username:
            self.username = username.screen_name
            self.response.headers.add_header(
                'Set-Cookie', 'sina_username='******'Sina username: %s' % self.username)
        else:
            logging.info('NO SINA USER')

        self.redirect('/')
Example #38
0
    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'))
Example #39
0
class sinaAPI():
    def __init__(self, token, tokenSecret):
        self.auth = OAuthHandler(consumer_key, consumer_secret)
        self.auth.setToken(token, tokenSecret)
        self.api = API(self.auth)

    def attr(self, obj, key):
        try:
            return obj.__getattribute__(key)
        except Exception, e:
            #print e
            return ''
Example #40
0
class WeiboBackup(object):
    """
    新浪微博自动备份.
    """

    def __init__(self):
        self.hdl = OAuthHandler(config.APP_KEY, config.APP_SECRET)
        self.api = None
        self.writer = None
        self.token = {}
        self.auth()

    def auth(self):
        try:
            with open("../" + config.TOKEN_FILE) as f:
                self.token = pickle.load(f)
            self.hdl.setToken(self.token["key"], self.token["secret"])
            self.api = API(self.hdl)
        except Exception as e:
            print e

    def get_auth_url(self):
        return self.hdl.get_authorization_url()

    def get_data(self, screen_name, page):
        count = 200
        while True:
            try:
                res = self.api.user_timeline(screen_name=screen_name, count=count, page=page)
                if len(res) == 0:
                    return page
                else:
                    for status in res:
                        text = status.text
                        retweet = getattr(status, "retweeted_status", False)
                        if retweet:
                            text = text + "//" + retweet.text
                        text = text.encode("utf-8")
                        self.writer.append(text)
                page = page + 1
            except Exception as e:
                print e

    def backup(self, screen_name, filename=""):
        if filename:
            self.writer = Writer(filename)
        else:
            self.writer = []
        page, alert_num = 1, 0
        while alert_num < ALERT_MAX_TIMES:
            page = self.get_data(screen_name, page)
            alert_num += 1
        return self.writer
Example #41
0
def login_callback():
    # This is called by the provider when user has granted permission to your app
    verifier = request.args.get('oauth_verifier', None)
    auth = OAuthHandler(APP_KEY, APP_SECRET)
    request_token = session['oauth_request_token']
    del session['oauth_request_token']

    # Show the provider it's us really
    auth.set_request_token(request_token.key, request_token.secret)
    # Ask for a temporary access token
    session['oauth_access_token'] = auth.get_access_token(verifier)
    return render_template("login_callback.html")
Example #42
0
def login_callback():
    # This is called by the provider when user has granted permission to your app
    verifier = request.args.get('oauth_verifier', None)
    auth = OAuthHandler(APP_KEY, APP_SECRET)
    request_token = session['oauth_request_token']
    del session['oauth_request_token']
    
    # Show the provider it's us really
    auth.set_request_token(request_token.key, request_token.secret)
    # Ask for a temporary access token
    session['oauth_access_token'] = auth.get_access_token(verifier)
    return render_template("login_callback.html")
Example #43
0
class sinaAPI():
	def __init__(self, token, tokenSecret):
		self.auth = OAuthHandler(consumer_key, consumer_secret)
		self.auth.setToken(token, tokenSecret)
		self.api = API(self.auth)
				
	def attr(self,obj,key):
		try:
			return obj.__getattribute__(key)
		except Exception,e:
			#print e
			return ''
Example #44
0
class SinaClient:
    def __init__(self, key, secret):
        self.auth=OAuthHandler(key,secret)

    def get_auth_url(self):
        return self.auth.get_authorization_url()

    def set_access_token(self,token):
        key,secret=token.split('|')
        self.auth.setToken(key,secret)
        self.api=API(self.auth)

    def get_access_token(self):
        token=self.auth.access_token
        return token.key+'|'+token.secret

    def set_request_token(self,token):
        key,secret=token.split('|')
        self.auth.request_token=oauth.OAuthToken(key,secret)

    def get_request_token(self):
        token=self.auth.request_token
        return token.key+'|'+token.secret

    def set_verifier(self,verifier):
        self.auth.get_access_token(verifier)
        self.api=API(self.auth)

    def send_msg(self,msg,coord=None):
        lat,long=self.get_lat_long(coord)
        msg=msg.encode('utf-8')
        status=self.api.update_status(status=msg,lat=lat,long=long)
        return status

    def send_pic(self,msg,pic,coord=None):
        lat,long=self.get_lat_long(coord)
        msg=msg.encode('utf-8')
        status=self.api.upload(pic,status=msg,lat=lat,long=long)
        
        return status

    def get_timeline(self):
        return self.request(SINA_USER_TIMELINE_URL)

    def get_lat_long(self,coord):
        if not coord:
          return (None,None)

        return map(lambda x:str(x),coord)

    def get_user(self):
        return self.api.verify_credentials()
Example #45
0
 def GET(self):
     try:
         ins = web.input()
         oauth_verifier = ins.get('oauth_verifier', None)
         request_token = session.get('request_token', None)
         auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
         auth.request_token = request_token
         access_token = auth.get_access_token(oauth_verifier)
         session.access_token = access_token
         web.seeother("/index")
     except Exception:
         info = "亲,系统繁忙,请稍后再试......,系统在3秒后自动返回..."
         return render_template('error.html', info=info.decode('utf-8'))
Example #46
0
 def get(self):
     recordtoken = OauthInfo(states="openAccount",service="twitter",emailaddr="*****@*****.**")
     recordtoken.put()
     auth = OAuthHandler(CONSUMER_KEY_TWITTER, CONSUMER_SECRET_TWITTER,self.call_back_url+"?UID="+str(recordtoken.key()),True)
     auth.OAUTH_HOST = 'api.twitter.com'
     auth.OAUTH_ROOT = '/oauth/'
     try :
         url = auth.get_authorization_url()
         recordtoken.states = "request_token_got"
         recordtoken.fromOauthToken(auth.request_token)
         recordtoken.put()
         self.redirect(url)
     except Exception,error_message:
         self.response.out.write( error_message )
Example #47
0
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 auth(self):
        
        if len(self.consumer_key) == 0:
            print("Please set consumer_key£¡£¡£¡")
            return
        
        if len(self.consumer_key) == 0:
            print("Please set consumer_secret£¡£¡£¡")
            return
                
        self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
        auth_url = self.auth.get_authorization_url()
        print('Please authorize: ' + auth_url)
        verifier = input('PIN: ').strip()
        self.auth.get_access_token(verifier)
        self.api = API(self.auth)
        
    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 update(self, message):
        status = self.api.update_status(message)
        self.obj = status
        id = self.getAtt("id")
        text = self.getAtt("text")
        print("update,id="+ str(id) +",text="+ text)
        
    def destroy_status(self, id):
        status = self.api.destroy_status(id)
        self.obj = status
        id = self.getAtt("id")
        text = self.getAtt("text")
        print("update---"+ str(id) +":"+ text)
Example #48
0
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 auth(self):

        if len(self.consumer_key) == 0:
            print("Please set consumer_key£¡£¡£¡")
            return

        if len(self.consumer_key) == 0:
            print("Please set consumer_secret£¡£¡£¡")
            return

        self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
        auth_url = self.auth.get_authorization_url()
        print('Please authorize: ' + auth_url)
        verifier = input('PIN: ').strip()
        self.auth.get_access_token(verifier)
        self.api = API(self.auth)

    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 update(self, message):
        status = self.api.update_status(message)
        self.obj = status
        id = self.getAtt("id")
        text = self.getAtt("text")
        print("update,id=" + str(id) + ",text=" + text)

    def destroy_status(self, id):
        status = self.api.destroy_status(id)
        self.obj = status
        id = self.getAtt("id")
        text = self.getAtt("text")
        print("update---" + str(id) + ":" + text)
Example #49
0
def post_to_wb(request):
    if request.method == 'POST':
        success = ""
        access_token = request.session['oauth_access_token']
        auth = OAuthHandler(SINA_APP_KEY, SINA_APP_SECRET)
        auth.set_access_token(access_token.key, access_token.secret)
        api = API(auth)
        try:
            content = request.POST.get("content")
            api.update_status(content)
            success = "成功发布"
        except:
            raise
            success = "失败"
        return HttpResponseRedirect('/status')
    return HttpResponseRedirect('/status')
Example #50
0
    def auth(self):

        if len(self.consumer_key) == 0:
            print("Please set consumer_key£¡£¡£¡")
            return

        if len(self.consumer_key) == 0:
            print("Please set consumer_secret£¡£¡£¡")
            return

        self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
        auth_url = self.auth.get_authorization_url()
        print('Please authorize: ' + auth_url)
        verifier = input('PIN: ').strip()
        self.auth.get_access_token(verifier)
        self.api = API(self.auth)
Example #51
0
class WebOAuthHandler():
    def __init__(self):
        self.back_url = current_app.config['SERVER_PATH'] + 'oauth/callback'
        self.oauth = OAuthHandler(consumer_key, consumer_secret)

    def get_authorizate_url(self):
        return self.oauth.get_authorization_url(
        ) + '&oauth_callback=' + self.back_url
Example #52
0
def oauth_callback(request):
    oauth_verifier = request.REQUEST.get('oauth_verifier', None)
    request_token = request.session.get('oauth_sina_request_token', None)
    auth = OAuthHandler(settings.SINA_CONSUMER_KEY,
                        settings.SINA_CONSUMER_SECRET)
    auth.request_token = request_token
    access_token = auth.get_access_token(oauth_verifier)
    logger.debug("authorized")
    request.session['oauth_sina'] = auth

    api = API(auth)
    data = api.verify_credentials()

    from django.contrib.auth import authenticate, login as django_login

    user = authenticate(sinaweiboid=data.id)
    if user is None:
        #  query = SinaWeibo.objects.filter(weiboid = data.id)
        #  if (len(query) ==  0):

        user = User()
        user.username = "******" + data.name
        user.backend = 'sinaweibo'
        user.save()

        sina_weibo = SinaWeibo()
        sina_weibo.weiboid = data.id
        sina_weibo.name = data.name
        sina_weibo.access_token = auth.access_token.key
        sina_weibo.access_secret = auth.access_token.secret
        sina_weibo.user = user
        sina_weibo.save()

        user = authenticate(sinaweiboid=data.id)
        assert user != None


#  else:
#    sina_weibo = query[0]
#    user = sina_weibo.user
#    user.backend = 'sinaweibo'

    django_login(request, user)

    return HttpResponseRedirect("/")
Example #53
0
def test_rp(request):
    if request.method == 'POST':
        success = ""
        access_token = request.session['oauth_access_token']
        auth = OAuthHandler(SINA_APP_KEY, SINA_APP_SECRET)
        auth.set_access_token(access_token.key, access_token.secret)
        api = API(auth)
        try:
            username = api.me().screen_name
            number = int(md5.md5(username.encode('utf-8')).hexdigest(), 16)
            rp = number % 100
            rating = rp2rating(rp)
            api.update_status(u"%s, 你的人品是 %d, %s" % (username, rp, rating))
            success = u"成功发布"
        except:
            raise
            success = u"失败"
        return HttpResponseRedirect('/status')
    return HttpResponseRedirect('/status')
Example #54
0
    def GET(self):
        data = web.input()
        try:
            select = data.star
        except:
            try:
                select = data.hobby
            except:
                try:
                    select = data.personality
                except:
                    select = data.job
        try:
            auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET)
            auth.access_token = session['access_token']
            api = API(auth)
            seuid = []
            nu = 0
            """ 
            这里写的很不好..... 
            """
            while True:
                re = cursor.execute(
                    'select uid from taginfo where tagid=%d limit 20' %
                    select).fetchall()
                for r in re:
                    seuid.append(r[0])
                for s in seuid:
                    try:
                        api.create_friendship(user_id=s)
                        nu += 1
                    except:
                        continue
                if nu >= 50:
                    break

            info = "恭喜您已成功关注%d位用户....." % nu
            return render_template('success.html', info=info.decode('utf-8'))
        except:
            info = "亲,系统繁忙,请稍后再试......,系统在3秒后自动返回..."
            return render_template('error.html', info=info.decode('utf-8'))
Example #55
0
def showstatus(request):
    logined = False
    if request.session.get('oauth_access_token'):
        logined = True
        access_token = request.session['oauth_access_token']
    else:
        return render_to_response('wb/status.html', locals())
    access_token = request.session['oauth_access_token']
    auth = OAuthHandler(SINA_APP_KEY, SINA_APP_SECRET)
    auth.set_access_token(access_token.key, access_token.secret)
    api = API(auth)
    try:
        gender = "male" if api.me().gender == "m" else "female"
        id = api.me().id
        screen_name = api.me().screen_name
        description = api.me().description
        location = api.me().location
        profile_image_url = api.me().profile_image_url
    except:
        return render_to_response('wb/status.html', locals())
    return render_to_response('wb/status.html', locals())
Example #56
0
    def get(self):
        invitationCode = self.request.get('invitation_code')
        if not self.isValidInvitationCode(invitationCode):
            error_output(self, "<html><body>邀请码无效</body></html>", "text/html",
                         400)
            return
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)

        verifier = self.request.get("oauth_verifier").strip()
        twitterId = self.request.get("twitter_id").strip()
        if verifier == "" or twitterId == "":
            authUrl = auth.get_authorization_url()
            success_output(self, page_goto_sina_oauth % \
                {'url':authUrl,
                 'invitation':invitationCode.encode('UTF-8'),
                 'token':auth.request_token.key,
                 'secret':auth.request_token.secret})
        else:
            request_token = self.request.get("request_token")
            request_secret = self.request.get("request_secret")
            auth.set_request_token(request_token, request_secret)
            accessToken = auth.get_access_token(verifier)
            binding = SyncBinding.getOrInsertByInvitationCode(invitationCode)
            binding.lastTweetId = None
            binding.twitterId = twitterId
            binding.sinaAccessToken = accessToken.key
            binding.sinaAccessSecret = accessToken.secret
            binding.put()
            success_output(
                self, '''
<html><body>
<p>Twitter与新浪微博同步绑定成功</p>
<p>如需要修改绑定,请重新访问邀请链接</p>
</body></html>
            ''')
Example #57
0
def press_sina_weibo():
    ''''' 
    调用新浪微博Open Api实现通过命令行写博文,功能有待完善 
    author: socrates 
    date:2012-02-06 
    新浪微博:@偶是正太
    '''
    sina_weibo_config = configparser.ConfigParser()
    #读取appkey相关配置文件
    try:
        sina_weibo_config.readfp(open('sina_weibo_config.ini'))
    except ConfigParser.Error:
        print('read sina_weibo_config.ini failed.')

    #获取需要的信息
    consumer_key = sina_weibo_config.get("userinfo", "CONSUMER_KEY")
    consumer_secret = sina_weibo_config.get("userinfo", "CONSUMER_SECRET")
    token = sina_weibo_config.get("userinfo", "TOKEN")
    token_sercet = sina_weibo_config.get("userinfo", "TOKEN_SECRET")

    #调用新浪微博OpenApi(python版)
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.setAccessToken(token, token_sercet)
    api = API(auth)

    #通过命令行输入要发布的内容
    #    weibo_content = raw_input('Please input content:')
    #    status = api.update_status(status=weibo_content)
    #    print "Press sina weibo successful, content is: %s" % status.text
    iNum = 2
    while True:
        #上传图片,名称和内容如果重复,open api会检查,内容采用了取当前时间的机制
        #图片名称从0-5循环遍历
        status = api.upload(str(iNum) + '.jpg', 'test ' + str(iNum))

        if iNum == MAX_PIC_NUM:
            break
        else:
            iNum += 1
Example #58
0
def do_auth():
    auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL)
    auth_url = auth.get_authorization_url()
    request_token_key = auth.request_token.key
    request_token_secret = auth.request_token.secret
    auth.set_request_token(request_token_key, request_token_secret)
    webbrowser.open(auth_url)
    verifier = input("Verifier: ").strip()
    access_token = auth.get_access_token(verifier)
    ATK = access_token.key
    ATS = access_token.secret
    auth.setAccessToken(ATK, ATS)
    api = API(auth)
    user = api.verify_credentials()
    logging("[AUTH]: We are uing API from account: [uid = %s, name = %s]" %
            (user.id, user.screen_name))
    return api
Example #59
0
    def __init__(self, username="******", psw="123456789"):
        #self.logfile=log_stream.log_stream("sina_sdk")
        global gconsumer_key
        global gconsumer_secret
        global gtoken
        global gtokenSecret

        #创建一个opener
        self.__cJar = cookielib.CookieJar()
        self.__opener = urllib2.build_opener(
            urllib2.HTTPCookieProcessor(self.__cJar))
        self.__opener.addheaders = [
            ('User-agent',
             'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)')
        ]
        urllib2.install_opener(self.__opener)

        #创建一个auth对象
        self.__auth = OAuthHandler(gconsumer_key, gconsumer_secret)

        self.__auth.setToken(gtoken, gtokenSecret)

        #创建api对象
        self.__api = API(self.__auth)