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'))
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)
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'))
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)
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
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)
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
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> ''')
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
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)
def GET(self): access_token = session.get('access_token', None) if not access_token: """ key.py中放置了开发者的信息 """ auth = OAuthHandler(key.CONSUME_KEY, key.CONSUME_SECRET, web.ctx.get('homedomain') + '/callback') #获取授权url auth_url = auth.get_authorization_url() 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() return render_template('index.html', user=user)
def __init__(self): #设定网页应用回调页面(桌面应用设定此变量为空) BACK_URL = "" #验证开发者密钥. auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL) #设定用户令牌密钥. auth.setToken(TOKEN_KEY, TOKEN_SECRET) #绑定用户验证信息. self.api = API(auth)
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
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)))
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
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('/')
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'))
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")
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'))
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')
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 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
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("/")
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')
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'))
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())
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
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)
def setAccessToken(self, key, secret): self.auth = OAuthHandler(self.consumer_key, self.consumer_secret) self.auth.setAccessToken(key, secret) self.api = API(self.auth)
# 一、应用验证相关代码 以下的代码属于基础代码,之后各个步骤的代码均需承接以下代码。 from weibopy.auth import OAuthHandler from weibopy.api import API import webbrowser #此应用的开发者密钥(此处应替换为创建应用时获取到的开发密钥) APP_KEY = '1234567890'; APP_SECRET = 'abcdefghijklmnopqrstuvwxyz123456'; #设定网页应用回调页面(桌面应用设定此变量为空) BACK_URL = "http://beauty.hit.edu.cn/backurl"; #验证开发者密钥. auth = OAuthHandler( APP_KEY, APP_SECRET, BACK_URL ); # 二、应用授权相关代码 #获取授权页面网址. auth_url = auth.get_authorization_url(); webbrowser.open(auth_url) 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便可获取用户令牌密钥。