示例#1
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
示例#2
0
 def GET(self):
     access_token = session.get('access_token',None)
     uid = session.get('uid',None)
     expires_in = session.get('expires_in',None)
     if access_token != None and uid!=None and expires_in!=None:
         client = APIClient(app_config.APP_KEY, app_secret=app_config.APP_SECRET, redirect_uri=app_config.CALLBACK_URL)
         client.set_access_token(access_token,expires_in)
         return showUserInfo(client,uid,expires_in)
     else:
         client = APIClient(app_key=app_config.APP_KEY, app_secret=app_config.APP_SECRET, redirect_uri=app_config.CALLBACK_URL)
         url = client.get_authorize_url()
         web.seeother(url)
示例#3
0
def get_client():
    ''' 生成新浪微博SDK的client
    '''
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    return client
示例#4
0
    def __init__(self, app_key, app_secret, call_back):
        '''
    初始化相关数据
    '''
        # 新浪api认证
        self.client = APIClient(app_key=app_key,
                                app_secret=app_secret,
                                redirect_uri=call_back)
        auth_url = self.client.get_authorize_url()
        webbrowser.open(auth_url)

        code = raw_input('Please input the code: ').strip()
        r = self.client.request_access_token(code)
        access_token = r.access_token
        expires_in = r.expires_in

        self.client.set_access_token(access_token, expires_in)

        print 'INFO\t:Login success!'

        # MongoDB 数据库连接
        self.connection = Connection()
        self.db = self.connection.weibo
        self.user_collection = self.db.user_info
        self.friend_collection = self.db.user_friend
        self.follower_collection = self.db.user_follower
        print 'INFO\t:Connect to MongoDB  success!'
示例#5
0
class Weibo:
    # attributes
    APP_KEY = '1464287299'  # app key
    APP_SECRET = 'e4d573c77e41118abe06df2628cc4418'  # app secret
    CALLBACK_URL = 'http://www.example.com/callback'  # callback url
    WEIBOLIST_PATH = '../result/weibolist/'
    INFOLIST_PATH = '../result/infolist/'
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    access_token = '2.00v5KI4DFBAGbB4289cec5d0MFFs5B'

    # methods
    def getNewWeiboIdList(self):
        idlist = []
        for i in range(iternum):
            try:
                jsondata = self.client.statuses.public_timeline.get(
                    access_token=self.access_token, count=100)
                for weibo in jsondata['statuses']:
                    idlist.append(weibo['id'])
                time.sleep(60)
            except Exception, e:
                print e
                break
        return list(set(idlist))
示例#6
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
示例#7
0
def access_client():
    client = APIClient(app_key='APP_KEY',
                       app_secret='APP_SECRET',
                       redirect_uri='CALLBACK_URL')
    client.set_access_token(
        'XXXXX', '12')  ##填入获得token,形式为2.00Hk5I5B3mz1gEda51bd5caewXXXYY
    return client
示例#8
0
def GetCode(userid, passwd):
    """获取用户code"""
    print 'Get the code...',
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    referer_url = client.get_authorize_url()
    postdata = {
        "action": "login",
        "client_id": APP_KEY,
        "redirect_uri": CALLBACK_URL,
        "userId": userid,
        "passwd": passwd,
    }
    headers = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0",
        "Referer": referer_url,
        "Connection": "keep-alive"
    }
    req = urllib2.Request(url=AUTH_URL,
                          data=urllib.urlencode(postdata),
                          headers=headers)
    resp = urllib2.urlopen(req)
    print 'success!!!'
    return resp.geturl()[-32:]
示例#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)
示例#10
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)
示例#11
0
def weibo_login(request):
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    auth_url = client.get_authorize_url()

    return HttpResponseRedirect(auth_url)
