当前位置: 首页>>代码示例>>Python>>正文


Python APIClient.request_access_token方法代码示例

本文整理汇总了Python中weibo.APIClient.request_access_token方法的典型用法代码示例。如果您正苦于以下问题:Python APIClient.request_access_token方法的具体用法?Python APIClient.request_access_token怎么用?Python APIClient.request_access_token使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在weibo.APIClient的用法示例。


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

示例1: weibo_auth

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def weibo_auth(request):

    # 获取URL参数code:

    code = request.GET.get('code')

    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=_get_weibo_callback_url(request))
    token_obj = client.request_access_token(code)
    client.set_access_token(token_obj.access_token, token_obj.expires_in)

    if request.session.has_key('oauth_access_token'):
        del request.session['oauth_access_token']

    request.session['oauth_access_token'] = { 'uid' : token_obj.uid, 'access_token' : token_obj.access_token, 'expires_in' :  token_obj.expires_in}

    oauth_access_token = request.session.get('oauth_access_token', None)

    back_to_url = reverse('songs.views.my_home')

    if token_obj is not None:
        try:
            w_user = WeiboUser.objects.get(weibo_user_id=oauth_access_token['uid'])
            user = authenticate(weibo_user=w_user)
            if user and user.is_active:
                auth_login(request,user)

        except WeiboUser.DoesNotExist:
            back_to_url = reverse('social.views.create_user_from_weibo')

    return HttpResponseRedirect(back_to_url)
开发者ID:andy071001,项目名称:dongtingfm,代码行数:32,代码来源:views.py

示例2: callback

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def callback(request):
    code = request.GET.get('code')
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    r = client.request_access_token(code)
    request.session['token'] = r.access_token
    request.session['expire'] = r.expires_in
    return HttpResponseRedirect('/')
开发者ID:Tebyt,项目名称:InterSNS,代码行数:9,代码来源:views.py

示例3: weiboLogcheck

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def weiboLogcheck(request):
    code = request.GET.get('code', None)
    if code:
        client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
        r = client.request_access_token(code)
        access_token = r.access_token   # 返回的token,类似abc123xyz456
        expires_in = r.expires_in       # token过期的UNIX时间:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4
        uid = r.uid
        # 在此可保存access token
        client.set_access_token(access_token, expires_in)
        weibo_res = client.get_user_time_line(0)
        text = weibo_res.statuses
        uname = text[0]['user']['name']


        try:
            exitUser=Users.objects.filter(login_type='1').get(weibo_id=uid)
            request.session['logintype']=1
            user = authenticate(username=uname,password=uid)
            if user is not None:
                login(request, user)
                return HttpResponseRedirect('/personalRecommend/', {'current_time': datetime.now(),'uname':request.user.username})

        except Users.DoesNotExist :

            Users.create_weiboUser(uname,uid)
            user = authenticate(username=uname,password=uid)
            if user is not None:
                login(request, user)
                request.session['logintype']=1
                return render_to_response('weibologin/tasteTest.html',
                                      {'current_time': datetime.now(),'liveJob_list':liveJob_list,'liveType_list':liveType_list})
开发者ID:leemiko0602,项目名称:personal_radio_web,代码行数:34,代码来源:views.py

示例4: weibo_check

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def weibo_check(request):
    code = request.GET.get('code', None)
    now = datetime.datetime.now()
    if code:
        client = APIClient(app_key=settings.WEIBO_APP_KEY, app_secret=settings.WEIBO_APP_SERCET, redirect_uri=settings.WEIBO_CALLBACK_URL)
        r = client.request_access_token(code)
        access_token = r.access_token   # 返回的token,类似abc123xyz456
        expires_in = r.expires_in	   # token过期的UNIX时间:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4
        uid = r.uid
        # 在此可保存access token
        client.set_access_token(access_token, expires_in)
        request.session['access_token'] = access_token
        request.session['expires_in'] = expires_in
        request.session['uid'] = uid

        # http://open.weibo.com/wiki/2/users/show
        data=client.user.show.get(uid)
        user=User(username=uid)
        user.save()
        name=data.get('name')
        return HttpResponseRedirect('/verification/index/?username='+name)
        # user = SupserWeibo(access_token=access_token, uid=uid, request=request)	  # 实例化超级微博类
        '''
        # 更新数据库
        if MyUser.objects.filter(uid=uid).exists():
            MyUser.objects.filter(uid=uid).update(last_login=now)
            user.Login()	# 登陆
            return HttpResponseRedirect('/')#返回主页
        else:
            # 创建用户并登陆
            u_id = user.createUser()
        if u_id:
            return HttpResponseRedirect('/manage/user/%s/' %u_id)
        '''
    return HttpResponse('/404/') #未获得新浪微博返回的CODE
