Exemplo n.º 1
0
def begin():

APP_KEY = 'xxxxxxxx' # app key
APP_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # app secret
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html' # callback url

client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)

code = get_code()

r = client.request_access_token(code)
print r
access_token = r.access_token # 新浪返回的token,类似abc123xyz456
expires_in = r.expires_in # token过期的UNIX时间

client.set_access_token(access_token, expires_in)

#发普通微博
client.statuses.update.post(status=u'test')

#发图片微博
f = open('C:/pic/test.jpg', 'rb')
r = client.statuses.upload.post(status=u'测试OAuth 2.0带图片发微博', pic=f)
f.close() # APIClient不会自动关闭文件,需要手动关闭

begin() 
Exemplo n.º 2
0
    def build_token(self):
        all_tokens = []
        tmp = {}
        app_key = APP_KEY
        app_secret = APP_SECRET
        callback_url = CALLBACK_URL

        for i in range(len(app_key)):
            A_K = app_key[i]
            A_S = app_secret[i]
            C_U = callback_url
            client = APIClient(A_K, A_S, C_U)
            print 'authorize_url: ', client.get_authorize_url()
            code = raw_input('code: ')
            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
            tmp['APP_KEY'] = A_K
            tmp['APP_SECRET'] = A_S
            tmp['CALLBACK_URL'] = C_U
            tmp['token'] = access_token
            tmp['expires'] = expires_in
            all_tokens.append(tmp)
            tmp = {}
        f = file(self.token_file, 'w')
        json.dump(all_tokens, f)
        f.close()
