Пример #1
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()
Пример #2
0
def get_sina_token():      
    #申请应用时得到的App Key及密码  
    App_key = '3028524014'  
    App_secret = '660eb5d3feacc40d3bba28e0b9dcc50b'  
  
    #授权  
    auth_handler = OAuthHandler(App_key, App_secret)  
    auth_url = auth_handler.get_authorization_url()  
  
    print "Please open this url by your Browser:" + auth_url  
    verifier = raw_input('Please input PIN code get from above url: ').strip()  
      
    #得到token及密码  
    auth_handler.get_access_token(verifier)  
Пример #3
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)
Пример #4
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)
Пример #5
0
 def sinaapp(self,app_key,app_secret):
         auth = OAuthHandler(app_key, app_secret)  ##认证
         auth_url = auth.get_authorization_url()    ##返回授权页面链接,用浏览器打开
         #webbrowser.open(auth_url)
         content = self._request(auth_url)[1].read()        
         soup=BeautifulSoup.BeautifulSoup(''.join(content))
         #print content
         pin=soup.span.string   #自动获取pin码
         #print 'Please authorize: ' + auth_url  ##输入获得的Pin码
         #verifier = raw_input('输入您在浏览器页面显示的PIN码: ').strip()
         auth.get_access_token(pin)
         api = API(auth)  #整合函数
         connent=raw_input('What are you want to say?')
         status = api.update_status(status=connent)#发布微博
         print "Send Successed"
         raw_input('Press enter to exit ......')
Пример #6
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>
            ''')
Пример #7
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
Пример #8
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>
            ''')
Пример #9
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')
Пример #10
0
def login(request):
    '''get a permanent access token'''
    session = get_current_session()
    if not request.GET.get('oauth_token'):
        '''login and save oauth token'''
        cur_url = _get_absolute_path(request)
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET, callback = cur_url)
        auth_url = auth.get_authorization_url()
        # 需要保存request_token的信息,留做取access_token用
        session["oauth_token"] = auth.request_token.key
        session["oauth_token_secret"] = auth.request_token.secret
        return http.HttpResponseRedirect(auth_url)
    else:
        ''' Get the access token '''
        oauth_verifier = request.GET.get('oauth_verifier')
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        # 从session中取出request_token的信息
        auth.set_request_token(session["oauth_token"], session["oauth_token_secret"])
        auth.get_access_token(oauth_verifier)
        # save access token
        session['access_token_key'] = auth.access_token.key
        session['access_token_secret'] = auth.access_token.secret
        response = shortcuts.redirect('sinaweibo.views.mainPage')
        return response
        
        
    if 0:
        path = os.path.join(os.path.dirname(__file__), "templates/index.html")
        myself = api.get_user(id=1894001933)
        screen_name = myself. __getattribute__("screen_name")
        self.response.out.write(template.render(path,
                {"name": screen_name}))#dir(api.verify_credentials)}))#api.verify_credentials.name}))#screen_name}))

    if 0:
        params = {}
        params['test'] = 'nothing'
        return shortcuts.render_to_response('test.html', params)

    if 0:
        # add GET para and redirect
        response = shortcuts.redirect('sinaweibo.views.mainPage')
        response['Location'] += '?oauth_verifier=%s' % oauth_verifier
        return response
            
Пример #11
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("/")
Пример #12
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)))
Пример #13
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)))
Пример #14
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")
Пример #15
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")
Пример #16
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'))
Пример #17
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
         #通过oauth_verifier来获取access_token
         access_token=auth.get_access_token(oauth_verifier)
         session.access_token=access_token
         web.seeother("/")
     except Exception:
         web.header("Content-Type", "text/html;charset=utf-8")
         return ':-( 出错了'
Пример #18
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
Пример #19
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
Пример #20
0
 def get(self):
     print '123123123'
     verifier = self.get_argument('oauth_verifier', None)
     auth = OAuthHandler(SINA_CONSUME_KEY, SINA_CONSUME_SECRET)
     if not verifier:
         #self.SESSION['goto'] = self.get_argument('to_url', None)
         auth_url = auth.get_authorization_url()+'&oauth_callback='+self.request.protocol+'://'+self.request.host+'/people/auth/'
         self.SESSION['oauth_request_token'] = auth.request_token
         self.redirect(auth_url)
     else:
         request_token = self.SESSION['oauth_request_token']
         del self.SESSION['oauth_request_token']
         auth.set_request_token(request_token.key, request_token.secret)
         access_token = auth.get_access_token(verifier)
         self.SESSION['oauth_access_token'] = access_token
         me = WeiboAPI(auth).me()
         self.after_auth(me)