开发者ID:Luxun0535,项目名称:Forum,代码行数:37,代码来源:views.py

示例5: access_client

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
 def access_client(self,app_index):
     #定义供替换的APP Key和Secret
     APP_KEYS_SECRETS=config.APP_KEYS_SECRETS
     
     ##随机取出一个app index
     #current_index = int(random.random()*100 % len(APP_KEYS_SECRETS))    
     APP_KEY=  APP_KEYS_SECRETS[app_index][0] #app key
     APP_SECRET = APP_KEYS_SECRETS[app_index][1] # app secret
     CALLBACK_URL = config.CALLBACK_URI # callback url
     username=config.ACCOUNT1
     password=config.PASSWORD1
     client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
     url = client.get_authorize_url()
     conn = httplib.HTTPSConnection('api.weibo.com')
     postdata = urllib.urlencode({'client_id':APP_KEY,'response_type':'code','redirect_uri':CALLBACK_URL,'action':'submit','userId':username,'passwd':password,'isLoginSina':0,'from':'','regCallback':'','state':'','ticket':'','withOfficalFlag':0})
     conn.request('POST','/oauth2/authorize',postdata,{'Referer':url, 'Content-Type': 'application/x-www-form-urlencoded'})
     res = conn.getresponse()
     page = res.read()
     conn.close()##拿新浪给的code
     code = urlparse.parse_qs(urlparse.urlparse(res.msg['location']).query)['code'][0]
     token = client.request_access_token(code)
     access_token = token.access_token # 新浪返回的token,类似abc123xyz456
     expires_in = token.expires_in # token过期的UNIX时间:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4
     # TODO: 在此可保存access token
     client.set_access_token(access_token, expires_in)##生成token
     return client
开发者ID:skymoney,项目名称:Sina_Weibo_Master,代码行数:28,代码来源:client.py

示例6: __init__

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
class Sina:
	def __init__(self, app_key, app_secret, redirect_uri):
		self.client = APIClient(app_key, app_secret, redirect_uri)
		if not os.path.exists("./sinadb"):
			self.request_url = self.client.get_authorize_url()
			print self.request_url
			code = raw_input('waiting code:')
			f = open("./sinadb", 'w')
			f.write(str(code))
			r = self.client.request_access_token(code)
			access_token = r.access_token 
			f.write(str(access_token))
			expires_in = r.expires_in 
			f.write(str(expires_in))
			f.close()
		else:
			f = open("./sinadb", 'r')
			code = f.readline().replace("\n",'')
			access_token = f.readline().replace("\n",'')
			expires_in = f.readline().replace("\n",'')
		self.client.set_access_token(access_token, expires_in)

	def twite(self):
		input_status=raw_input('STATUS: ')
		if input_status == "quit":
			return -1
		pic_path=raw_input('PICTURE: ')
		if not pic_path:
			self.client.post.statuses__update(status=input_status)
		else:
			self.client.upload.statuses__upload(status=input_status, pic=open(pic_path))
开发者ID:kevein,项目名称:twapi,代码行数:33,代码来源:sina.py

示例7: callback

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def callback():
    i = web.input()
    code = i.get("code", None)
    if code:
        # /callback?code=xxx
        client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET)
        token = client.request_access_token(code, _CALLBACK_URL)
        logging.info("got access token: %s" % str(token))
        uid = token.uid
        kw = dict(access_token=token.access_token, expires_in=token.expires_in)
        # check for update:
        if 0 == db.update("user", where="uid=$uid", vars=dict(uid=uid), **kw):
            # create user:
            client.set_access_token(token.access_token, token.expires_in)
            user = client.get.users__show(uid=uid)
            kw["uid"] = uid
            kw["name"] = user.screen_name
            kw["gender"] = user.gender
            kw["province_code"] = user.province
            kw["city_code"] = user.city
            kw["image_url"] = user.profile_image_url
            db.insert("user", **kw)
        # make a cookie:
        web.setcookie("weibouser", _make_cookie(uid, token.access_token), int(token.expires_in - time.time()))
        raise web.found("/index")
开发者ID:baepython,项目名称:baepython_sdk,代码行数:27,代码来源:urls.py

示例8: getAccessToken

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def getAccessToken():
    client = APIClient(app_key=_LocalVar.APP_KEY, app_secret=_LocalVar.APP_SECRET, redirect_uri=_LocalVar.CALLBACK_URL)
    referer_url = client.get_authorize_url()
    postdata = {
        "action": "login",
        "client_id": _LocalVar.APP_KEY,
        "redirect_uri":_LocalVar.CALLBACK_URL,
        "userId": _LocalVar.name,
        "passwd": _LocalVar.password,
        }

    headers = {
        "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
        "Referer":referer_url,
        "Connection":"keep-alive"
    }

    req  = urllib2.Request(
        url = _LocalVar.AUTH_URL,
        data = urllib.urlencode(postdata),
        headers = headers
    )

    print referer_url

    resp = urllib2.urlopen(req)
    code = resp.geturl()[-32:]
    r = client.request_access_token(code)
    access_token = r.access_token
    expires_in = r.expires_in
    # urllib2.urlopen('http://weibo.com/u/2490013033').read().decode('gbk')
    return access_token