Exemplo n.º 3
0
def get_weibo_client():
    APP_KEY = APP_KEY[0]
    APP_SECRET = APP_SECRET[0]
    CALLBACK_URL = CALLBACK_URL
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)

    print 'authorize_url: ', client.get_authorize_url()
    code = raw_input('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 'access_token: ', access_token
    print 'expires_in: ', expires_in
    # store in local
    f = file('token.json', 'w')
    token = dict(token=access_token, expires=expires_in)
    json.dump(token, f)
    f.close()
    client.set_access_token(access_token, expires_in)

    return client
Exemplo n.º 4
0
def upload_pic(code):
    #print "codecodecodecode"
    #print code
    app_key = '2375582409'
    app_secret = '30efe65a663641a1c5b75f1f32063892'
    callback_url = 'https://api.weibo.com/oauth2/default.html'
    client = APIClient(app_key=app_key,
                       app_secret=app_secret,
                       redirect_uri=callback_url)
    #code = raw_input("Input code:")
    r = client.request_access_token(code)
    access_token = r.access_token
    expires_in = r.expires_in

    client.set_access_token(access_token, expires_in)

    idx = 1
    default_msg_part_1 = 'This is no.'
    default_msg_part_2 = ' msg sent automatically from benny"s robot HAHAHA'

    # send a weibo with img
    f = open('test.jpg', 'rb')
    #r = client.statuses.share.post(status=u'test: weibo with an img. -benny')
    r = client.statuses.share.post(access_token=access_token,
                                   status=u'测试 http://www.weibo.com/',
                                   pic=f)
    f.close()  # APIClient不会自动关闭文件,需要手动关闭
Exemplo n.º 5
0
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))
Exemplo n.º 6
0
def weibo_check(request):
    code = request.GET.get('code', None)
    now = datetime.datetime.now()
    if code:
        client = APIClient(app_key=settings.APP_KEY,
                           app_secret=settings.APP_SERCET,
                           redirect_uri=settings.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
        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/')
Exemplo n.º 7
0
def weibo_login_check(request):
    code = request.GET.get('code', None)
    back_to_url = _get_referer_url(request)
    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
    
    request.session['oauth_access_token'] = r
    client.set_access_token(access_token, expires_in)
    uid=client.account.get_uid.get()  
    data=client.users.show.get(uid=uid['uid'])
    user={
    'weibo_id':data['id'],
    'name':data['screen_name'],
    'description':data['description'],
    'avatar':data['avatar_large'],
    'created_at':datetime.datetime.now().strftime('%y年%m月%d日 %H:%M:%S'),
    }

    #check the database
    user_ins=profile_manager()
    user_ins.check_or_save(user)
    request.session['user']=user
    return HttpResponseRedirect(back_to_url)
Exemplo n.º 8
0
def getAccess():
    ACCOUNT = "*****@*****.**"
    PASSWORD = "******"
    
    # 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]
Exemplo n.º 9
0
	def get_user_info(self,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
		print r.access_token,r.expires_in
		client.set_access_token(access_token, expires_in)
		uid = client.get.account__get_uid().uid
		print uid
		user  = User.verify_user_openID(accountType=User.USER_TYPE_SINA_WEIBO,\
							accountID=uid)
		if not user:
			user_info = client.get.users__show(uid=uid)
			user = User.new(username="******" % (User.USER_TYPE_SINA_WEIBO,uid),\
						accountType=User.USER_TYPE_SINA_WEIBO,accountID=uid)
			user.screen_name = user_info.screen_name
			user.gender	= user_info.gender
			user.headPortrait_url = user_info.profile_image_url #avatar_large?
			print user_info
			user.openIDinfo = user_info
		else:
			print "old user"

		if user.last_login == None:
			user.bonus_notification = 1
		else:
			last_login_date = datetime.fromtimestamp(user.last_login)
			if last_login_date.date() < datetime.today().date():
				user.bonus_notification = 1
		user.last_login	= int(time.time())

		self.got_user_info(uid,user)
Exemplo n.º 10
0
def publish(msg):


#    print msg
    #print url
    code_obj = Code.objects.first()
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    try:
        if code_obj and code_obj.access_token and code_obj.expires_in:
            pass
        else:
            if not code_obj:
                return redirect(client.get_authorize_url())
            r = client.request_access_token(code_obj.code)
            code_obj.access_token = r.access_token # 新浪返回的token,类似abc123xyz456
            code_obj.expires_in = r.expires_in # token过期的UNIX时间:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4
            code_obj.save()

        access_token = code_obj.access_token
        expires_in = code_obj.expires_in

        assert access_token
        print expires_in
        ### TODO: 在此可保存access token
        print "access_token", access_token
        print 'expires_in', expires_in
        client.set_access_token(access_token, expires_in)
        #
        print client.get.statuses__user_timeline()
        print client.post.statuses__update(status=msg)
    except:
        return redirect(client.get_authorize_url())
Exemplo n.º 11
0
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:"******"password:"******"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
Exemplo n.º 12
0
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
Exemplo n.º 13
0
Arquivo: test.py Projeto: kunlbc/test
def event_func():
    APP_KEY = "2218208544"
    APP_SECRET = "956ae245a2f62a11a9eca1d91fbda092"
    CALLBACK_URL = "http://cdgir.cumt.edu.cn/ShowCode.aspx"
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()
    print url
    webbrowser.open(url)

    code = raw_input("input the code:").strip()
    print code
    r = client.request_access_token(code)
    access_token = r.access_token
    expires_in = r.expires_in
    client.set_access_token(access_token, expires_in)
    poi_result = client.place.nearby.pois.get(lat="39.98435", long="116.30999")

    text = ""
    print poi_result.total_number
    for val in poi_result.pois:
        # for k, v in val.items():
        # print ("%s : %s" % (k,v))这个是val这个dic的循环遍历
        text += "%s\t%s\t%s\t%s\t%s\r\n" % (val.poiid, val.title, val.lon, val.lat, val.address)  # 可参考api的json返回示例

    # print text.encode('utf-8')
    # print text.encode('utf-8')
    open("poi.txt", "a").write(text.encode("utf-8"))
Exemplo n.º 14
0
def weibo_login_check(request):
    code = request.GET.get('code', None)
    back_to_url = _get_referer_url(request)
    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

    request.session['oauth_access_token'] = r
    client.set_access_token(access_token, expires_in)
    uid = client.account.get_uid.get()
    data = client.users.show.get(uid=uid['uid'])
    user = {
        'weibo_id': data['id'],
        'name': data['screen_name'],
        'description': data['description'],
        'avatar': data['avatar_large'],
        'created_at': datetime.datetime.now().strftime('%y年%m月%d日 %H:%M:%S'),
    }

    #check the database
    user_ins = profile_manager()
    user_ins.check_or_save(user)
    request.session['user'] = user
    return HttpResponseRedirect(back_to_url)
Exemplo n.º 15
0
Arquivo: test2.py Projeto: kunlbc/test
def event_func():
    APP_KEY='2218208544'
    APP_SECRET='956ae245a2f62a11a9eca1d91fbda092'
    CALLBACK_URL='http://cdgir.cumt.edu.cn/ShowCode.aspx'
    client=APIClient(app_key=APP_KEY,app_secret=APP_SECRET,\
                     redirect_uri=CALLBACK_URL)
    url=client.get_authorize_url()
    print url
    webbrowser.open(url)

    code=raw_input("input the code:").strip()
    print code
    r=client.request_access_token(code);
    access_token=r.access_token
    expires_in=r.expires_in
    client.set_access_token(access_token,expires_in)
    val=client.place.pois.show.get(poiid='B2094757D06FA3FD4499')
    text="%s\t%s\t%s\t%s\r\n" % (val.title,val.lon,val.lat,val.address)
    #print poi_result.total_number
    #for val in poi_result:
        #for k, v in val.items():
            #print ("%s : %s" % (k,v))这个是val这个dic的循环遍历
        #text+="%s\t%s\t%s\t%s\r\n" % (val.title,val.lon,val.lat,val.address)#可参考api的json返回示例

    print text
    #print text.encode('utf-8')
    open('log.txt','a').write(text.encode('utf-8'))
Exemplo n.º 16
0
Arquivo: views.py Projeto: jtr109/ToDo
def weibo_login():
    app_key = current_app.config['APP_KEY']
    app_secret = current_app.config['APP_SECRET']
    callback_url = current_app.config['CALLBACK_URL']
    client = APIClient(app_key=app_key, app_secret=app_secret, redirect_uri=callback_url)
    code = request.args.get('code')
    try:
        r = client.request_access_token(code)
    except APIError:
        flash('Invalid weibo code. Please Try again.')
        return redirect(request.args.get('next') or url_for('auth.login'))
    access_token = r.access_token
    expires_in = r.expires_in
    client.set_access_token(access_token, expires_in)
    uid = r.get('uid')
    if uid is None:
        flash('Not found uid of weibo')
        return redirect(request.args.get('next') or url_for('auth.login'))
    screen_name = client.statuses.user_timeline.get().get('statuses')[0].get('user').get('screen_name')
    user = User.query.filter_by(weibo_uid=uid).first()
    if user is None:
        user = User(weibo_uid=uid, username=screen_name, confirmed=True)
        user.upgrade_bind_mode()
        db.session.add(user)
        db.session.commit()
    login_user(user)  # the second argument is 'remember me'
    return redirect(request.args.get('next') or url_for('main.index'))
Exemplo n.º 17
0
 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
Exemplo n.º 18
0
def publish(msg):

    #    print msg
    #print url
    code_obj = Code.objects.first()
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    try:
        if code_obj and code_obj.access_token and code_obj.expires_in:
            pass
        else:
            if not code_obj:
                return redirect(client.get_authorize_url())
            r = client.request_access_token(code_obj.code)
            code_obj.access_token = r.access_token  # 新浪返回的token,类似abc123xyz456
            code_obj.expires_in = r.expires_in  # token过期的UNIX时间:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4
            code_obj.save()

        access_token = code_obj.access_token
        expires_in = code_obj.expires_in

        assert access_token
        print expires_in
        ### TODO: 在此可保存access token
        print "access_token", access_token
        print 'expires_in', expires_in
        client.set_access_token(access_token, expires_in)
        #
        print client.get.statuses__user_timeline()
        print client.post.statuses__update(status=msg)
    except:
        return redirect(client.get_authorize_url())
Exemplo n.º 19
0
    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
    def get_user_info(self, 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
        print r.access_token, r.expires_in
        client.set_access_token(access_token, expires_in)
        uid = client.get.account__get_uid().uid
        print uid
        user = User.verify_user_openID(accountType=User.USER_TYPE_SINA_WEIBO, accountID=uid)
        if not user:
            user_info = client.get.users__show(uid=uid)
            user = User.new(
                username="******" % (User.USER_TYPE_SINA_WEIBO, uid),
                accountType=User.USER_TYPE_SINA_WEIBO,
                accountID=uid,
            )
            user.screen_name = user_info.screen_name
            user.gender = user_info.gender
            user.headPortrait_url = user_info.profile_image_url  # avatar_large?
            print user_info
            user.openIDinfo = user_info
        else:
            print "old user"

        if user.last_login == None:
            user.bonus_notification = 1
        else:
            last_login_date = datetime.fromtimestamp(user.last_login)
            if last_login_date.date() < datetime.today().date():
                user.bonus_notification = 1
        user.last_login = int(time.time())

        self.got_user_info(uid, user)
Exemplo n.º 21
0
def weibo_check(request):
    code = request.GET.get('code', None)
    now = datetime.datetime.now()
    if code:
        client = APIClient(app_key=settings.APP_KEY, app_secret=settings.APP_SERCET, redirect_uri=settings.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
        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/')
Exemplo n.º 22
0
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('/')
Exemplo n.º 23
0
Arquivo: sina.py Projeto: kevein/twapi
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))
Exemplo n.º 24
0
 def accessToken_get(self):
     APP_KEY = '1690375172'
     APP_SECRET = 'e09cff8b33bd34426831fbf63caf00ca'
     CALLBACK_URL = 'http://weibo.com/itgeeks'
     ACCOUNT = '*****@*****.**'
     PASSWORD = '******'
     
     #for getting the authorize url
     client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
     url = client.get_authorize_url()
     print 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()
     print 'headers===========',res.getheaders()
     print 'msg===========',res.msg
     print 'status===========',res.status
     print 'reason===========',res.reason
     print 'version===========',res.version
     location = res.getheader('location')
     print location
     code = location.split('=')[1]
     conn.close()
     
     r = client.request_access_token(code)
     access_token = r.access_token # The token return by sina
     expires_in = r.expires_in
     
     print "access_token=" ,access_token, "expires_in=" ,expires_in
     
     #save the access token
     client.set_access_token(access_token, expires_in)
     return client
Exemplo n.º 25
0
def weibo_auth_end(request):
    code   = request.GET['code']
    client = APIClient(app_key=weibo_app_key, app_secret=weibo_app_secret, redirect_uri=weibo_call_back)
    r      = client.request_access_token(code)

    uid          = r.uid
    access_token = r.access_token 
    expires_in   = r.expires_in 

    client.set_access_token(access_token, expires_in)

    response = HttpResponseRedirect("/")

    response.set_cookie('token', access_token)
    response.set_cookie('expires_in', str(int(expires_in)))
    response.set_cookie('weibo_uid', str(uid))

    show=client.users.show.get(access_token=access_token, uid=uid)

    username   = '******' + str(uid)
    password   = '******'
    first_name = 'weibo'
    last_name  = show['screen_name']

    user = auth.authenticate(username=username, password=password)
    if user is None:
        user = User.objects.create_user(username=username, password=password)
        user.first_name = first_name
        user.last_name  = last_name
        user.save()

    user = auth.authenticate(username=username, password=password)
    auth.login(request, user)

    return response
Exemplo n.º 26
0
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('/')
		
Exemplo n.º 27
0
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")
Exemplo n.º 28
0
def authorize(user_password, parameters):
    """Get Auth2.0 from weibo.
    """
    # http://jas0n.me/2014/12/19/weibo_robot/

    USERID = '*****@*****.**' #微博登陆邮箱
    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)
Exemplo n.º 29
0
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, '*****@*****.**', 'testtest')
        user.save()
        
    
    user = authenticate(username=back.screen_name, password='******')
    if user is not None:
        login(request, user)
        
    t = get_template('FreeJoinapp/loginsuccess.html')
    html = t.render(Context({'back':""}))
    return HttpResponse(html)