Пример #21
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("/")
Пример #22
0
    def post(self):
        t_name = self.request.get('t_name')
        s_name = self.request.get('s_name')
        s_request_key = self.request.get('s_request_key')
        s_request_secret = self.request.get('s_request_secret')
        t_request_key = self.request.get('t_request_key')
        t_request_secret = self.request.get('t_request_secret')
        t_pin = self.request.get('t_pin')
        s_pin = self.request.get('s_pin')
        self.response.out.write("""<html><head><title>Tui2Lang-Result</title></head><body><center>""")
        if t_name == "" or s_name =="" or s_pin == "":
            self.response.out.write("""<h2>4 Input can not be empty! <a href="/">Back</a></h2>""")
        else:
            sina = OAuthHandler(app_key,app_secret)
            sina.set_request_token(s_request_key,s_request_secret)
            s_access_token = sina.get_access_token(s_pin.strip())
            sina_api = API(sina)

            twitter = tweepy.OAuthHandler(consumer_key,consumer_secret)
            twitter.set_request_token(t_request_key,t_request_secret)
            t_access_token = twitter.get_access_token(t_pin.strip())
            twitter_api = tweepy.API(twitter);
            
            t_tl = twitter_api.user_timeline()
            t_last_id = t_tl[0].id_str
            t_last_text = replace_tweet(t_tl[0].text)
            

            oauth_user = OauthUser(key_name=s_name)
            oauth_user.twitter_name = t_name
            oauth_user.sina_name = s_name
            oauth_user.sina_access_key = s_access_token.key
            oauth_user.sina_access_secret = s_access_token.secret
            oauth_user.twitter_access_key = t_access_token.key
            oauth_user.twitter_access_secret = t_access_token.secret
            oauth_user.twitter_last_id = t_last_id
            oauth_user.put()

            try:
                sina_api.update_status(t_last_text)            
            except WeibopError,e:
                self.response.out.write(e)
            else:
Пример #23
0
def WeiboAuthV1():
    auth = OAuthHandler(WEIBO_APP_KEY, WEIBO_APP_SECRET)
    auth_url = auth.get_authorization_url()
    print ""
    print "请在浏览器中访问下面链接,授权给buzz2weibo后,会获得一个授权码。"
    print ""
    print auth_url
    print ""

    while True:
        verifier = raw_input("请输入授权码:").strip()
        try:
            token = auth.get_access_token(verifier)
        except HTTPError:
            print "授权码不正确或者过期,请重新运行本向导"
            sys.exit(1)
        else:
            break

    weibo_token_key = token.key
    weibo_token_secret = token.secret
Пример #24
0
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,"PCRemote",size=(400,260),pos=(400,200))
        if os.path.isfile("token")==False:#第一次使用进行验证,把得到的用户key和secret写入token文件中,以后使用不用再验证PIN码
            app_key="3146673438"
            app_secret="f65a02335629c4ff5c4a5314fedfa97f" 
            auth = OAuthHandler(app_key, app_secret)
            auth_url = auth.get_authorization_url()
            wx.MessageBox("你这是第一次使用该软件,请在接下来代开的网页中\n允许使用该应用,并将获得的PIN吗复制下来","验证")
            webbrowser.open(auth_url)
            text= wx.GetPasswordFromUser("请授权该应用,并将您获得的PIN码\n复制到下面的方框内","PIN")
            token=auth.get_access_token(string.atoi(text)) 
            file=open("token","w")
            file.write(token.key+"\n"+token.secret)
            file.close()
            wx.MessageBox("恭喜您,验证成功!","验证")
            
        self.weibo=MyWeibo()

        self.timer=wx.Timer(self)#设置定时器
        self.Bind(wx.EVT_TIMER,self.OnTimer,self.timer)
        self.timer.Start(10000)
        
        self.panel=wx.Panel(self,-1)
        self.createMenuBar()
Пример #25
0
verifier = raw_input('PIN: ').strip() 
#取出请求令牌密钥(桌面应用跳过此处)
rtKey = auth.request_token.key;
rtSecret = auth.request_token.secret;
#   进行到这一步针对桌面应用和网页应用有两个不同的分支:
#   1、桌面应用将授权页面网址提供给用户,用户访问授权页面,输入用户名和密码并通过验证之后,获取到一个授权码,回到桌面应用中提交该授权码。
#   2、网页应用直接将用户引导至授权页面,引导前应将rtKey和rtSecret缓存到Session中。当用户在授权页面输入用户名和密码并通过验证之后,
#     授权页面会调用网页应用的回调页面,同时传递参数oauth_token和oauth_verifier,其中oauth_token应和rtKey相同(回调页面中需确认此处),
#     而oauth_verifier即为授权码,下文中简称为verifier。
#   有了授权码verifier之后,加上之前缓存在Session中的rtKey和rtSecret便可获取用户令牌密钥。

