コード例 #1
0
ファイル: test.py プロジェクト: qinxuzhen/weibosend
def run():
    #weibo模块的APIClient是进行授权、API操作的类,先定义一个该类对象,传入参数为APP_KEY, APP_SECRET, CALL_BACK
    client = weibo.APIClient(APP_KEY, APP_SECRET, CALL_BACK)
    #获取该应用(APP_KEY是唯一的)提供给用户进行授权的url
    auth_url = client.get_authorize_url()
    #打印出用户进行授权的url,将该url拷贝到浏览器中,服务器将会返回一个url,该url中包含一个code字段(如图1所示)
    print "auth_url : " + auth_url
    #输入该code值(如图2所示)
    code = raw_input("input the retured code : ")
    #通过该code获取access_token,r是返回的授权结果,具体参数参考官方文档:
    # http://open.weibo.com/wiki/Oauth2/access_token
    r = client.request_access_token(code)
    #将access_token和expire_in设置到client对象
    client.set_access_token(r.access_token, r.expires_in)

    #以上步骤就是授权的过程,现在的client就可以随意调用接口进行微博操作了,下面的代码就是用用户输入的内容发一条新微博

    while True:
        print "Ready! Do you want to send a new weibo?(y/n)"
        choice = raw_input()
        if choice == 'y' or choice == 'Y':
            content = raw_input('input the your new weibo content : ')
            if content:
                #调用接口发一条新微薄,status参数就是微博内容
                client.statuses.update.post(status=content)
                print "Send succesfully!"
                break
            else:
                print "Error! Empty content!"
        if choice == 'n' or choice == 'N':
            break
コード例 #2
0
def run():  
       
    client = weibo.APIClient(APP_KEY, APP_SECRET, CALL_BACK)  
        
    auth_url = client.get_authorize_url()  
    
    print "auth_url : " + auth_url  
    
    code = raw_input("input the retured code : ")  
    03a86f890a0ace3076d3acdd439dca7a
    r = client.request_access_token(code)  
        
    client.set_access_token(r.access_token, r.expires_in)   
  
    while True:  
        print "Ready! Do you want to send a new weibo?(y/n)"  
        choice = raw_input()  
        if choice == 'y' or choice == 'Y':  
            content = raw_input('input the your new weibo content : ')  
            if content:  
                client.statuses.update.post(status=content)  
                print "Send succesfully!"  
                break;  
            else:  
                print "Error! Empty content!"  
        if choice == 'n' or choice == 'N':  
            break  