Exemplo n.º 30
0
def callback():
    code = request.args.get('code')
    if code is not None:
        client = APIClient(
            app_key = current_app.config['APP_KEY'],
            app_secret = current_app.config['APP_SECRET'],
            redirect_uri = current_app.config['CALLBACK_URL'])
        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)
        session['access_token'] = access_token
        user = User.query.filter_by(uuid = uid).first()
        if user is not None:
            login_user(user)
            return redirect(url_for('main.index'))
        else:
            u = client.users.show.get(uid = uid)
            user = User(
                uuid = uid,
                name = u.get('screen_name'),
                location = u.get('location'),
                description = u.get('description'),
                avatar = u.get('profile_image_url'),
                url = u.get('domain'),
                gender = u.get('gender')
            )
            db.session.add(user)
            login_user(user)
            return redirect(url_for('main.index'))
    else:
        return redirect(url_for('main.index'))
Exemplo n.º 31
0
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='******'''
        # 更新数据库
        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
Exemplo n.º 32
0
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)
Exemplo n.º 33
0
     def GET(self):
        try:
            ins=web.input()
   
            # 获取URL参数code:
            code = ins.get('code')

            client = APIClient(app_key=CONSUME_KEY, app_secret=CONSUME_SECRET,redirect_uri=web.ctx.get('homedomain')+'/callback')
            
            r = client.request_access_token(code)
            access_token = r.access_token # 新浪返回的token,类似abc123xyz456
            #return str(access_token )
            expires_in = r.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)
            
            #oauth_verifier=ins.get('oauth_verifier',None)
            #request_token=session.get('request_token',None)
            #auth=OAuthHandler(CONSUME_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
            
            session.code = code
            session.expires_in = expires_in
            #return str(access_token)
            print '111111111111111111111'
            #user = client.get.users_show()
            #id = client.get.account__get_uid()
            #return str(expires_in)
            web.seeother("/index")
        except Exception:
            web.header("Content-Type", "text/html;charset=utf-8")
            return ':-( 出错了在这里222'+ str(code)