#设定请求令牌密钥(桌面应用跳过此句)
auth.set_request_token( rtKey, rtSecret );

#获取用户令牌密钥.
access_token = auth.get_access_token( verifier );
atKey = access_token.key;
atSecret = access_token.secret;
#   终于,我们获取到了用户令牌密钥atKey和atSecret,接下来的所有步骤都需要用这两个参数来验证用户的身份。

# 三、获取用户信息
from weibopy.error import WeibopError;

#设定用户令牌密钥.
auth.setToken( atKey, atSecret );
#绑定用户验证信息.
api = API(auth);

#获取用户信息.
try:
  user = api.verify_credentials();
Пример #26
0
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        #-- Get access token from in coming url --#
        oauth_verifier=cgi.escape(self.request.get('oauth_verifier'))
        logging.debug("oauth_verifier is "+oauth_verifier)
        request_token=cgi.escape(self.request.get('oauth_token'))
        logging.debug("request_token is "+request_token)
        dbkey = cgi.escape(self.request.get('UID'))
        logging.debug("UID is "+ dbkey)

        #-- Find if token is defined in DB? --#
        #TODO: handle exception if search db failed
        Target = db.get(db.Key(dbkey))
        Target.verifier = oauth_verifier

        if Target.service == "sina":
            auth1 = OAuthHandler(CONSUMER_KEY_SINA, CONSUMER_SECRET_SINA,self.call_back_url)
            auth1.request_token = Target.toOauthToken()
            auth1.get_access_token(Target.verifier.strip())
            auth1.api = API(auth1)
            #status = auth1.api.update_status("Hello weibo! from myapp".encode("utf-8"))
            access_token_user_name = auth1.get_username()

            #-- Write to DB --#
            Target.fromOauthToken(auth1.access_token)
            Target.states = "accessTokenOK"
            Target.put()

            #-- Show info to user --#
            self.response.out.write('Hello '+access_token_user_name+"\nYou are verified!!")

        if Target.service == "twitter":
            auth1 = OAuthHandler(CONSUMER_KEY_TWITTER, CONSUMER_SECRET_TWITTER,self.call_back_url+"?UID="+dbkey,True)
            auth1.OAUTH_HOST = 'api.twitter.com'
            auth1.OAUTH_ROOT = '/oauth/'
            auth1.request_token = Target.toOauthToken()

            try:
                auth1.get_access_token(Target.verifier.strip())
#                status = auth1.api.update_status("Hello weibo! from myapp".encode("utf-8"))
                
            except Exception,error_message:
                logging.error("Get access token failed!! ")
                logging.debug("Service Provider " + Target.service)
                logging.debug("oauth_token:" + request_token)
                logging.debug("oauth_verifier:" + oauth_verifier)
                logging.debug( error_message )
                self.response.out.write( error_message )

            auth1.api = API(auth1,host='api.twitter.com',search_host='api.twitter.com')
            user = auth1.api.verify_credentials()
            if user:

                auth1.username = user.screen_name
                self.response.out.write('Hello '+auth1.username+"\nYou are verified!!")
            else:
                logging.error("Cannot Get user Name!")

            #-- Write to DB --#
            Target.fromOauthToken(auth1.access_token)
            Target.states = "accessTokenOK"
            Target.put()
Пример #27
0
class WeiboBackup(object):
    """
    新浪微博自动备份.
    """
    def __init__(self):
        self.hdl = OAuthHandler(APP_KEY, APP_SECRET)
        self.api = None
        self.writer = None
        self.token  = {}

    def auth(self, pin):
        try:
            token = self.hdl.get_access_token(pin)
            """
            self.token = dict(parse_qsl(token))
            self.hdl.setToken(
                self.token['oauth_token'],
                self.token['oauth_token_secret']
            )
            self.hdl.setToken(
                ACCESS_TOKEN,
                ACCESS_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):
        self.writer = Writer(filename)
        page,alert_num = 1,0
        while alert_num<ALERT_MAX_TIMES:
            page = self.get_data(screen_name, page)
            alert_num += 1