コード例 #3
0
def abc():
    APP_KEY = '2260324575'  ## 填写应用程序的信息
    APP_SECRET = 'fb8ec84988227c4cb6fd6b4f5091b7a1'
    CALLBACK_URL = 'http://vpiao.wiseweb.com.cn/authformweibo'
    client = weibo.APIClient(app_key=APP_KEY,
                             app_secret=APP_SECRET,
                             redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()
    print url
コード例 #4
0
ファイル: weibo_users_2.py プロジェクト: ginking/weibo
def do_auth(conn):
    logging = Logging.get_logger('do_auth')
    client = weibo.APIClient(app_key=APP_KEY,
                             app_secret=APP_SECRET,
                             redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()
    #urllib2.Request(url)
    webbrowser.open(url)
    #command = "curl " + url
    #print command
    #os.system(command)
    # verifier = input("Verifier: ").strip()
    verifier = get_code(conn)
    #client = weibo.APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    ret = client.request_access_token(verifier)
    access_token = ret.access_token
    expires_in = ret.expires_in

    print("access_token = %s    expires_in = %s " % (access_token, expires_in))

    client.set_access_token(access_token, expires_in)
    # u = client.get.statuses__friends_timeline(count=1)
    # print u
    # print u.total_number
    # print u.statuses
    # print u.statuses[0].user.id
    # print u.statuses[0].user.screen_name
    if not client.is_expires():
        try:
            uid = client.get.account__get_uid().uid
        except weibo.APIError as apierr:
            logging.error(str(apierr))
            logging.info("Stored " + str(g_stored_counter) +
                         " New Person In Total!")
            sys.exit(1)
        except urllib2.HTTPError as httperr:
            logging.error(str(httperr))
            logging.error(str(httperr.read()))
            logging.info("Stored " + str(g_stored_counter) +
                         " New Person In Total!")
            sys.exit(1)
        logging.info("uid = %s " % uid)
        try:
            u = client.get.users__show(uid=uid)
        except weibo.APIError as apierr:
            logging.error(str(apierr))
        except urllib2.HTTPError as httperr:
            logging.error(str(httperr))
            logging.error(str(httperr.read()))
            logging.info("Stored " + str(g_stored_counter) +
                         " New Person In Total!")
            sys.exit(1)
        #logging.info(str(u))
        logging.info("We are uing API from account: [uid = %s, name = %s]" %
                     (u.id, u.screen_name))
    return client
コード例 #5
0
def getClient(access_token,expires_in):
    appkey='3541987275'
    appsecret='9e2cca6d2f735a7ebee4999ac6608231'
    redirecturl='http://0.0.0.0:8080/redirecturl'
    client=weibo.APIClient(app_key=appkey,app_secret=appsecret,redirect_uri=redirecturl)
    try:
        client.set_access_token(access_token,expires_in)
        return client
    except:
        web.seeother("https://api.weibo.com/oauth2/authorize?client_id=3541987275&redirect_uri=http://0.0.0.0:8080/redirecturl&response_type=code")
コード例 #6
0
ファイル: weibo_limit.py プロジェクト: ginking/weibo
def do_auth():
    logging = Logging.get_logger('do_auth')
    client = weibo.APIClient(app_key=APP_KEY,
                             app_secret=APP_SECRET,
                             redirect_uri=CALLBACK_URL)
    code = raw_input('input code you got:')
    r = client.request_access_token(code)
    access_token = r.access_token
    logging.info(access_token)
    expires_in = r.expires_in
    client.set_access_token(access_token, expires_in)
    print client.get.account__rate_limit_status()
コード例 #7
0
ファイル: wcMsgProc.py プロジェクト: vohoaiviet/WechatPy
    def sendToWeibo(self, msg):

        client = weibo.APIClient(
            WEIBO_APPKEY,
            WEIBO_APPSEC,
            # modify it.
            WEIBO_USER,
            WEIBO_PASS)
        try:
            r = client.post.statuses__update(source=WEIBO_APPKEY, status=msg)
            return '发出去啦!'
        except:
            return '发送失败!'
コード例 #8
0
def main():

    APP_KEY = '2260324575'  ## 填写应用程序的信息
    APP_SECRET = 'fb8ec84988227c4cb6fd6b4f5091b7a1'
    CALLBACK_URL = 'http://vpiao.wiseweb.com.cn/authformweibo'
    #APP_KEY = '1851011061' ## 填写应用程序的信息
    #APP_SECRET = '4f46048f5c6d1bb1038a0b379bda30b8'
    #CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
    #没有验证码的 5606463752
    #username = '******'
    #password = '******'
    #有验证码的
    #username = '******'
    #password = '******'
    #需要授权的 爱闹的守候 5770961845
    username = '******'
    password = '******'
    driver = webdriver.Firefox()
    code = getCode(driver, APP_KEY, CALLBACK_URL, username, password)
    time.sleep(2)
    response = getAccessToken(code, APP_KEY, APP_SECRET, CALLBACK_URL)

    access_token = response['access_token']
    expires_in = float(response['expires_in'])
    print access_token
    print expires_in

    client = weibo.APIClient(app_key=APP_KEY,
                             app_secret=APP_SECRET,
                             redirect_uri=CALLBACK_URL)
    client.set_access_token(access_token, expires_in)

    print('-----------')
    #http://open.weibo.com/wiki/2/statuses/share
    #第三方分享一条链接到微博
    #sendweibo = sendWeibo(client, '支持豌豆荚','http://www.wandoujia.com/apps/com.eico.weico ')
    #print sendweibo

    print('-----------')
    #http://open.weibo.com/wiki/2/comments/create
    #对一条微博进行评论

    #commentweibo = commentWeibo(client, '支持豌豆荚', 4148645941125493)
    #print(commentweibo)

    print('-----------')
    #http://open.weibo.com/wiki/2/statuses/user_timeline
    ## 获取某个用户最新发表的微博列表
    getweibocontent = getWeiboContent(client, 5770961845)
    print getweibocontent
コード例 #9
0
ファイル: code.py プロジェクト: SinaAApay/data
def getAccesstokenAndSoOn(code):
    #print code
    appkey='3541987275'
    appsecret='9e2cca6d2f735a7ebee4999ac6608231'
    redirecturl='http://0.0.0.0:8080/redirecturl'
    client=weibo.APIClient(app_key=appkey,app_secret=appsecret,redirect_uri=redirecturl)
    r=client.request_access_token(str(code[u'code']))
    web.setcookie('uid',r.uid)
    web.setcookie('access_token',r.access_token)
    web.setcookie('expires_in',r.expires_in)
    client.set_access_token(r.access_token,r.expires_in)
    userinfor={}
    userinfor[u'uid']=r.uid
    userinfor[u'client']=client
    return userinfor
コード例 #10
0
ファイル: weibo_crawler.py プロジェクト: livan123/practice
def weibo():
    APP_KEY = "2282143806"
    APP_SECRET = "bae8982e5539f7426ef2f71f553b514e"
    CALLBACK_URL = "http://api.weibo.com/livan/default.html"
    AUTH_URL = "http://api.weibo.com/livan/default.html"
    USERID = "2577633693"
    PASSWD = "xujingboyy123"

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

    referer_url = client.get_authorize_url()
    print "referer url is: %s" % refer_url

    cookies = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener(cookies)
    urllib2.install_opener(opener)
    postdata = {
        "client_id":APP_KEY,
        "userId":USERID,
        "passwd":PASSWD,
        "isLoginSina":"0",
        "action":"submit",
        "response_type":"code",
    }

    headers = {
        "User-Agent":"",
        "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()
        pat = "code=(.*?)$"
        print(resp.geturl())
        code = input()
        print "code is : %s" % code
    except Exception, e:
        print e
コード例 #11
0
def authSina(code):
    client = weibo.APIClient(SinaAppKey, SinaAppSecret,
                             MoeWebsite + "/sinacallback")
    r = client.request_access_token(code)

    client.set_access_token(r.access_token, r.expires_in)
    ruid = client.account.get_uid.get()
    user_type = mc.get('user_type')
    mc.set('user_type', 'invalid')
    sinaData = WeiboAuth(access_token=r.access_token,
                         expires_in=r.expires_in,
                         source="sina",
                         user_type=user_type,
                         uid=ruid.uid)
    sinaData.save()
    return r.access_token, r.expires_in
コード例 #12
0
def run():
    # weibo模块的APIClient是进行授权、API操作的类,先定义一个该类对象,传入参数为APP_KEY, APP_SECRET, CALL_BACK
    client = weibo.APIClient(APP_KEY, APP_SECRET, CALLBACK_URL)
    # 获取该应用(APP_KEY是唯一的)提供给用户进行授权的url
    auth_url = client.get_authorize_url()
    # 打印出用户进行授权的url,将该url拷贝到浏览器中,服务器将会返回一个url,该url中包含一个code字段(如图1所示)
    print "auth_url : " + auth_url
    # 输入该code值(如图2所示)

    #code = raw_input("input the retured code : ")
    code = get_selenium_js_html(auth_url)
    print '呵呵哒 code已经出来了 %s ' % {code}
    # 通过该code获取access_token,r是返回的授权结果,具体参数参考官方文档:
    # http://open.weibo.com/wiki/Oauth2/access_token
    r = client.request_access_token(code)
    # 将access_token和expire_in设置到client对象
    client.set_access_token(r.access_token, r.expires_in)

    # 以上步骤就是授权的过程,现在的client就可以随意调用接口进行微博操作了,下面的代码就是用用户输入的内容发一条新微博

    reload(sys)
    sys.setdefaultencoding('utf8')

    while True:
        #print "Ready! Do you want to send a new weibo?(y/n)"
        #choice = raw_input()
        time.sleep(600)
        choice = 'y'
        if choice == 'y' or choice == 'Y':
            #content = raw_input('input the your new weibo content : ')
            spider = qiubai.Spider_QSBK()
            temStr = spider.start()
            content = '[糗事百科]%s 现在北京时间是:%s  ---自动发送 [黑线]' % (
                temStr, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            if len(content) > 140:
                content = content[0:139]
            if content:
                # 调用接口发一条新微薄,status参数就是微博内容
                client.statuses.update.post(status=content)
                print "Send succesfully!"
                #break
                continue
            else:
                print "Error! Empty content!"
        if choice == 'n' or choice == 'N':
            break
コード例 #13
0
def run():
    client = weibo.APIClient(APP_KEY, APP_SECRET, CALL_BACK)
    auth_url = client.get_authorize_url()
    print "auth_url : " + auth_url
    # code = " "
    code = raw_input("input the retured code : ")
    r = client.request_access_token(code)
    client.set_access_token(r.access_token, r.expires_in)
    poiFile = open("poi.txt", "r")
    poiResaultFile = open("checkInNum.txt", "a")
    cache = []
    for lines in poiFile:
        try:
            checkin_num = 0
            title = None
            lat_long = lines.strip("\n").split(",")
            longitude = lat_long[0]
            latitude = lat_long[1]
            poi_result = str(
                client.place.nearby.pois.get(lat=latitude, long=longitude))
            poi_list = eval(poi_result)
            poi_string = json.dumps(poi_list)
            poi_json = json.loads(poi_string)
            for i in range(0, len(poi_json["pois"])):
                if poi_json["pois"][i]["poiid"] in cache:
                    pass
                else:
                    poi_id = poi_json["pois"][i]["poiid"]
                    cache.append(poi_id)
                    checkin_result = str(
                        client.place.pois.show.get(poiid=poi_id))
                    checkin_list = eval(checkin_result)
                    checkin_string = json.dumps(checkin_list)
                    checkin_json = json.loads(checkin_string)
                    checkin_num = checkin_json["checkin_num"]  #签到数
                    lon = checkin_json["lon"]  #经度
                    lat = checkin_json["lat"]  #纬度
                    title = checkin_json["title"]  #地点名称
                    if checkin_num != 0 and title != None:
                        print lon, lat, checkin_num, title
                        poiResaultFile.write(lon, lat, checkin_num,
                                             title + "\n")
                        poiResaultFile.flush()
        except Exception, e:
            print str(e)
            pass
コード例 #14
0
ファイル: main.py プロジェクト: JeffWSJ/weibo_checkin_spider
def run():
    client = weibo.APIClient(APP_KEY, APP_SECRET, CALL_BACK)
    auth_url = client.get_authorize_url()
    print "auth_url : " + auth_url
    code = raw_input("input the retured code : ")
    r = client.request_access_token(code)
    client.set_access_token(r.access_token, r.expires_in)
    lat_long_file = open("poi.txt", "r")
    cache = []  #缓存以确保不重复
    for lines in lat_long_file:
        try:
            checkin_num = 0
            title = None
            lat_long = lines.strip("\n").split(",")
            longitude = lat_long[0]
            latitude = lat_long[1]
            poi_result = str(
                client.place.nearby.pois.get(lat=latitude,
                                             long=longitude))  #返回附近多个poi点的信息
            poi_list = eval(poi_result)
            poi_string = json.dumps(poi_list)
            poi_json = json.loads(poi_string)
            for i in range(0, len(poi_json["pois"])):  #把附近所有的poi点都遍历一遍
                if poi_json["pois"][i]["poiid"] in cache:
                    pass
                else:
                    poi_id = poi_json["pois"][i]["poiid"]
                    cache.append(poi_id)
                    checkin_result = str(
                        client.place.pois.show.get(poiid=poi_id))
                    checkin_list = eval(checkin_result)
                    checkin_string = json.dumps(checkin_list)
                    checkin_json = json.loads(checkin_string)
                    checkin_num = checkin_json["checkin_num"]  #签到数
                    lon = checkin_json["lon"]  #经度
                    lat = checkin_json["lat"]  #纬度
                    title = checkin_json["title"]  #地点名称
                    if checkin_num != 0 and title != None:
                        print "%s\t%s\t%s\t%s" % (lon, lat, checkin_num, title)
        except:
            print "ERROR!!!!"
コード例 #15
0
def SinaAuth():
    client = weibo.APIClient(APP_KEY, APP_SECRET, CALL_BACK)
    auth_url = client.get_authorize_url()
    print("auth_url:" + auth_url)
    code = raw_input("input the returned code:")
    r = client.request_access_token(code)
    client.set_access_token(r.access_token, r.expires_in)

    while True:
        print("ready! Do you want to send a new weibo?(y/n)")
        choice = raw_input()
        if choice == 'y' or choice == 'Y':
            content = raw_input('input the you new weibo content:')
            if content:
                client.statuses.update.post(status=content)
                print('send successfully!')
                break
            else:
                print('error! empty content')
        if choice == 'n' or choice == 'N':
            break
コード例 #16
0
def getWeiboAuthedApi(source, user_type):
    try:
        weiboData = WeiboAuth.objects.get(source=source, user_type=user_type)
    except Exception as e:
        log.info("no valid auth info for %s, %s found" % (source, user_type))
        raise e

    if source == 'sina':
        client = weibo.APIClient(SinaAppKey, SinaAppSecret,
                                 MoeWebsite + "/sinacallback")
        client.set_access_token(weiboData.access_token, weiboData.expires_in)

        return client

    if source == 'tencent':
        auth = qqweibo.OAuthHandler(TencentAppKey,
                                    TencentAppSecret,
                                    callback=MoeWebsite + '/tencentcallback')
        auth.setToken(weiboData.access_token, weiboData.access_token_secret)
        api = qqweibo.API(auth, parser=qqweibo.ModelParser())
        return api
コード例 #17
0
def post_weibo():
    api = weibo.APIClient(APP_KEY, MY_APP_SECRET)

    # #第一次获取的时候需要在命令行中输入浏览器后面的code,来获取access_token
    # authorize_url = api.get_authorize_url(REDIRECT_URL)
    #
    # print(authorize_url)
    #
    # webbrowser.open_new(authorize_url)
    #
    # code = raw_input()
    #
    # request = api.request_access_token(code, REDIRECT_URL)
    # access_token = request.access_token
    # expires_in = request.expires_in
    # print access_token
    # print request.expires_in
    access_token = "2.00xI_xjBWxeIcE0eafacecd8qSgGQD"
    expires_in = 1408561200
    api.set_access_token(access_token, expires_in)
    status = get_weibo_status()
    print api.statuses.update.post(status=status)
コード例 #18
0
ファイル: weibo_send_2.py プロジェクト: ginking/weibo
def do_auth(conn):
    logging = Logging.get_logger('do_auth')
    logging.info(" IN DO_AUTH()")
    client = weibo.APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()   
    #urllib2.Request(url)
    webbrowser.open(url)
    # verifier = input("Verifier: ").strip()
    verifier = get_code(conn)
    #client = weibo.APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    ret = client.request_access_token(verifier)
    access_token = ret.access_token 
    expires_in = ret.expires_in 
    print("access_token = %s    expires_in = %s " %( access_token, expires_in))

    client.set_access_token(access_token, expires_in)
    if not client.is_expires():
        try:
            uid = client.get.account__get_uid().uid
        except weibo.APIError as apierr:
            logging.error(str(apierr))
            sys.exit(1)
        except urllib2.HTTPError as httperr:
            logging.error(str(httperr))
            logging.error(str(httperr.read()))
            sys.exit(1)
        logging.info("uid = %s " % uid)
        try:
            u = client.get.users__show(uid=uid)
        except weibo.APIError as apierr:
            logging.error(str(apierr))
        except urllib2.HTTPError as httperr:
            logging.error(str(httperr))
            logging.error(str(httperr.read()))
            sys.exit(1)
        #logging.info(str(u))
        logging.info("We are uing API from account: [uid = %s, name = %s]" % (u.id, u.screen_name))
    return client
コード例 #19
0
def run():
    client = weibo.APIClient(APP_KEY, APP_SECRET, CALL_BACK)
    auth_url = client.get_authorize_url()
    print "auth_url : " + auth_url
    code = raw_input("input the retured code : ")
    r = client.request_access_token(code)
    client.set_access_token(r.access_token, r.expires_in)
    lat_long_file = open("poi.txt", "r")
    i = 0
    cache = []
    for i in range(303):
        try:
            checkin_num = 0
            title = None
            lat_long = lat_long_file.readline().strip("\n").split(",")
            longitude = lat_long[0]
            latitude = lat_long[1]
            poi_result = str(
                client.place.nearby.pois.get(lat=latitude, long=longitude))
            poi_list = eval(poi_result)
            poi_string = json.dumps(poi_list)
            poi_json = json.loads(poi_string)
            if poi_json["pois"][0]["poiid"] in cache:
                pass
            else:
                poi_id = poi_json["pois"][0]["poiid"]
                cache.append(poi_id)
                checkin_result = str(client.place.pois.show.get(poiid=poi_id))
                checkin_list = eval(checkin_result)
                checkin_string = json.dumps(checkin_list)
                checkin_json = json.loads(checkin_string)
                checkin_num = checkin_json["checkin_user_num"]
                title = checkin_json["title"]
                if checkin_num != 0 and title != None:
                    print "%s\t%s\t%s\t%s" % (longitude, latitude, checkin_num,
                                              title)
        except:
            pass
コード例 #20
0
ファイル: p_weibo_users_2.py プロジェクト: ginking/weibo
def do_auth(conn):
    logging = Logging.get_logger('do_auth')
    client = weibo.APIClient(app_key=APP_KEY,
                             app_secret=APP_SECRET,
                             redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()
    webbrowser.open(url)
    time.sleep(2)
    #command = "curl " + url
    #logging.info(command)
    #os.system(command)
    # verifier = input("Verifier: ").strip()
    # verifier = get_code(conn)
    #client = weibo.APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)

    codes = False
    while (False == codes):
        time.sleep(2)
        codes = get_codes(conn)

    verified_flag = False
    for c in codes:
        try:
            logging.info("Current code is: " + str(c))
            ret = client.request_access_token(c)
        except urllib2.HTTPError as httperr:
            logging.error(str(httperr))
            logging.error(
                " <<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>  Incorrect Verifier Code!  <<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>> "
            )
            continue
        else:
            logging.info(
                "----------=============--  Correct Verifier Code!  --================----------------"
            )
            verifier = c
            verified_flag = True
            break

    if (False == verified_flag):
        logging.error("There is no correct verifier code so far.")
        sys.exit(1)
    else:
        if not set_invalid(conn, verifier):
            logging.error(
                "Error Occured when set the invalid flag for verifier code")
            sys.exit(1)
        else:
            logging.info(
                "Set the invalid flag for verifier code successfully!")

    access_token = ret.access_token
    expires_in = ret.expires_in

    logging.info("access_token = %s    expires_in = %s " %
                 (access_token, expires_in))

    client.set_access_token(access_token, expires_in)
    while not client.is_expires():
        try:
            uid = client.get.account__get_uid().uid
        except weibo.APIError as apierr:
            logging.error(str(apierr))
            logging.info("So Far, ---> Stored " + str(g_stored_counter) +
                         " New Person In Total!")
            time.sleep(300)
        except urllib2.HTTPError as httperr:
            logging.error(str(httperr))
            logging.error(str(httperr.read()))
            logging.info("So Far, ---> Stored " + str(g_stored_counter) +
                         " New Person In Total!")
            time.sleep(300)
        else:
            break
        logging.info("uid = %s " % uid)
    while not client.is_expires():
        try:
            u = client.get.users__show(uid=uid)
        except weibo.APIError as apierr:
            logging.error(str(apierr))
            logging.info("So Far, ---> Stored New Person: " +
                         str(g_stored_counter) + "; Received Person: " +
                         str(g_person_received) + "; E => " + get_E())
            time.sleep(300)
        except urllib2.HTTPError as httperr:
            logging.error(str(httperr))
            logging.error(str(httperr.read()))
            logging.info("So Far, ---> Stored New Person: " +
                         str(g_stored_counter) + "; Received Person: " +
                         str(g_person_received) + "; E => " + get_E())
            time.sleep(300)
        else:
            logging.info(
                "We are uing API from account: [uid = %s, name = %s]" %
                (u.id, u.screen_name))
            break
    return client
コード例 #21
0
    userinfo = request.session['userinfo']
    name = userinfo['name']
    headimg = userinfo['headimg']
   
    exam = Exam_b.objects.get(id=eid)
    exam_options = exam.exam_option_set.all()
    exam_option = random.choice(exam_options)
    if request.method == 'POST':
        title = request.POST['title']
        print title 
    return render_to_response('exam_b_info.html',{'exam_option':exam_option,'exam':exam,'headimg':headimg,'name':name,'headimgs':headimgs,'names':names})

APP_KEY = '3469247574'
APP_SECRET = 'd57bddcba8867095446ae0477b512cf6'
CALLBACK_URL = 'http://www.b.com/index2'
client = weibo.APIClient(app_key=APP_KEY,app_secret=APP_SECRET,redirect_uri=CALLBACK_URL)

from django import http
def fa_wei(request):
    access_token = request.session['token'] 
    espires_in = request.session['espires']
    client.set_access_token(access_token,espires_in)
    
    #print request.session.get('k')
    if request.method == 'POST':
        fenxiang = request.POST['fenxiang']
        #print fenxiang
        img = request.POST['img']
        print 'img=',img
    fr = request.session['fr']
    for ff in fr:
コード例 #22
0
import os
import sys
import weibo
import webbrowser
import json
import time

APP_KEY = '3586469417'
MY_APP_SECRET = 'a5a5c8f8797979119e259d199012f046'
REDIRECT_URL = 'https://api.weibo.com/oauth2/default.html'

client = weibo.APIClient(APP_KEY, MY_APP_SECRET)

access_token = '2.00d_KLoDvW9iuD4f32be1132s9YmnC'
expires_in = 1527353899

client.set_access_token(access_token, expires_in)

client.statuses.update.post(status=u'tomorrow is annother day')
time.sleep(15)
client.statuses.update.post(status=u'to be or not to be')
time.sleep(15)
client.statuses.update.post(
    status=u'is it tough to make a decision like this?')

print "*************OK**********"
コード例 #23
0
def authSinaUrl():
    client = weibo.APIClient(SinaAppKey, SinaAppSecret,
                             MoeWebsite + "/sinacallback")
    return client.get_authorize_url()
コード例 #24
0
def get_weibo_client():
    app_key = Config.objects.get(kind=Config.KIND_APP_KEY).value
    app_secret = Config.objects.get(kind=Config.KIND_APP_SECRET).value
    call_back = Config.objects.get(kind=Config.KIND_CALLBACK).value
    client = weibo.APIClient(app_key, app_secret, call_back)
    return client
コード例 #25
0
ファイル: weiboTask.py プロジェクト: daiyunbin/Automation
def review(APP_KEY, APP_SECRET, CALLBACK_URL, comment, rid, platform):

    # add_account('18354254831', 'pp9999', APP_KEY, APP_SECRET, CALLBACK_URL, '微博')
    # time.sleep(100)

    # plat_from = '评论微博'
    # account_info = get_account(plat_from)
    # print account_info  #<type 'dict'>
    #
    #
    # username= account_info['data']['accountId']
    # password = account_info['data']['password']
    # print username
    # print password
    #
    #
    # #print type(account_info['data']['data'])
    # if type(account_info['data']['data']) == unicode:
    #     access_token = json.loads(account_info['data']['data'])['access_token']
    #     expires_in = json.loads(account_info['data']['data'])['expires_in']
    # elif type(account_info['data']['data']) == dict:
    #     access_token = account_info['data']['data']['access_token']
    #     expires_in = account_info['data']['data']['expires_in']
    #
    #
    # print access_token
    # print expires_in
    #
    #
    # r = requests.post('https://api.weibo.com/oauth2/get_token_info', data={'access_token': access_token})
    # #print type(r.text)  #<type 'unicode'>
    # #print type(r.content)   #<type 'str'>
    # current_expire_in = json.loads(r.text)['expire_in']
    # print '剩余时间为: %d'%current_expire_in
    #
    #
    # if current_expire_in < 10:#如果有效期小于五秒钟,更新token
    #     driver = webdriver.Firefox()
    #     time.sleep(10)
    #     code = getCode(driver, APP_KEY, CALLBACK_URL, username, password)
    #     print code
    #
    #     response_dirctory = getAccessToken(code, APP_KEY, APP_SECRET, CALLBACK_URL)
    #     print response_dirctory
    #     #print type(response_dirctory)   #<type 'dict'>
    #
    #     update_cookies(username, password, response_dirctory, plat_from)
    #     # print type(account_info['data']['data'])
    print '本次使用的评论微博信息为: '
    logger.info('本次使用的评论微博信息为: ')
    access_token, expires_in = getToken(APP_KEY, APP_SECRET, CALLBACK_URL,
                                        platform)

    client = weibo.APIClient(app_key=APP_KEY,
                             app_secret=APP_SECRET,
                             redirect_uri=CALLBACK_URL)
    client.set_access_token(access_token, expires_in)

    print('-----------')
    logger.info('-----------')
    #http://open.weibo.com/wiki/2/statuses/share
    #第三方分享一条链接到微博
    #sendweibo = sendWeibo(client, '支持豌豆荚','http://www.wandoujia.com/apps/com.eico.weico ')
    #print sendweibo

    print('-----------')
    logger.info('-----------')
    #http://open.weibo.com/wiki/2/comments/create
    #对一条微博进行评论

    commentweibo = commentWeibo(client, comment, rid)
    print commentweibo
    logger.info(commentweibo)
    print('-----------')
    logger.info('-----------')
    #http://open.weibo.com/wiki/2/statuses/user_timeline
    # # 获取某个用户最新发表的微博列表
    # getweibocontent = getWeiboContent(client, 5770961845)
    # print getweibocontent

    print('-----------')
    logger.info('-----------')
コード例 #26
0
 def initWBAPI(self, accessToken):
     
     client = weibo.APIClient()
     client.set_access_token(accessToken)
     return client
コード例 #27
0
 def __init__(self, appkey, appsecret, callback, token, expires_in):
     super(WeiboApi, self).__init__()
     self.client = weibo.APIClient(appkey, appsecret, callback)
     self.client.set_access_token(token, expires_in)
コード例 #28
0
Created on 2016��3��12��

@author: daniel
'''
import sys
import weibo
import webbrowser
import urllib, httplib
import urllib2
import MySQLdb
#获得新浪微博授权api
APP_KEY = '1010823506'
MY_APP_SECRET = '7bbb4decac9dfbad905a190f663ce989'
REDIRECT_URL = 'http://www.sina.com.cn/'
api = weibo.APIClient(app_key=APP_KEY,
                      app_secret=MY_APP_SECRET,
                      redirect_uri=REDIRECT_URL)
authorize_url = api.get_authorize_url()
webbrowser.open_new(authorize_url)
code = raw_input("input the code: ").strip()
print "111"
request = api.request_access_token(code, REDIRECT_URL)
access_token = request.access_token
expires_in = request.expires_in
api.set_access_token(access_token, expires_in)
#连接数据库获得用户昵称
conn = MySQLdb.connect(host="115.29.55.54",
                       port=3306,
                       user="******",
                       passwd="chen724467110",
                       db="b5test",
コード例 #29
0
# See: https://github.com/tornadoweb/tornado/blob/branch2.1/tornado/database.py#L50
_orig_reconnect = tornado.database.Connection.reconnect


def _reconnect(self):
    self._db_args['init_command'] = 'SET time_zone = "+8:00"'
    return _orig_reconnect(self)


tornado.database.Connection.reconnect = _reconnect

APP_KEY = '2426835332'
APP_SECRET = '594f4a061b1a481ce4e030fbd88681f9'

callback = 'http://xdictweb.sinaapp.com/login'
oauth = weibo.APIClient(APP_KEY, APP_SECRET, callback)


def _build_accesskey():
    return ''.join([random.choice(string.letters) for n in range(40)])


class BaseHandler(tornado.web.RequestHandler):
    @property
    def db(self):
        return tornado.database.Connection(
            #'localhost:3306', 'app_xdictweb', 'root', 'root'
            ':'.join([MYSQL_HOST, MYSQL_PORT]),
            MYSQL_DB,
            MYSQL_USER,
            MYSQL_PASS)
コード例 #30
0
 def setClient(self):
     self.api2 = weibo.APIClient(
         app_key=self.sinaweiboOauth['app_key'],
         app_secret=self.sinaweiboOauth['app_secret'],
         redirect_uri=self.sinaweiboOauth['redirect_uri'])