Exemplo n.º 34
0
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})
Exemplo n.º 35
0
 def get(self, request):
     # 得到回传的 code
     code = request.GET.get('code')
     oauth_sina = APIClient(app_key=settings.SINA_APP_KEY,
                            app_secret=settings.SINA_APP_SECRET,
                            redirect_uri=settings.SINA_REDIRECT_URI)
     try:
         # 根据 code 得到 tocken => {'access_token': '2.00IsO_OGJcPibD120f9a82d9R4xf1C', 'uid': '5708251100', 'expires_in': 1563044399, 'expires': 1563044399}
         tocken = oauth_sina.request_access_token(code=code)
     except Exception as e:
         logger.error(e)
         return http.HttpResponseServerError('Oauth2.0认证失败!')
     # 获取 uid
     uid = tocken.get('uid')
     # 判断 uid 是否绑定用户
     try:
         sina_user = OAuthSinaUser.objects.get(uid=uid)
     except Exception as e:
         # 查询失败说明未绑定,跳转到绑定页面
         # 将 uid 加密
         secret_uid = SecretOauth().dumps({'uid': uid})
         context = {'uid': secret_uid}
         return render(request, 'sina_callback.html', context)
     else:
         # 用户已绑定,则记录用户登陆状态
         user = sina_user.user
         login(request, user)
         # 跳转到首页
         response = redirect(reverse('contents:index'))
         # 设置 cookie
         response.set_cookie('username',
                             user.username,
                             max_age=3600 * 24 * 14)
         return response