开发者ID:sexroute,项目名称:Python,代码行数:34,代码来源:oauth2.py

示例9: LoginSuccess

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def LoginSuccess(request):

    code = request.GET.get('code')
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    r = client.request_access_token(code)
    access_token = r.access_token 
    expires_in = r.expires_in 
    
    client.set_access_token(access_token, expires_in)
    
    r=client.account.get_uid.get()
    back=client.users.show.get(uid=r.uid)
    
    
    try:
        Users.objects.get(Name=back.screen_name).Name
    except Users.DoesNotExist:
        p1 = Users(Name=back.screen_name,RegisterTime= datetime.date.year,WeiboUrl=back.profile_url,cellphone="",qq="",weibo_uid=back.id,province=back.province,city=back.city,profile_image_url=back.profile_image_url,gender=back.gender,avatar_large=back.avatar_large,description=back.description)
        p1.save()
        
        user = User.objects.create_user(back.screen_name, '[email protected]', 'testtest')
        user.save()
        
    
    user = authenticate(username=back.screen_name, password='testtest')
    if user is not None:
        login(request, user)
        
    t = get_template('FreeJoinapp/loginsuccess.html')
    html = t.render(Context({'back':""}))
    return HttpResponse(html)
开发者ID:zhangshijie,项目名称:FreeJoin,代码行数:33,代码来源:views.py

示例10: authorize

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def authorize(user_password, parameters):
    """Get Auth2.0 from weibo.
    """
    # http://jas0n.me/2014/12/19/weibo_robot/

    USERID = '[email protected]' #微博登陆邮箱
    PASSWORD = user_password #微博登陆密码

    client = APIClient(app_key=parameters['APP_KEY'], 
                       app_secret=parameters['APP_SECRET'], 
                       redirect_uri=parameters['CALLBACK_URL'])
    referer_url = client.get_authorize_url()
    # print('referer_url: %s' % referer_url)

    # 获取URL参数code:
    # https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//frank-the-obscure.me/&response_type=code&client_id=1512985854

    code = '0b9e70a77bae860c34c02fbffbfd8c00' # manually got code
    #client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET,
    #                   redirect_uri=CALLBACK_URL)
    r = client.request_access_token(code)
    access_token = r.access_token # 新浪返回的token,类似abc123xyz456
    expires_in = r.expires_in # token过期的UNIX时间:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4
    print('token:', access_token)
    print('expires in', expires_in)
    client.set_access_token(access_token, expires_in)
开发者ID:mofhu,项目名称:pkuairquality,代码行数:28,代码来源:weibo_post.py

示例11: authorize

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
    def authorize(self, username, password):
        try:
            client = APIClient(app_key=const.APP_KEY, app_secret=const.APP_SECRET,
                               redirect_uri=const.CALLBACK_URL)

            # Step 1: Get the authorize url from Sina
            authorize_url = client.get_authorize_url()

            # Step 2: Send the authorize info to Sina and get the authorize_code
            authorize_code = authorize(authorize_url, username, password)
            if not authorize_code:
                self.loginReturn.emit(self.PASSWORD_ERROR)
                return

            # Step 3: Get the access token by authorize_code
            r = client.request_access_token(authorize_code)

            # Step 4: Setup the access token of SDK
            client.set_access_token(r.access_token, r.expires_in)
            const.client = client
            self.loginReturn.emit(self.SUCCESS)
            return
        except:
            self.loginReturn.emit(self.NETWORK_ERROR)
            return
开发者ID:lxg19880914,项目名称:WeCase,代码行数:27,代码来源:LoginWindow.py

