示例#1
0
def callback():
    code = request.args.get('code', '')
    client = Client(APP_KEY, APP_SECRET, CALLBACK_URL)
    try:
        client.set_code(code)
        r = client.token_info
        uid = r['uid']
        access_token = r['access_token']
        expires_in = r['expires_in']
    except:
        flash(u'微博登录没有成功')
        return redirect(url_for('login'))

    try:
        userinfo = client.get('users/show', uid=uid)
        screen_name = userinfo["screen_name"]
        profile_image_url = userinfo["profile_image_url"]

        mongo.db.users.update({"uid": uid},
                              {"$set": {"uid": uid, "access_token": access_token,
                              "expires_in": expires_in, "screen_name": screen_name,
                              "profile_image_url": profile_image_url}}, upsert=True, safe=True)

        session['uid'] = uid
        session['screen_name'] = screen_name
        session["profile_image_url"] = profile_image_url
        return redirect(url_for('index'))
    except Exception:
        flash(u'获取用户微博信息没有成功')
        return redirect(url_for('login'))
def init():
    """
    Instantiates a client.

    Besides the developer's credentials, weibo always a requires live login before using weibo API 
    to prevent abusing. You can login with any plain weibo account.
    """
    # API_KEY = os.getenv('API_KEY')
    # API_SECRET = os.getenv('API_SECRET')
    # REDIRECT_URI = os.getenv('REDIRECT_URI')
    try:
        client = Client(API_KEY, API_SECRET, REDIRECT_URI)
    except:
        print("Invalid API Credentials...")
    while True:  # check if authorization succeeds, if not, try again
        try:
            webbrowser.open_new(client.authorize_url)
            print("Please authorize... \nIf your browser does not open automatically,"\
                "please paste this URL to your browser manually: {}".format(client.authorize_url))
            client.set_code(input("Input your code:\n"))
            break
        except:
            try_again = input(
                "Authorization failed... Input Y to try again...\n")
            if try_again != 'y' and try_again != 'Y':
                break

    return Client(API_KEY, API_SECRET, REDIRECT_URI, client.token)
    def authorize_app(self, app_data = APP_DATA):
        '''
        authorize the app
        return the client for invoding weibo api
        must be invoked after the login function
        '''
        c = Client(*app_data)
        self.driver.get(c.authorize_url)
        try:
            WebDriverWait(self.driver, 10).until(
                    lambda x: x.find_element_by_css_selector('div.oauth_login_submit')
                    )
            # logging.info driver.pagself.e_source
            submit_button = self.driver.find_element_by_css_selector('p.oauth_formbtn').find_element_by_tag_name('a')

            submit_button.click()
        except TimeoutException:
            # there is no submit button, so the user may have authorized the app
            logging.info('the user has authorized the app')

        # parse the code
        # logging.info driver.current_url
        query_str = urllib.parse.urlparse(self.driver.current_url).query
        code = urllib.parse.parse_qs(query_str)['code']

        c.set_code(code)
        logging.info('authorize the app success! code, {}'.format(code))
        return c
    def authorize_app(self, app_data=APP_DATA):
        """
        authorize the app
        return the client for invoding weibo api
        must be invoked after the login function
        """
        c = Client(*app_data)
        self.driver.get(c.authorize_url)
        try:
            WebDriverWait(self.driver, 10).until(lambda x: x.find_element_by_css_selector("div.oauth_login_submit"))
            # logging.info driver.pagself.e_source
            submit_button = self.driver.find_element_by_css_selector("p.oauth_formbtn").find_element_by_tag_name("a")

            submit_button.click()
        except TimeoutException:
            # there is no submit button, so the user may have authorized the app
            logging.info("the user has authorized the app")

        # parse the code
        # logging.info driver.current_url
        query_str = urllib.parse.urlparse(self.driver.current_url).query
        code = urllib.parse.parse_qs(query_str)["code"]

        c.set_code(code)
        logging.info("authorize the app success! code, {}".format(code))
        return c
示例#5
0
    def get(self):
        code = self.get_argument('code')
        key, secret = self.get_app()
        client = Client(api_key=key, api_secret=secret,
                        redirect_uri=self.callback_url)

        client.set_code(code)

        result = client.token
        self.set_auth(result)
        return self.redirect('/utility/sina/exec/')