Exemplo n.º 36
0
class Crawler():
    def __init__(self, client_id, redirect_uri, username, passwd):
        url = "https://api.weibo.com/oauth2/authorize?client_id="+client_id+"&redirect_uri="+redirect_uri+"&response_type=code"
        conn = httplib.HTTPSConnection("api.weibo.com")
        postdata = urllib.urlencode({'client_id':client_id,'redirect_uri':redirect_uri,'action':'submit','userId':username,'passwd':passwd})
        conn.request('POST','/oauth2/authorize',postdata,{'Referer':url, 'Content-Type': 'application/x-www-form-urlencoded'})
        res = conn.getresponse()
        page = res.read()
        code = res.msg['Location'].split("?")[1][5:]
        self.client = APIClient(app_key=client_id, app_secret=app_scret, redirect_uri=redirect_uri)
        r = self.client.request_access_token(code)
        self.access_token = r.access_token
        # expires_in = r.expires_in
        self.client.set_access_token(r.access_token, r.expires_in)

    def users_show(self, user_id):
        print self.client.users.show.get(uid=user_id)

    def friendships_followers_active(self, user_id):
        print self.client.friendships.followers.active.get(uid = user_id)

    def statuses_user_timeline(self, user_id):
        print self.client.statuses.user_timeline.get(uid = user_id, page = 1)

    def statuses_go(self, user_id):
        print self.client.statuses.go.get(uid = user_id)
Exemplo n.º 37
0
Arquivo: app.py Projeto: rw1993/Youji
 def GET(self):
     webinput=web.input()
     code=webinput[u'code']
     client=APIClient(app_key="367162776",app_secret="059f286cb49d0d922dd22aa83b5853d9",redirect_uri="http://0.0.0.0:8080/get_code")
     r=client.request_access_token(code)
     print r[u'access_token']
     print r[u'expires_in']
     return "hello"
Exemplo n.º 38
0
def prepare():
    code = getCode(USER_ID, PASSWORD)
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    response = client.request_access_token(code)
    access_token = response.access_token
    expires_in = response.expires_in
    client.set_access_token(access_token, expires_in)
    return client
Exemplo n.º 39
0
def get_auth_client():
    """get a auth weibo api client"""
    client = APIClient(app_key=conf.APP_KEY, app_secret=conf.APP_SECRET, redirect_uri=conf.CALLBACK_URL)
    url = client.get_authorize_url()
    code = get_code(url)
    r = client.request_access_token(code)
    client.set_access_token(r.access_token, r.expires_in)
    return client
Exemplo n.º 40
0
def get_access_token():
    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  # access token,e.g., abc123xyz456
    expires_in = r.expires_in  # token expires in
    print access_token
    print expires_in