示例#12
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() 
示例#13
0
def get_local_weibo_client():
    all_tokens = None
    if 'token.json' not in os.listdir('.'):
        print 'no token.json file'
        return None
    else:
        f = file('token.json', 'r')
        all_tokens = json.load(f)
        f.close()
    if not all_tokens:
        return None

    token = all_tokens.pop(0)
    APP_KEY = token['APP_KEY']
    APP_SECRET = token['APP_SECRET']
    CALLBACK_URL = token['CALLBACK_URL']
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    access_token = token['token']
    expires_in = token['expires']

    client.set_access_token(access_token, expires_in)

    return client
示例#14
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()
示例#15
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不会自动关闭文件,需要手动关闭
示例#16
0
def post_weibo(access_token, expires_in, text, pic=None):
    auth_client = APIClient(APP_KEY, APP_SECRET, CALLBACK_URL)
    auth_client.set_access_token(access_token, expires_in)
    if pic == None:
        auth_client.statuses.update.post(status=text)
    else:
        auth_client.statuses.upload.post(status=text, pic=pic)
示例#17
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())
示例#18
0
 def weiboClient(self):
     APP_KEY='1257616669'
     APP_SECRET='b8d924e1b6aa10f0bbd4e7af6ed1bf19'
     CALLBACK_URL='https://api.weibo.com/oauth2/default.html'
     AUTH_URL='https://api.weibo.com/oauth2/authorize'
     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=AUTH_URL,data=urllib.urlencode(postdata),headers=headers)
     try:
         resp=urllib2.urlopen(req)
         print "callback url is : %s" % resp.geturl()
         code=resp.geturl()[-32:]
         print "code is %s" % code
     except Exception, e:
         print e
示例#19
0
def weiboLogin(request):
    """微博登录"""
    client = APIClient(app_key=settings.APP_KEY,
                       app_secret=settings.APP_SERCET,
                       redirect_uri=settings.CALLBACK_URL)
    url = client.get_authorize_url()
    return HttpResponseRedirect(url)
示例#20
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/')
示例#21
0
def main():
    client = APIClient(
        app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=C_URL)
    client.set_access_token(ACCESS_TOKEN, EXPIRES_IN)
    base_dir = os.path.split(os.path.realpath(__file__))[0]

    f = open(os.path.join(base_dir, 'tang300.v4.json'), 'r')
    ps = json.load(f)
    f.close()
    try:
        logfilename = os.path.join(base_dir, 'log.txt')
        logfile = open(logfilename, 'r')
        idx = int(logfile.read())
        logfile.close()
    except:
        idx = 0

    p = ps[idx]
    q = urllib.quote_plus(p[1].encode('utf8'))
    s = u'《%s》%s %s https://www.google.com.hk/#q=%s' % (p[1], p[2], p[0], q)
    s = urllib.quote_plus(s.encode('utf8'))
    img = os.path.join(base_dir, 'poem_png/%03d.png' % idx)
    client.statuses.upload.post(
        status=s, pic=open(img, 'rb'))

    idx = (idx+1) % len(ps)
    logfile = open(logfilename, 'w')
    logfile.write(str(idx))
    logfile.close()
示例#22
0
 def weibo_position_search_data(self):
   client = APIClient(app_key=oauth_para['weibo']['appid'], app_secret=oauth_para['weibo']['secret'], redirect_uri=oauth_para['weibo']['redirect_url'])
   client.set_access_token( self.__weibo_access_token, self.__weibo_expires )    
   ruid = client.get.account__get_uid()
   address = request.params.get('address')
   #return address
   
   position = client.get.location__geo__address_to_geo( address = address )
   
   ruid = client.get.account__get_uid()
   userinfo = client.get.users__show( access_token =self.__weibo_access_token, uid = ruid.uid )
  
   lats = str(position.geos[0]['latitude'])
   lngs = str(position.geos[0]['longitude'])
   
   lat = string.atof( lats )
   lng = string.atof( lngs )
   
   place_photos = client.get.place__nearby__photos( access_token =self.__weibo_access_token, lat = lat, long = lng, range = 500, count = 50 )
  
   
   if 'statuses' in place_photos:
     data = json.dumps( place_photos.statuses)
     return {'data': data, 'username':userinfo.screen_name} 
   else:
     return {'error_info': 'input_error', 'username':userinfo.screen_name}