示例#6
0
class Wayterm(object):
    def __init__(self):
        self.app_key = '1746312660'
        self.app_secret = 'a113b12f49266b12125f6df1f9808045'
        self.callback_url = 'http://wayterm.nerocrux.org/done'
        self.template = Template()
        self.url = Url()
        self.reader = Reader()
        self.token = {}

        if self._read_access_token():
            self.client = Client(self.app_key, self.app_secret, self.callback_url, self.token)
        else:
            self.client = Client(self.app_key, self.app_secret, self.callback_url)
            self.auth_url = self.url.shorten(self.client.authorize_url)
            print '[1] Open this url in your browser: ' + self.auth_url
            self.auth_code = raw_input('[2] Enter authorization code: ')
            self.client.set_code(self.auth_code)
            token = {
                'access_token':self.client.token['access_token'],
                'expires_at':self.client.token['expires_at'],
                'uid':self.client.token['uid'],
            }
            self._write_access_token(token)
            print 'Authorization done. Enjoy!'


    def _read_access_token(self):
        try:
            self.token = yaml.load(open(os.path.join(os.getenv('HOME'), '.wayterm.yaml')).read())
        except:
            return False
        return True


    def _write_access_token(self, token):
        stream = file(os.path.join(os.getenv('HOME'), '.wayterm.yaml'), 'w')
        yaml.dump(token, stream)


    def _init_print(self):
        self.reader.printfile('logo')


    def call(self, command):
        if command[0].lower() == 'exit':
            exit()
        if command[0].lower() == 'help':
            self.reader.printfile('help')
            return
        api = Api(self.client)
        api.call(command)
示例#7
0
文件: test.py 项目: Heipiao/weibo
from weibo import Client
from pprint import pprint
from time import clock
import json

APP_KEY = "3722673574"
APP_SECTER = "3686fea0a65da883b6c2a7586f350425"
CALLBACK_URL = 'http://siliang.org'
code = "004ba6f4d40736d7aff25f4203d46f73"

c = Client(APP_KEY, APP_SECTER , CALLBACK_URL)
# url = c.authorize_url
# webbrowser.open_new(url)
c.set_code('code')
token = c.token
c = Client(APP_KEY, APP_SECTER , CALLBACK_URL,token)

#pprint(raw_data['statuses'][1]['text'])

a = []
raw_data  = c.get('statuses/public_timeline', count=200)
for x in range(200):
    a = a.append(str(raw_data['statuses'][x]['text']))

print (a)
# author: [email protected]
# reference: [doc of third-party weibo sdk](http://weibo.lxyu.net/)
from weibo import Client
from config.Weibo_API_Config import *
from idTranslation import mid2id, id2mid

client = Client(API_KEY, API_SECRET, REDIRECT_URI)
print("please paste the URL to your browser"+client.authorize_url+", and authorize")
client.set_code(input("input your code:"))

userMsg = client.get('users/show', uid=2146965345)
print(type(userMsg), userMsg)
print("************************************************")

comments = client.get('comments/show', id=4545555559354630, count=5)["comments"]
# print(type(comments), comments)

for comment in comments:
    print(comment["text"])
示例#9
0
import sys
from weibo import Client

## 微连接 移动应用 申请
API_KEY = "xxxxx"
API_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxx"
REDIRECT_URI = "https://api.weibo.com/oauth2/default.html"
c = Client(API_KEY, API_SECRET, REDIRECT_URI)

# 通过手动操作,访问 authorize_url 得到 access或者authorize code
url = c.authorize_url
print(url)
code = input()
c.set_code(code)

out = open("res.txt", 'w', encoding="utf8")

## 获取公共微博
d = c.get('statuses/public_timeline', count=200)

for i in range(len(d['statuses'])):
    cc = d['statuses'][i]['text'].strip()
    cc = cc.replace('\u200b', '').replace('\n', '    ').strip()
    out.write(cc + '\n')
示例#10
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from weibo import Client
import webbrowser, json
import demjson

APP_KEY = '415390189'
APP_SECRET = '958ea2c93dcad4ab45a99098b44b016a'
REDIRECT_URI = 'https://api.weibo.com/oauth2/authorize'
client = Client(APP_KEY, APP_SECRET, REDIRECT_URI)
url = client.authorize_url
'https://api.weibo.com/oauth2/authorize?client_id=415390189&response_type=code&redirect_uri=958ea2c93dcad4ab45a99098b44b016a'
print (url)
webbrowser.open_new(url)
print ('输入url中code后面的内容后按回车键:')
code = raw_input()
client.set_code(code)
token = client.token
uuid = client.uid
d = json.dumps(client.get('statuses/user_timeline', uid=uuid, separators=(',', ':')))
print (d)
s = json.loads(d)
length = len(s['statuses'])
print (length)
for i in range(0,length):
    print (s['statuses'][i]['text'])
示例#11
0
from weibo import Client
from datetime import datetime

API_KEY = '308244242'
API_SECRET = '4532eb6062e29c14707cc8527bc9ec4f'
REDIRECT_URI = 'http://tools.iadright.com'

c = Client(API_KEY, API_SECRET, REDIRECT_URI)
print(c.authorize_url)
c.set_code(input('Please input token:'))
print(c.token)