Exemplo n.º 41
0
    def authorization(self, **kwargs):
        APP_KEY = kwargs.get("APP_KEY")
        APP_SECRET = kwargs.get("APP_SECRET")
        CALLBACK_URL = kwargs.get("CALLBACK_URL")
        USER = kwargs.get("USER")
        PWD = kwargs.get("PWD")
        client = APIClient(app_key=APP_KEY,
                           app_secret=APP_SECRET,
                           redirect_uri=CALLBACK_URL)
        url = client.get_authorize_url()
        driver = webdriver.Chrome()
        driver.maximize_window()
        driver.implicitly_wait(30)
        driver.get(url)
        time.sleep(5)
        driver.find_element_by_id("userId").send_keys(USER)
        ActionChains(driver).double_click(
            driver.find_element(by=By.XPATH,
                                value="/html/body/label")).perform()
        for i in PWD:
            pyautogui.hotkey(i)
        time.sleep(2)
        dis = driver.find_element_by_xpath(
            "//*[@id=\"outer\"]/div/div[2]/form/div/div[1]/div[1]/p[3]"
        ).get_attribute("style")
        if not dis == 'display: none;':
            ActionChains(driver).double_click(
                driver.find_element(
                    by=By.XPATH,
                    value=
                    "//*[@id=\"outer\"]/div/div[2]/form/div/div[1]/div[1]/p[3]/label"
                )).perform()
            print('输入输入验证码登录后再往控制台按回车键:')
            input()

        driver.find_element_by_xpath(
            "//*[@id=\"outer\"]/div/div[2]/form/div/div[2]/div/p/a[1]").click(
            )
        time.sleep(1)
        try:
            driver.find_element_by_xpath(
                "//*[@id=\"outer\"]/div/div[2]/form/div/div[2]/div/p/a[1]"
            ).click()
            time.sleep(1)
        except:
            pass
        code = driver.current_url.split("code=")[-1]
        driver.minimize_window()
        print(code)
        r = client.request_access_token(code)
        print(r)
        self.access_token = r.access_token  # 新浪(授权服务器)返回的token
        expires_in = r.expires_in

        client.set_access_token(self.access_token, expires_in)
        self.client = client
        driver.close()
Exemplo n.º 42
0
def prepare():
    code = getCode(USER_ID, PASSWORD)
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    response = client.request_access_token(code)
    access_token = response.access_token
    expires_in = response.expires_in
    client.set_access_token(access_token, expires_in)
    return client
Exemplo n.º 43
0
def get_auth_client():
    """get a auth weibo api client"""
    client = APIClient(app_key=conf.APP_KEY,
                       app_secret=conf.APP_SECRET,
                       redirect_uri=conf.CALLBACK_URL)
    url = client.get_authorize_url()
    code = get_code(url)
    r = client.request_access_token(code)
    client.set_access_token(r.access_token, r.expires_in)
    return client
Exemplo n.º 44
0
def login(code):
    print 'Login...',
    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
    client.set_access_token(access_token, expires_in)
    print 'success!!!'
    return client
Exemplo n.º 45
0
def weiboLoginBack(request):
    #得到微博认证的信息
    code = request.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
    # TODO: 在此可保存access token
    request.session['access_token'] = access_token
    request.session['expires_in'] = expires_in
    client.set_access_token(access_token, expires_in)
    #测试发微博
    #    status = u'亲们,俺刚才手快,测试了一把,您别b4啊!'
    #    client.post.statuses__update(status=status)
    #得到微博用户的id,如果有绑定,则直接登录,没有则跳到绑定页面
    json_obj = client.get.statuses__user_timeline()
    weibo_user = json_obj['statuses'][0]['user']
    #得到用户的weibo UID
    weibo = weibo_user['id']
    #    request.session['weibo_client'] = client
    request.session['weibo'] = weibo
    #得到用户的微博nick
    weibo_nick = weibo_user['screen_name']
    request.session['weibo_nick'] = weibo_nick
    a = Admin.objects.filter(weibo=weibo)
    #先尝试admin登陆
    if len(a) != 0:
        request.session['admin'] = a[0]
        now = datetime.datetime.now()
        list = Match.objects.filter(matchtime__gte=now).order_by(
            '-state', 'matchtime')
        c = Context({'list': list, 'session': request.session})
        t = loader.get_template('admin.htm')
        return HttpResponse(t.render(c))
    #尝试用户登陆
    u = Gambler.objects.filter(weibo=weibo)
    if len(u) != 0:
        gambler = u[0]
        request.session['gambler'] = gambler
        gambler.weibo_nick = weibo_nick
        gambler.save()
        return myaccount(request)
    else:
        c = Context({
            'info': 'Please bind your account or register first!',
            'session': request.session
        })
        t = loader.get_template('bind.htm')
        return HttpResponse(t.render(c))
    return HttpResponseRedirect("/")