示例#23
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('/')
def _create_client():
    global _APP_ID, _APP_SECRET
    try:
        import sae
    except Exception, e:
        return APIClient(_APP_ID, _APP_SECRET,
                         'http://127.0.0.1:8080/callback')
示例#25
0
def create_user_from_weibo(request,
                           template_name='register/create_user_from_weibo.html'
                           ):

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

    if request.user.is_authenticated() or oauth_access_token is None:
        return HttpResponseRedirect(reverse('home.views.index'))

    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=_get_weibo_callback_url(request))
    client.set_access_token(oauth_access_token['access_token'],
                            oauth_access_token['expires_in'])

    weibo_user = client.get.users__show(uid=oauth_access_token['uid'])
    weibo_username = weibo_user.screen_name

    template_var = {}
    form = RegistrationForm(initial={'username': weibo_username})
    if request.method == 'POST':
        form = RegistrationForm(request.POST.copy())
        if request.method == 'POST':
            if form.is_valid():
                username = form.cleaned_data['username']
                email = form.cleaned_data['email']
                password = form.cleaned_data['password']
                user = User.objects.create_user(username, email, password)
                user.is_active = True
                user.save()

                profile = UserProfile()
                profile.user = user
                profile.song_ord_filed = 'post_datetime'
                profile.save()

                #weibo信息记录
                w_user = WeiboUser()
                w_user.user = user

                w_user.weibo_user_id = oauth_access_token['uid']
                w_user.weibo_username = weibo_username
                w_user.oauth_access_token = oauth_access_token['access_token']
                w_user.save()

                #发微博提示
                if request.POST.get('update_msg'):
                    msg = request.POST.get('bind_msg')[0:140]
                    client.post.statuses__update(status=msg)

                user = authenticate(username=username, password=password)
                auth_login(request, user)

                return HttpResponseRedirect(reverse('songs.views.my_home'))

    template_var['form'] = form
    template_var['weibo_username'] = weibo_username
    return render_to_response(template_name,
                              template_var,
                              context_instance=RequestContext(request))
示例#26
0
def get_code():
    client = APIClient(app_key=APP_KEY,
                       app_secret=APP_SECRET,
                       redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()
    #print "referer url is : %s" % 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": url
    }
    req = urllib2.Request(url=url,
                          data=urllib.urlencode(postdata),
                          headers=headers)
    resp = urllib2.urlopen(req)
    #print "callback url is : %s" % resp.geturl()
    #print "code is : %s" % resp.geturl()[-32:]
    code = resp.geturl()[-32:]
    return code
示例#27
0
def login_weibo():
    client = APIClient(app_key=current_app.config["APP_KEY"],
                       app_secret=current_app.config["APP_SECRET"],
                       redirect_uri=request.host_url +
                       url_for(".weibo_callback"))
    url = client.get_authorize_url()

    return redirect(url)
示例#28
0
 def new_view(request, *args, **kwargs):
     if 'token' in request.session and 'expire' in request.session:
         client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
         client.set_access_token(request.session['token'], request.session['expire'])
         if client.is_expires():
             return render(request, 'loginForm.html')
         return view(request, client, *args, **kwargs)
     return render(request, 'loginForm.html')
示例#29
0
def main():
    client = APIClient(app_key='1026820539',
                       app_secret='9815a7c13eb99018346d0e8f34d6a51e',
                       redirect_uri='http://raspberry.sinaapp.com/callback')
    apply_token(client)
    post_weibo(
        client, u'Post a weibo from raspberry pi at %s' %
        time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())))
示例#30
0
def login_weibo():
    callbackUrl = request.args.get('next', CALLBACK_URL)
    client_ = APIClient(app_key=APP_KEY,
                        app_secret=APP_SECRET,
                        redirect_uri=callbackUrl)
    url = client_.get_authorize_url()
    print url
    return redirect(url)