示例12: getAccess

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def getAccess():
    ACCOUNT = "[email protected]"
    PASSWORD = "aiai2012"
    
    # get configure from file
    accessFile = open( path+"/accessKey.conf", "r" )
    values = accessFile.readlines()
    accessFile.close()

    accessKeys = []
    for value in values:
        accessKeys.append( value.strip() )

    # get the weibo authorization
    try:
        APP_KEY = accessKeys[ 0 ]
        APP_SECRET = accessKeys[ 1 ]
        CALLBACK_URL = accessKeys[ 2 ]

        client = APIClient( app_key = APP_KEY, app_secret = APP_SECRET, redirect_uri = CALLBACK_URL )
        # webbrowser.open_new( client.get_authorize_url() )
        url = client.get_authorize_url()
        conn = httplib.HTTPSConnection('api.weibo.com')
        postdata = urllib.urlencode({'client_id':APP_KEY,'response_type':'code','redirect_uri':CALLBACK_URL,'action':'submit','userId':ACCOUNT,'passwd':PASSWORD,'isLoginSina':0,'from':'','regCallback':'','state':'','ticket':'','withOfficalFlag':0})
        conn.request('POST','/oauth2/authorize',postdata,{'Referer':url,'Content-Type': 'application/x-www-form-urlencoded'})
        res = conn.getresponse()
        location = res.getheader('location')
        code = location.split('=')[1]
        conn.close()
        
        r = client.request_access_token( code )
        client.set_access_token( r.access_token, r.expires_in )
        return client
    except:
        print sys.exc_info()[0], sys.exc_info()[1]
开发者ID:Lhfcws,项目名称:ai_hw,代码行数:37,代码来源:getAccess.py

示例13: GetClient

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def GetClient(_key, _secret, _redirect_uri, userName, passWord):
    
    client = APIClient(app_key = _key, 
                       app_secret = _secret, 
                       redirect_uri = _redirect_uri)
    
    url = client.get_authorize_url()
    
    print "username:" + userName
    print "password:" + passWord
    print "threads blocked for login now"
    
    #multi-threads synchronize
    theLock.acquire()
    
    webbrowser.open_new(url)
    code = raw_input()
    
    theLock.release()
    #sync finished
    
    print "lock released"
    
    tok_class = client.request_access_token(code)
    token = tok_class.access_token
    expires = tok_class.expires_in
    
    client.set_access_token(token, expires)
    
    return client
开发者ID:B-Rich,项目名称:WSpi,代码行数:32,代码来源:ClientFactory.py

示例14: __init__

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
class Weibo:
    def __init__(self):
        self.client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
        self.conn = httplib.HTTPSConnection('api.weibo.com')

    def auth(self, username, password):
        postdata = urllib.urlencode({'client_id':APP_KEY,'response_type':'code','redirect_uri':CALLBACK_URL,'action':'submit',\
        'userId':username,'passwd':password,'isLoginSina':0,'withOfficalFlag':0})
        self.conn.request('POST','/oauth2/authorize',postdata,{'Referer':self.client.get_authorize_url(),\
        'Content-Type':'application/x-www-form-urlencoded'})
        location = self.conn.getresponse().getheader('location')
        self.conn.close()
        if location:
            r = self.client.request_access_token(location.split('=')[1])
            return (r.access_token, r.expires_in)
        else:
            return None

    def setToken(self, access_token, expires_in):
        self.client.set_access_token(access_token, expires_in)

    def post(self, text, image):
        return self.client.statuses.upload.post(status=text, pic=urllib.urlopen(image))

    def profile(self):
        u = self.client.get.statuses__user_timeline().statuses[0].user
        return(u.screen_name, u.avatar_large)

    def getComment(self, mid):
        return self.client.comments.show.get(id=int(mid))

    def addComment(self, newcomment, mid):
        return self.client.comments.create.post(comment=newcomment, id=int(mid))
开发者ID:wonleing,项目名称:live-shooter,代码行数:35,代码来源:sina.py

示例15: register

# 需要导入模块: from weibo import APIClient [as 别名]
# 或者: from weibo.APIClient import request_access_token [as 别名]
def register(request):
	if 'code' in request.GET:
		code = request.GET.get('code')
		client = APIClient(app_key=settings.WEIBO_APP_KEY, app_secret=settings.WEIBO_APP_SECRET, redirect_uri=settings.WEIBO_REDIRECT)
		r = client.request_access_token(code)
		access_token = r.access_token
		expires_in = r.expires_in
		uid = r.uid
		client.set_access_token(access_token,expires_in)
		user = client.users.show.get(uid=uid)
		username = user.name
		avatar = user.profile_image_url
		if UserenaSignup.objects.filter(user__username__iexact=username):
			pass
        	else:
            		new_user = UserenaSignup.objects.create_user(username,
                                                     username,
                                                     '',
                                                     uid,
                                                     not userena_settings.USERENA_ACTIVATION_REQUIRED,
                                                     userena_settings.USERENA_ACTIVATION_REQUIRED)

		        myProfile = MyProfile.objects.get(user=new_user)
            		myProfile.socialImageUrl = avatar
            		myProfile.save()
        	user = authenticate(username=username, password=uid)
      		login(request, user)
        	return HttpResponseRedirect('/')
		
开发者ID:Atreia,项目名称:grad_project,代码行数:30,代码来源:views.py


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