Exemplo n.º 46
0
    def _get_sina_profile(self, code=None, openid=None, request=None):
        redirect_uri = request.build_absolute_uri('authentication_callback')
        sina_client = APIClient(app_key=settings.SINA_APP_ID,
                                app_secret=settings.SINA_APP_SECRET,
                                redirect_uri=redirect_uri)

        # Get a legit access token
        access_token_dict = sina_client.request_access_token(code)
        access_token = access_token_dict.access_token
        sina_client.set_access_token(access_token,
                                     access_token_dict.expires_in)

        # Read the user's profile information
        try:
            sina_profile = sina_client.account.profile.basic.get()
            sina_id = str(sina_profile['id'])
            sina_email = sina_profile['email']
        except Exception as e:
            LOG.warn("SinaAPIClient Error: %s", e)
            messages.error(request, 'You SinaID is not authorized to login.')
            return None

        # Validate the user
        valid = False
        # Get the user's bilateral friends.
        uid = settings.SINA_GROUP_ID
        page = 1
        all_friends = []
        while True:
            try:
                friends = sina_client.friendships.friends.bilateral.get(
                    uid=uid, page=page)
                # no more friends.
                if friends['total_number'] == 0:
                    break
            except Exception as e:
                LOG.debug('Error: %s', e)
                break
            all_friends.extend(friends['users'])
            page = page + 1
        user_ids = [str(user['id']) for user in all_friends]
        if sina_id in user_ids:
            valid = True
        else:
            messages.error(request,
                           "Your sinaID is not followed by %s yet." % uid)

        return dict(user_id=sina_id,
                    user_email=sina_email,
                    access_token=access_token,
                    valid=valid)
Exemplo n.º 47
0
def get_access_token(app_key, app_secret, callback_url):
    client = APIClient(app_key=app_key,
                       app_secret=app_secret,
                       redirect_uri=callback_url)
    # 获取授权页面网址
    auth_url = client.get_authorize_url()
    print auth_url
    code = raw_input("Input code:")
    r = client.request_access_token(code)
    local_access_token = r.access_token
    # token 过期的 UNIX 时间
    local_expires_in = r.expires_in

    return local_access_token, local_expires_in
Exemplo n.º 48
0
 def getAuth(self):
     client = APIClient(app_key=self.app_key,
                        app_secret=self.app_secret,
                        redirect_uri=self.redirect_uri)
     # get the authenticate page url
     url = client.get_authorize_url()
     # retrieve the authenticate code automatically
     code = self.get_code(url)
     # get access token via the code
     r = client.request_access_token(code)
     access_token = r.access_token
     expires_in = r.expires_in
     # set token to the client
     client.set_access_token(access_token, expires_in)
     return client
Exemplo n.º 49
0
def run():
    #模拟登陆
    APP_KEY = '1392181xxx'
    APP_SECRET = '612b0c6432a5f9cc7dxxxxxxx'
    CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
    USERID = '用户微博账号'
    PASSWD = '用户微博密码'

    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    referer_url = client.get_authorize_url()
    print "referer url is : %s" % referer_url

    cookies = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener(cookies)
    urllib2.install_opener(opener)

    postdata = {
        "client_id": APP_KEY,
        "redirect_uri": CALLBACK_URL,
        "userId": USERID,
        "passwd": PASSWD,
        "isLoginSina": "0",
        "action": "submit",
        "response_type": "code",
    }

    headers = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0",
        "Host": "api.weibo.com",
        "Referer": referer_url
    }

    req = urllib2.Request(url=referer_url,
                          data=urllib.urlencode(postdata),
                          headers=headers)
    try:
        resp = urllib2.urlopen(req)
        print "callback url is : %s" % resp.geturl()
        print "code is : %s" % resp.geturl()[-32:]
        code = resp.geturl()[-32:]
        r = client.request_access_token(code)
        #将access_token和expire_in设置到client对象
        client.set_access_token(r.access_token, r.expires_in)
    except Exception, e:
        print e
Exemplo n.º 50
0
def get_access_token(app_key, app_secret, callback_url):
    client = APIClient(app_key=app_key,
                       app_secret=app_secret,
                       redirect_uri=callback_url)

    auth_url = client.get_authorize_url()
    print auth_url

    code = raw_input("Input code:")
    r = client.request_access_token(code)
    access_token = r.access_token
    expires_in = r.expires_in
    print 'access_token:', access_token
    print 'expires_in:', expires_in

    return access_token, expires_in
Exemplo n.º 51
0
 def GET(self):
     #在session中保存code,用于在新浪微博认证通过后换取access_token
     code = web.input(code=None).code       
     client = APIClient(app_config.APP_KEY, app_secret=app_config.APP_SECRET, redirect_uri=app_config.CALLBACK_URL)
     r = client.request_access_token(code)
     access_token = r.access_token # 新浪返回的token
     expires_in = r.expires_in # token过期的UNIX时间
     client.set_access_token(access_token, expires_in)
     user_uid = client.get.account__get_uid()
     # TODO: 在此保存access token等保存到session中
     session.access_token=access_token
     session.expires_in=expires_in
     session.uid = user_uid['uid']
     
     uid = user_uid['uid']
     return showUserInfo(client,uid,expires_in)
