Exemplo n.º 1
0
Arquivo: api.py Projeto: non117/Boxnya
class Api():
    def __init__(self,  atoken="", atokensecret="", ckey="ZctjpCsuug2VtjfEuceg", 
                 csecret="pO9WL26Ia9rXyjNavXrit1iclCt1G2J1nRA4jZ6LGc"):
        self.oauth = OAuth(ckey, csecret, atoken, atokensecret)
        self.site = "https://api.twitter.com/"
    
    def initializer(self):
        ''' アクセストークン, シークレットを作る '''
        request_url = "https://twitter.com/oauth/request_token"
        auth_url = "https://twitter.com/oauth/authorize"
        accesstoken_url = "https://twitter.com/oauth/access_token"
        return self.oauth.oauth_initializer(request_url, auth_url, accesstoken_url)
    
    def execute(self, url, method, params={}, extra_header={}, extra_data=None):
        ''' twitterのリクエスト処理の実行 '''
        # パラメータを成形して辞書に
        for key, val in params.items():
            if isinstance(val, unicode): val = val.encode("utf-8")
            params[key] = urllib.quote(str(val), "")
        # gzip圧縮されたレスポンスを受け取る
        extra_header.update({"Accept-Encoding": "deflate, gzip"})
        request = self.oauth.base(url, method, params, extra_header, extra_data)
        try:
            response = urllib2.urlopen(request)
            if response.info().get('Content-Encoding') == 'gzip':
                buf = StringIO(response.read())
                f = gzip.GzipFile(fileobj=buf)
                data = f.read()
            else:
                data = response.read()
            return parse(data)
        except urllib2.URLError:
            return False

    def timeline(self):
        url = self.site + "1.1/statuses/home_timeline.json"
        return self.execute(url,"GET")

    def user_timeline(self, count=20, screen_name=""):
        url = self.site + "1.1/statuses/user_timeline.json"
        return self.execute(url, "GET", {"count":count, "screen_name":screen_name})

    def update(self, status):
        url = self.site + "1.1/statuses/update.json"
        return self.execute(url,"POST", {"status":status})
    
    def favorite(self, status_id):
        url = self.site + "1.1/favorites/create.json"
        return self.execute(url, "POST", {"id":str(status_id)})
    
    def upload_icon(self, filename):
        url = self.site + "1/account/update_profile_image.json"
        filetype = mimetypes.guess_type(filename)[0]
        BOUNDARY = 'B0xNyA'
        body = []
        body.append('--' + BOUNDARY)
        body.append('Content-Disposition: form-data; name="image"; filename="%s"' % filename)
        body.append('Content-Type: %s' % filetype)
        body.append('')
        with open(filename, 'rb') as f:
            body.append(f.read())
        body.append('--%s--' % BOUNDARY)
        body.append('')
        body = '\r\n'.join(body)
        headers = {'Content-Type': 'multipart/form-data; boundary=%s' % BOUNDARY,
                   'Content-Length': len(body)}
        return self.execute(url, "POST", extra_header=headers, extra_data=body)
    
    def userstream(self, callback_func, rawdata=False):
        
        url = 'https://userstream.twitter.com/2/user.json'
        req = self.oauth.base(url, "GET")
        response = urllib2.urlopen(req)
        response.readline()
        response.readline()
        while True:
            try:
                rawstr = response.readline()
            except urllib2.URLError:
                rawstr = ''
            if rawstr == '':
                response.close()
                response = urllib2.urlopen(self.oauth.base(url, "GET"))
                continue
            else:
                if rawdata:
                    callback_func(rawstr)
                callback_func(parse(rawstr))
Exemplo n.º 2
0
Arquivo: api.py Projeto: non117/Boxnya
 def __init__(self,  atoken="", atokensecret="", ckey="ZctjpCsuug2VtjfEuceg", 
              csecret="pO9WL26Ia9rXyjNavXrit1iclCt1G2J1nRA4jZ6LGc"):
     self.oauth = OAuth(ckey, csecret, atoken, atokensecret)
     self.site = "https://api.twitter.com/"