Exemplo n.º 52
0
def get_auth_data(code):
    auth_client = APIClient(APP_KEY, APP_SECRET, CALLBACK_URL)
    auth_record = auth_client.request_access_token(code)
    sina_user = get_sina_user_info(auth_record.access_token, auth_record.expires_in)
    if not sina_user:
        return None
    sina_data = {}
    sina_data['access_token'] = auth_record.access_token
    sina_data['expires_in'] = auth_record.expires_in
    sina_data['sina_id'] = sina_user.id
    sina_data['screen_name'] = sina_user.name
    sina_data['avatar_small'] = sina_user.profile_image_url
    sina_data['avatar_large'] = sina_user.avatar_large
    sina_data['gender'] = sina_user.gender
    sina_data['location'] = sina_user.location
    return sina_data
Exemplo n.º 53
0
def get_access_token(app_key, app_secret, callback_url):
    client = APIClient(app_key=app_key, app_secret=app_secret, redirect_uri=callback_url)
    # 获取授权页面网址
    auth_url = client.get_authorize_url()
    print auth_url
    
    # 在浏览器中访问这个URL,会跳转到回调地址,回调地址后面跟着code,输入code
    code = raw_input("Input code:")
    r = client.request_access_token(code)
    access_token = r.access_token
    # token过期的UNIX时间
    expires_in = r.expires_in
    print 'access_token:',access_token
    print 'expires_in:', expires_in

    return access_token, expires_in
Exemplo n.º 54
0
def callback(request):
    """
    用户授权后的回调
    """
    code = request.GET.get(u'code')
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    res = client.request_access_token(code)
    access_token = res['access_token']
    expires_in = res['expires_in']
    request.session['access_token'] = access_token
    request.session['expires_in'] = expires_in
    client.set_access_token(access_token, expires_in)
    uid = client.get.account__get_uid()['uid']
    username = str(uid) + '@weibo'
    email = str(uid) + '@weibo.com'

    # 判断用户是否已经注册过
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:

        # 注册一个微博用户
        new_user = User.objects.create_user(username=username,
                                            email=email,
                                            password='******')
        new_user.is_active = True
        try:
            new_user.save()
        except Exception, e:
            return HttpResponse('连接新浪账号时出错:%s' % e)

        # 获取用户的新浪信息
        sina_profile = client.users__show(uid)

        # 增加用户档案
        new_prfile = UserProfile(user=new_user)
        new_prfile.screen_name = sina_profile['screen_name']  # 截取前10个字符
        new_prfile.city = '北京'
        new_prfile.introduction = sina_profile['description']

        try:
            new_prfile.save()
        except Exception, e:
            return HttpResponse('注册账号时服务器出现错误:%s' % str(e))
Exemplo n.º 55
0
def login():
    print "logging on..."
    client = APIClient(app_key=con.APP_KEY,
                       app_secret=con.APP_SECRET,
                       redirect_uri=con.CALLBACK_URL)
    referer_url = client.get_authorize_url()
    cookies = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener(cookies)
    urllib2.install_opener(opener)

    postdata = {
        "client_id": con.APP_KEY,
        "redirect_uri": con.CALLBACK_URL,
        "userId": con.USERID,
        "passwd": con.PASSWD,
        "isLoginSina": "0",
        "action": "submit",
        "response_type": "code",
    }

    headers = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0",
        "Host": "api.weibo.com",
        "Referer": referer_url,
        "Connection": "keep-alive"
    }

    req = urllib2.Request(url=referer_url,
                          data=urllib.urlencode(postdata),
                          headers=headers)
    try:
        resp = urllib2.urlopen(req)
        print resp.geturl()
        # 获取最后32个字符
        code = resp.geturl()[-32:]
        # 通过该code获取access_token,r是返回的授权结果
        r = client.request_access_token(code)
        print r
        # 将access_token和expire_in设置到client对象
        client.set_access_token(r.access_token, r.expires_in)
        print "login success!"
        return client
    except Exception, e:
        print 'login error!'
        print e
Exemplo n.º 56
0
def weibo_check(request):
    global client
    code = request.GET.get('code', None)
    now = datetime.datetime.now()
    if code:
        client = APIClient(app_key=APP_KEY, app_secret=APP_SERCET, 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)
        request.session['access_token'] = access_token
        request.session['expires_in'] = expires_in
        request.session['uid'] = uid
        return HttpResponseRedirect('/')
    return HttpResponse('/404/')
Exemplo n.º 57
0
    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
Exemplo n.º 58
0
def connection2api():
    """
    get access token using webibo API
    return an available client
    """
    # retrieve token
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()
    webbrowser.open_new(url)  # click auth in browser
    # input strings after 'code=' in the url of newly opened page
    code = raw_input("input the code: ")
    r = client.request_access_token(code)
    access_token = r.access_token  # weibo token
    expires_in = r.expires_in  # token expiration
    client.set_access_token(access_token, expires_in)  # save token\
    return client