예제 #1
0
 def update_profile_background_image(self, filename, *args, **kargs):
     headers, post_data = API._pack_image(filename, 800)
     bind_api(path='/account/update_profile_background_image.json',
              method='POST',
              payload_type='user',
              allowed_param=['tile'],
              require_auth=True)(self, post_data=post_data, headers=headers)
예제 #2
0
 def test(self):
     try:
         bind_api(
             path = '/help/test.json',
         )(self)
     except WeibopError:
         return False
     return True
예제 #3
0
 def exists_block(self, *args, **kargs):
     try:
         bind_api(path='/blocks/exists.json',
                  allowed_param=['id', 'user_id', 'screen_name'],
                  require_auth=True)(self, *args, **kargs)
     except TweepError:
         return False
     return True
예제 #4
0
파일: api.py 프로젝트: DonghoChoi/Socrates
 def update_profile_banner(self, filename, *args, **kargs):
     headers, post_data = API._pack_image(filename, 700, form_field="banner")
     bind_api(
         path = '/account/update_profile_banner.json',
         method = 'POST',
         allowed_param = ['width', 'height', 'offset_left', 'offset_right'],
         require_auth = True
     )(self, post_data=post_data, headers=headers)
예제 #5
0
파일: api.py 프로젝트: UniIsland/citypk
 def test(self):
     try:
         bind_api(
             path = '/help/test.json',
         )(self)
     except WeibopError:
         return False
     return True
예제 #6
0
파일: api.py 프로젝트: openMinix/Yocto
 def update_profile_image(self, filename):
     headers, post_data = API._pack_image(filename, 700)
     bind_api(
         path = '/account/update_profile_image.json',
         method = 'POST',
         parser = parse_none,
         require_auth = True
     )(self, post_data=post_data, headers=headers)
예제 #7
0
파일: api.py 프로젝트: UniIsland/citypk
 def update_profile_background_image(self, filename, *args, **kargs):
     headers, post_data = API._pack_image(filename, 800)
     bind_api(
         path = '/account/update_profile_background_image.json',
         method = 'POST',
         payload_type = 'user',
         allowed_param = ['tile'],
         require_auth = True
     )(self, post_data=post_data, headers=headers)
예제 #8
0
파일: api.py 프로젝트: UniIsland/citypk
 def exists_block(self, *args, **kargs):
     try:
         bind_api(
             path = '/blocks/exists.json',
             allowed_param = ['id', 'user_id', 'screen_name'],
             require_auth = True
         )(self, *args, **kargs)
     except WeibopError:
         return False
     return True
예제 #9
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def followers_ids(self):
     """Get list of IDs of users following the specified user"""
     return bind_api(
         path = '/followers/ids.json',
         parser = parse_ids,
         allowed_param = ['id', 'user_id', 'screen_name', 'page']
     )
예제 #10
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def exists_friendship(self):
     """Check if friendship exists"""
     return bind_api(
         path = '/friendships/exists.json',
         parser = parse_bool,
         allowed_param = ['user_a', 'user_b']
     )
예제 #11
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def friends(self):
     """Show friends"""
     return bind_api(
         path = '/statuses/friends.json',
         parser = parse_users,
         allowed_param = ['id', 'user_id', 'screen_name', 'page']
     )
예제 #12
0
파일: api.py 프로젝트: openMinix/Yocto
 def trends_weekly(self, *args, **kargs):
     return bind_api(
         host = "search." + self.host,
         path = '/trends/weekly.json',
         parser = parse_json,
         allowed_param = ['date', 'exclude']
     )(self, *args, **kargs)
예제 #13
0
    def upload(self, filename, status, lat=None, long=None, source=None):
        if source is None:
            source=self.source
        headers, post_data = API._pack_image(filename, 1024, source=source, status=status, lat=lat, long=long, contentname="pic")
        args = [status]
        allowed_param = ['status']
        
        if lat is not None:
            args.append(lat)
            allowed_param.append('lat')
        
        if long is not None:
            args.append(long)
            allowed_param.append('long')
        
        if source is not None:
            args.append(source)
            allowed_param.append('source')
        kargs={
               'post_data': post_data,
               'headers': headers,
               }    
        return bind_api(
            path = '/statuses/upload.json',            
            method = 'POST',
            payload_type = 'status',
            require_auth = True,
            allowed_param = allowed_param            
#        )(self, *args, post_data=post_data, headers=headers)
         )(self, *args, **kargs)
예제 #14
0
파일: api.py 프로젝트: openMinix/Yocto
 def search(self, *args, **kargs):
     return bind_api(
         host = 'search.' + self.host,
         path = '/search.json',
         parser = parse_search_results,
         allowed_param = ['q', 'lang', 'locale', 'rpp', 'page', 'since_id', 'geocode', 'show_user'],
     )(self, *args, **kargs)
예제 #15
0
파일: api.py 프로젝트: openMinix/Yocto
 def retweets(self, id, *args, **kargs):
     return bind_api(
         path = '/statuses/retweets/%s.json' % id,
         parser = parse_retweets,
         allowed_param = ['count'],
         require_auth = True
     )(self, *args, **kargs)
예제 #16
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def public_timeline(self):
     """Return the public timeline"""
     return bind_api(
         path = '/statuses/public_timeline.json',
         parser = parse_statuses,
         allowed_param = []
     )
예제 #17
0
 def destroy_list(self, slug):
     return bind_api(
         path = '/%s/lists/%s.json' % (self.auth.get_username(), slug),
         method = 'DELETE',
         payload_type = 'list',
         require_auth = True
     )(self)
예제 #18
0
    def _t_add_pic(self,
                   filename,
                   content,
                   clientip='127.0.0.1',
                   jing=None,
                   wei=None):
        headers, post_data = API._pack_image(
            filename,
            contentname="pic",
            content=content,
            clientip=clientip,
            jing=jing,
            wei=wei,
        )
        args = [content, clientip]
        allowed_param = ['content', 'clientip']

        if jing is not None:
            args.append(jing)
            allowed_param.append('jing')

        if wei is not None:
            args.append(wei)
            allowed_param.append('wei')

        return bind_api(path='/t/add_pic',
                        method='POST',
                        payload_type='retid',
                        require_auth=True,
                        allowed_param=allowed_param)(self,
                                                     *args,
                                                     post_data=post_data,
                                                     headers=headers)
예제 #19
0
파일: api.py 프로젝트: openMinix/Yocto
 def trends_current(self, *args, **kargs):
     return bind_api(
         host = 'search.' + self.host,
         path = '/trends/current.json',
         parser = parse_json,
         allowed_param = ['exclude']
     )(self, *args, **kargs)
예제 #20
0
    def upload_result(self, contents, status, contenttype,lat=None, long=None, source=None):
        if source is None:
            source=self.source
        headers, post_data = API._pack_result_image(contents, 1024, source=source, status=status, lat=lat, long=long, contentname="pic", contenttype=contenttype)
        args = [status]
        allowed_param = ['status']

        if lat is not None:
            args.append(lat)
            allowed_param.append('lat')

        if long is not None:
            args.append(long)
            allowed_param.append('long')

        if source is not None:
            args.append(source)
            allowed_param.append('source')

        return bind_api(
            path = '/statuses/upload.json',
            method = 'POST',
            payload_type = 'status',
            require_auth = True,
            allowed_param = allowed_param
        )(self, *args, post_data=post_data, headers=headers)
예제 #21
0
 def update_list(self, slug, *args, **kargs):
     return bind_api(path='/%s/lists/%s.json' %
                     (self.auth.get_username(), slug),
                     method='POST',
                     payload_type='list',
                     allowed_param=['name', 'mode', 'description'],
                     require_auth=True)(self, *args, **kargs)
예제 #22
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def get_status(self):
     """Show status"""
     return bind_api(
         path = '/statuses/show.json',
         parser = parse_status,
         allowed_param = ['id']
     )
예제 #23
0
 def remove_list_member(self, slug, *args, **kargs):
     return bind_api(path='/%s/%s/members.json' %
                     (self.auth.get_username(), slug),
                     method='DELETE',
                     payload_type='list',
                     allowed_param=['id'],
                     require_auth=True)(self, *args, **kargs)
예제 #24
0
파일: api.py 프로젝트: UniIsland/citypk
 def is_list_member(self, owner, slug, user_id):
     try:
         return bind_api(path='/%s/%s/members/%s.json' %
                         (owner, slug, user_id),
                         payload_type='user')(self)
     except WeibopError:
         return False
예제 #25
0
 def is_subscribed_list(self, owner, slug, user_id):
     try:
         return bind_api(path='/%s/%s/subscribers/%s.json' %
                         (owner, slug, user_id),
                         payload_type='user')(self)
     except TweepError:
         return False
예제 #26
0
파일: api.py 프로젝트: UniIsland/citypk
    def upload(self, filename, status, lat=None, long=None, source=None):
        if source is None:
            source=self.source
        headers, post_data = API._pack_image(filename, 1024, source=source, status=status, lat=lat, long=long, contentname="pic")
        args = [status]
        allowed_param = ['status']
        
        if lat is not None:
            args.append(lat)
            allowed_param.append('lat')
        
        if long is not None:
            args.append(long)
            allowed_param.append('long')
        
        if source is not None:
            args.append(source)
            allowed_param.append('source')
        kargs={
               'post_data': post_data,
               'headers': headers,
               }    
        return bind_api(
            path = '/statuses/upload.json',            
            method = 'POST',
            payload_type = 'status',
            require_auth = True,
            allowed_param = allowed_param            
#        )(self, *args, post_data=post_data, headers=headers)
         )(self, *args, **kargs)
예제 #27
0
파일: api.py 프로젝트: UniIsland/citypk
 def destroy_list(self, slug):
     return bind_api(
         path = '/%s/lists/%s.json' % (self.auth.get_username(), slug),
         method = 'DELETE',
         payload_type = 'list',
         require_auth = True
     )(self)
예제 #28
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def get_user(self):
     """Show user"""
     return bind_api(
         path = '/users/show.json',
         parser = parse_user,
         allowed_param = ['id', 'user_id', 'screen_name']
     )
예제 #29
0
 def verify_credentials(self):
     try:
         return bind_api(path='/account/verify_credentials.json',
                         payload_type='user',
                         require_auth=True)(self)
     except TweepError:
         return False
예제 #30
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def user_timeline(self):
     """Get user timeline"""
     return bind_api(
         path = '/statuses/user_timeline.json',
         parser = parse_statuses,
         allowed_param = ['id', 'user_id', 'screen_name', 'since_id',
                          'max_id', 'count', 'page']
     )
예제 #31
0
 def is_list_member(self, owner, slug, user_id):
     try:
         return bind_api(
             path = '/%s/%s/members/%s.json' % (owner, slug, user_id),
             payload_type = 'user'
         )(self)
     except TweepError:
         return False
예제 #32
0
 def update_profile_image(self, filename):
     headers, post_data = API._pack_image(filename, 700)
     return bind_api(path='/account/update_profile_image.json',
                     method='POST',
                     payload_type='user',
                     require_auth=True)(self,
                                        post_data=post_data,
                                        headers=headers)
예제 #33
0
파일: api.py 프로젝트: UniIsland/citypk
 def is_subscribed_list(self, owner, slug, user_id):
     try:
         return bind_api(
             path = '/%s/%s/subscribers/%s.json' % (owner, slug, user_id),
             payload_type = 'user'
         )(self)
     except WeibopError:
         return False
예제 #34
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def mentions(self):
     """Get mentions"""
     return bind_api(
         path = '/statuses/mentions.json',
         parser = parse_statuses,
         allowed_param = ['since_id', 'max_id', 'count', 'page'],
         require_auth = True
     )
예제 #35
0
파일: api.py 프로젝트: UniIsland/citypk
 def update_list(self, slug, *args, **kargs):
     return bind_api(
         path = '/%s/lists/%s.json' % (self.auth.get_username(), slug),
         method = 'POST',
         payload_type = 'list',
         allowed_param = ['name', 'mode', 'description'],
         require_auth = True
     )(self, *args, **kargs)
예제 #36
0
파일: api.py 프로젝트: UniIsland/citypk
 def remove_list_member(self, slug, *args, **kargs):
     return bind_api(
         path = '/%s/%s/members.json' % (self.auth.get_username(), slug),
         method = 'DELETE',
         payload_type = 'list',
         allowed_param = ['id'],
         require_auth = True
     )(self, *args, **kargs)
예제 #37
0
파일: api.py 프로젝트: openMinix/Yocto
 def test(self):
     try:
         return bind_api(
             path = '/help/test.json',
             parser = parse_return_true
         )(self)
     except TweepError:
         return False
예제 #38
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def sent_direct_messages(self):
     """Sent direct messages"""
     return bind_api(
         path = '/direct_messages/sent.json',
         parser = parse_directmessages,
         allowed_param = ['since_id', 'max_id', 'count', 'page'],
         require_auth = True
     )
예제 #39
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def followers(self):
     """Show followers"""
     return bind_api(
         path = '/statuses/followers.json',
         parser = parse_users,
         allowed_param = ['id', 'user_id', 'screen_name', 'page']
         require_auth = True
     )
예제 #40
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def show_friendship(self):
     """Show friendship details"""
     return bind_api(
         path = '/friendships/show.json',
         parser = parse_friendship,
         allowed_param = ['source_id', 'source_screen_name',
                          'target_id', 'target_screen_name']
     )
예제 #41
0
파일: api.py 프로젝트: UniIsland/citypk
 def update_profile_image(self, filename):
     headers, post_data = API._pack_image(filename=filename, max_size=700, source=self.source)
     return bind_api(
         path = '/account/update_profile_image.json',
         method = 'POST',
         payload_type = 'user',
         require_auth = True
     )(self, post_data=post_data, headers=headers)
예제 #42
0
파일: api.py 프로젝트: kojicomics/gnuspy
 def home_timeline(self):
     """Return the friends timeline"""
     return bind_api(
         path = '/statuses/home_timeline.json',
         parser = parse_statuses,
         allowed_param = ['since_id', 'max_id', 'count', 'page'],
         require_auth = True
     )
예제 #43
0
 def end_session(self):
     try:
         return bind_api(
             path = '/account/end_session.json',
             method = 'POST',
             payload_type = 'user',
             require_auth = True
         )(self)
     except WeibopError:
         return False
예제 #44
0
    def _user_update_head(self, filename):
        headers, post_data = API._pack_image(filename, "pic")
        args = []
        allowed_param = []

        return bind_api(path='/user/update_head',
                        method='POST',
                        require_auth=True,
                        allowed_param=allowed_param)(self,
                                                     *args,
                                                     post_data=post_data,
                                                     headers=headers)
예제 #45
0
class API(object):
    """Weibo API"""

    # TODO: remove unsupported params
    def __init__(self,
                 auth_handler=None,
                 retry_count=0,
                 host='open.t.qq.com',
                 api_root='/api',
                 cache=None,
                 secure=False,
                 retry_delay=0,
                 retry_errors=None,
                 source=None,
                 parser=None,
                 log=None):
        self.auth = auth_handler
        self.host = host
        self.api_root = api_root
        self.cache = cache
        self.secure = secure
        self.retry_count = retry_count
        self.retry_delay = retry_delay
        self.retry_errors = retry_errors
        self.parser = parser or ModelParser()
        self.log = log

        self._build_api_path()

    ## 时间线 ##
    """ 1.Statuses/home_timeline 主页时间线 """
    # BUG: type, contenttype, accesslevel is useless
    _statuses_home_timeline = bind_api(path='/statuses/home_timeline',
                                       payload_type='tweet',
                                       payload_list=True,
                                       allowed_param=[
                                           'reqnum', 'pageflag', 'pagetime',
                                           'type', 'contenttype'
                                       ],
                                       require_auth=True)
    """ 2.Statuses/public_timeline 广播大厅时间线"""
    _statuses_public_timeline = bind_api(path='/statuses/public_timeline',
                                         payload_type='tweet',
                                         payload_list=True,
                                         allowed_param=['reqnum', 'pos'],
                                         require_auth=True)
    """ 3.Statuses/user_timeline 其他用户发表时间线"""
    _statuses_user_timeline = bind_api(path='/statuses/user_timeline',
                                       payload_type='tweet',
                                       payload_list=True,
                                       allowed_param=[
                                           'name', 'reqnum', 'pageflag',
                                           'pagetime', 'lastid', 'type',
                                           'contenttype'
                                       ],
                                       require_auth=True)
    """ 4.Statuses/mentions_timeline @提到我的时间线 """
    _statuses_mentions_timeline = bind_api(path='/statuses/mentions_timeline',
                                           payload_type='tweet',
                                           payload_list=True,
                                           allowed_param=[
                                               'reqnum', 'pageflag',
                                               'pagetime', 'lastid', 'type',
                                               'contenttype', 'accesslevel'
                                           ],
                                           require_auth=True)
    """ 5.Statuses/ht_timeline 话题时间线 """
    _statuses_ht_timeline = bind_api(
        path='/statuses/ht_timeline',
        payload_type='tweet',
        payload_list=True,
        allowed_param=['httext', 'reqnum', 'pageflag', 'pageinfo'],
        require_auth=True)
    """ 6.Statuses/broadcast_timeline 我发表时间线 """
    _statuses_broadcast_timeline = bind_api(
        path='/statuses/broadcast_timeline',
        payload_type='tweet',
        payload_list=True,
        allowed_param=[
            'reqnum', 'pageflag', 'pagetime', 'lastid', 'type', 'contenttype'
        ],
        require_auth=True)
    """ 7.Statuses/special_timeline 特别收听的人发表时间线 """
    _statuses_special_timeline = bind_api(
        path='/statuses/special_timeline',
        payload_type='tweet',
        payload_list=True,
        allowed_param=['reqnum', 'pageflag', 'pagetime'],
        require_auth=True)
    """ 8.Statuses/area_timeline 地区发表时间线 """
    # required: country, province, city
    _statuses_area_timeline = bind_api(
        path='/statuses/area_timeline',
        payload_type='tweet',
        payload_list=True,
        allowed_param=['country', 'province', 'city', 'reqnum', 'pos'],
        require_auth=True)
    """ 9.Statuses/home_timeline_ids 主页时间线索引 """
    _statuses_home_timeline_ids = bind_api(path='/statuses/home_timeline_ids',
                                           payload_type='retid',
                                           payload_list=True,
                                           allowed_param=[
                                               'reqnum', 'pageflag',
                                               'pagetime', 'type',
                                               'contenttype'
                                           ],
                                           require_auth=True)
    """ 10.Statuses/user_timeline_ids 其他用户发表时间线索引 """
    # required: name
    _statuses_user_timeline_ids = bind_api(path='/statuses/user_timeline_ids',
                                           payload_type='retid',
                                           payload_list=True,
                                           allowed_param=[
                                               'name', 'reqnum', 'pageflag',
                                               'pagetime', 'type',
                                               'contenttype'
                                           ],
                                           require_auth=True)
    """ 11.Statuses/broadcast_timeline_ids 我发表时间线索引 """
    _statuses_broadcast_timeline_ids = bind_api(
        path='/statuses/broadcast_timeline_ids',
        payload_type='retid',
        payload_list=True,
        allowed_param=[
            'reqnum', 'pageflag', 'pagetime', 'lastid', 'type', 'contenttype'
        ],
        require_auth=True)
    """ 12.Statuses/mentions_timeline_ids 用户提及时间线索引 """
    _statuses_mentions_timeline_ids = bind_api(
        path='/statuses/mentions_timeline_ids',
        payload_type='retid',
        payload_list=True,
        allowed_param=[
            'reqnum', 'pageflag', 'pagetime', 'lastid', 'type', 'contenttype'
        ],
        require_auth=True)
    """ 13.Statuses/users_timeline 多用户发表时间线 """
    _statuses_users_timeline = bind_api(path='/statuses/users_timeline',
                                        payload_type='tweet',
                                        payload_list=True,
                                        allowed_param=[
                                            'names', 'reqnum', 'pageflag',
                                            'pagetime', 'lastid', 'type',
                                            'contenttype'
                                        ],
                                        require_auth=True)
    """ 14.Statuses/users_timeline_ids 多用户发表时间线索引 """
    _statuses_users_timeline_ids = bind_api(
        path='/statuses/users_timeline_ids',
        payload_type='retid',
        payload_list=True,
        allowed_param=[
            'names', 'reqnum', 'pageflag', 'pagetime', 'lastid', 'type',
            'contenttype'
        ],
        require_auth=True)

    ## 微博相关 ##
    """ 1.t/show 获取一条微博数据 """
    _t_show = bind_api(path='/t/show',
                       payload_type='tweet',
                       allowed_param=['id'],
                       require_auth=True)
    """ 2.t/add 发表一条微博 """
    _t_add = bind_api(path='/t/add',
                      method='POST',
                      payload_type='retid',
                      allowed_param=['content', 'clientip', 'jing', 'wei'],
                      require_auth=True)
    """ 3.t/del 删除一条微博 """
    _t_del = bind_api(path='/t/del',
                      method='POST',
                      payload_type='retid',
                      allowed_param=['id'],
                      require_auth=True)
    """ 4.t/re_add 转播一条微博 """
    _t_re_add = bind_api(
        path='/t/re_add',
        method='POST',
        payload_type='retid',
        allowed_param=['reid', 'content', 'clientip', 'jing', 'wei'],
        require_auth=True)
    """ 5.t/reply 回复一条微博 """
    _t_reply = bind_api(
        path='/t/reply',
        method='POST',
        payload_type='retid',
        allowed_param=['reid', 'content', 'clientip', 'jing', 'wei'],
        require_auth=True)
    """ 6.t/add_pic 发表一条带图片的微博 """

    def _t_add_pic(self,
                   filename,
                   content,
                   clientip='127.0.0.1',
                   jing=None,
                   wei=None):
        headers, post_data = API._pack_image(
            filename,
            contentname="pic",
            content=content,
            clientip=clientip,
            jing=jing,
            wei=wei,
        )
        args = [content, clientip]
        allowed_param = ['content', 'clientip']

        if jing is not None:
            args.append(jing)
            allowed_param.append('jing')

        if wei is not None:
            args.append(wei)
            allowed_param.append('wei')

        return bind_api(path='/t/add_pic',
                        method='POST',
                        payload_type='retid',
                        require_auth=True,
                        allowed_param=allowed_param)(self,
                                                     *args,
                                                     post_data=post_data,
                                                     headers=headers)

    """ 7.t/re_count 转播数或点评数 """
    _t_re_count = bind_api(path='/t/re_count',
                           payload_type='json',
                           allowed_param=['ids', 'flag'],
                           require_auth=True)
    """ 8.t/re_list 获取单条微博的转发或点评列表 """
    _t_re_list = bind_api(path='/t/re_list',
                          payload_type='tweet',
                          payload_list=True,
                          allowed_param=[
                              'rootid', 'reqnum', 'flag', 'pageflag',
                              'pagetime', 'twitterid'
                          ],
                          require_auth=True)
    """ 9.t/comment 点评一条微博 """
    _t_comment = bind_api(
        path='/t/comment',
        method='POST',
        payload_type='retid',
        allowed_param=['reid', 'content', 'clientip', 'jing', 'wei'],
        require_auth=True)
    """ 10.t/add_music发表音乐微博 """
    _t_add_music = bind_api(path='/t/add_music',
                            method='POST',
                            payload_type='retid',
                            allowed_param=[
                                'url', 'title', 'author', 'content',
                                'clientip', 'jing', 'wei'
                            ],
                            require_auth=True)
    """ 11.t/add_video发表视频微博 """
    _t_add_video = bind_api(
        path='/t/add_video',
        method='POST',
        payload_type='retid',
        allowed_param=['url', 'content', 'clientip', 'jing', 'wei'],
        require_auth=True)
    """ 12.t/getvideoinfo 获取视频信息 """
    _t_getvideoinfo = bind_api(path='/t/getvideoinfo',
                               method='POST',
                               payload_type='video',
                               allowed_param=['url'],
                               require_auth=True)
    """ 13.t/list 根据微博ID批量获取微博内容(与索引合起来用) """
    _t_list = bind_api(path='/t/list',
                       method='GET',
                       payload_type='tweet',
                       payload_list=True,
                       allowed_param=['ids'],
                       require_auth=True)

    ## 帐户相关 ##
    """ 1.User/info获取自己的详细资料 """
    _user_info = bind_api(path='/user/info',
                          payload_type='user',
                          allowed_param=[],
                          require_auth=True)
    """ 2.user/update 更新用户信息 """
    _user_update = bind_api(path='/user/update',
                            method='POST',
                            allowed_param=[
                                'nick', 'sex', 'year', 'month', 'day',
                                'countrycode', 'provincecode', 'citycode',
                                'introduction'
                            ],
                            require_auth=True)
    """ 3.user/update_head 更新用户头像信息 """

    def _user_update_head(self, filename):
        headers, post_data = API._pack_image(filename, "pic")
        args = []
        allowed_param = []

        return bind_api(path='/user/update_head',
                        method='POST',
                        require_auth=True,
                        allowed_param=allowed_param)(self,
                                                     *args,
                                                     post_data=post_data,
                                                     headers=headers)

    """ 4.user/other_info 获取其他人资料 """
    _user_other_info = bind_api(path='/user/other_info',
                                payload_type='user',
                                allowed_param=['name'],
                                require_auth=True)

    ## 关系链相关 ##
    """ 1.friends/fanslist 我的听众列表 """
    _friends_fanslist = bind_api(path='/friends/fanslist',
                                 payload_type='user',
                                 payload_list=True,
                                 allowed_param=['reqnum', 'startindex'],
                                 require_auth=True)
    """ 2.friends/idollist 我收听的人列表 """
    _friends_idollist = bind_api(path='/friends/idollist',
                                 payload_type='user',
                                 payload_list=True,
                                 allowed_param=['reqnum', 'startindex'],
                                 require_auth=True)
    """ 3.Friends/blacklist 黑名单列表 """
    _friends_blacklist = bind_api(path='/friends/blacklist',
                                  payload_type='user',
                                  payload_list=True,
                                  allowed_param=['reqnum', 'startindex'],
                                  require_auth=True)
    """ 4.Friends/speciallist 特别收听列表 """
    _friends_speciallist = bind_api(path='/friends/speciallist',
                                    payload_type='user',
                                    payload_list=True,
                                    allowed_param=['reqnum', 'startindex'],
                                    require_auth=True)
    """ 5.friends/add 收听某个用户 """
    _friends_add = bind_api(path='/friends/add',
                            method='POST',
                            allowed_param=['name'],
                            require_auth=True)
    """ 6.friends/del取消收听某个用户 """
    _friends_del = bind_api(  # fix confilicts with del
        path='/friends/del',
        method='POST',
        allowed_param=['name'],
        require_auth=True)
    """ 7.friends/addspecial 特别收听某个用户 """
    _friends_addspecial = bind_api(path='/friends/addspecial',
                                   method='POST',
                                   allowed_param=['name'],
                                   require_auth=True)
    """ 8.friends/delspecial 取消特别收听某个用户 """
    _friends_delspecial = bind_api(path='/friends/delspecial',
                                   method='POST',
                                   allowed_param=['name'],
                                   require_auth=True)
    """ 9.friends/addblacklist 添加某个用户到黑名单 """
    _friends_addblacklist = bind_api(path='/friends/addblacklist',
                                     method='POST',
                                     allowed_param=['name'],
                                     require_auth=True)
    """ 10.friends/delblacklist 从黑名单中删除某个用户 """
    _friends_delblacklist = bind_api(path='/friends/delblacklist',
                                     method='POST',
                                     allowed_param=['name'],
                                     require_auth=True)
    """ 11.friends/check 检测是否我的听众或收听的人 """
    _friends_check = bind_api(path='/friends/check',
                              payload_type='json',
                              allowed_param=['names', 'flag'],
                              require_auth=True)
    """ 12.friends/user_fanslist 其他帐户听众列表 """
    _friends_user_fanslist = bind_api(
        path='/friends/user_fanslist',
        payload_type='user',
        payload_list=True,
        allowed_param=['name', 'reqnum', 'startindex'],
        require_auth=True)
    """ 13.friends/user_idollist 其他帐户收听的人列表 """
    _friends_user_idollist = bind_api(
        path='/friends/user_idollist',
        payload_type='user',
        payload_list=True,
        allowed_param=['name', 'reqnum', 'startindex'],
        require_auth=True)
    """ 14.friends/user_speciallist 其他帐户特别收听的人列表 """
    _friends_user_speciallist = bind_api(
        path='/friends/user_speciallist',
        payload_type='user',
        payload_list=True,
        allowed_param=['name', 'reqnum', 'startindex'],
        require_auth=True)

    ## 私信相关 ##
    """ 1.private/add 发私信 """
    _private_add = bind_api(
        path='/private/add',
        method='POST',
        payload_type='retid',
        allowed_param=['name', 'content', 'clientip', 'jing', 'wei'],
        require_auth=True)
    """ 2.private/del 删除一条私信 """
    _private_del = bind_api(path='/private/del',
                            method='POST',
                            payload_type='retid',
                            allowed_param=['id'],
                            require_auth=True)
    """ 3.private/recv 收件箱 """
    _private_recv = bind_api(
        path='/private/recv',
        payload_type='tweet',
        payload_list=True,
        allowed_param=['reqnum', 'pageflag', 'pagetime', 'lastid'],
        require_auth=True)
    """ 4.private/send 发件箱 """
    _private_send = bind_api(
        path='/private/send',
        payload_type='tweet',
        payload_list=True,
        allowed_param=['reqnum', 'pageflag', 'pagetime', 'lastid'],
        require_auth=True)

    ## 搜索相关 ##
    """ 1.Search/user 搜索用户 """
    _search_user = bind_api(path='/search/user',
                            payload_type='user',
                            payload_list=True,
                            allowed_param=['keyword', 'pagesize', 'page'],
                            require_auth=True)
    """ 2.Search/t 搜索微博 """
    _search_t = bind_api(path='/search/t',
                         payload_type='tweet',
                         payload_list=True,
                         allowed_param=['keyword', 'pagesize', 'page'],
                         require_auth=True)
    """ 3.Search/userbytag 通过标签搜索用户 """
    _search_userbytag = bind_api(path='/search/userbytag',
                                 payload_type='user',
                                 payload_list=True,
                                 allowed_param=['keyword', 'pagesize', 'page'],
                                 require_auth=True)

    # TODO: model parser
    ## 热度,趋势 ##
    """ 1.trends/ht 话题热榜 """
    _trends_ht = bind_api(path='/trends/ht',
                          payload_type='json',
                          allowed_param=['reqnum', 'type', 'pos'],
                          require_auth=True)
    """ 2.Trends/t 转播热榜 """
    _trends_t = bind_api(path='/trends/t',
                         payload_type='tweet',
                         payload_list=True,
                         allowed_param=['reqnum', 'type', 'pos'],
                         require_auth=True)

    ## 数据更新相关 ##
    """ 1.info/update 查看数据更新条数 """
    _info_update = bind_api(path='/info/update',
                            payload_type='json',
                            allowed_param=['op', 'type'],
                            require_auth=True)

    ## 数据收藏 ##
    """ 1.fav/addt 收藏一条微博 """
    _fav_addt = bind_api(path='/fav/addt',
                         method='POST',
                         payload_type='retid',
                         allowed_param=['id'],
                         require_auth=True)
    """ 2.fav/delt 从收藏删除一条微博 """
    _fav_delt = bind_api(path='/fav/delt',
                         method='POST',
                         payload_type='retid',
                         allowed_param=['id'],
                         require_auth=True)
    """ 3.fav/list_t 收藏的微博列表 """
    _fav_list_t = bind_api(
        path='/fav/list_t',
        payload_type='tweet',
        payload_list=True,
        allowed_param=['reqnum', 'pageflag', 'nexttime', 'prevtime', 'lastid'],
        require_auth=True)
    """ 4.fav/addht 订阅话题 """
    _fav_addht = bind_api(path='/fav/addht',
                          method='POST',
                          payload_type='retid',
                          allowed_param=['id'],
                          require_auth=True)
    """ 5.fav/delht 从收藏删除话题 """
    _fav_delht = bind_api(path='/fav/delht',
                          method='POST',
                          payload_type='retid',
                          allowed_param=['id'],
                          require_auth=True)
    """ 6.fav/list_ht 获取已订阅话题列表 """
    _fav_list_ht = bind_api(
        path='/fav/list_ht',
        payload_type='json',
        payload_list=True,
        allowed_param=['reqnum', 'pageflag', 'pagetime', 'lastid'],
        require_auth=True)

    ## 话题相关 ##
    """ 1.ht/ids 根据话题名称查询话题ID """
    _ht_ids = bind_api(path='/ht/ids',
                       payload_type='json',
                       payload_list=True,
                       allowed_param=['httexts'],
                       require_auth=True)
    """ 2.ht/info 根据话题ID获取话题相关微博 """
    _ht_info = bind_api(path='/ht/info',
                        payload_type='json',
                        payload_list=True,
                        allowed_param=['ids'],
                        require_auth=True)

    ## 标签相关 ##
    """ 1.tag/add 添加标签 """
    _tag_add = bind_api(path='/tag/add',
                        method='POST',
                        payload_type='retid',
                        allowed_param=['tag'],
                        require_auth=True)
    """ 2.tag/del 删除标签 """
    _tag_del = bind_api(path='/tag/del',
                        method='POST',
                        payload_type='retid',
                        allowed_param=['tagid'],
                        require_auth=True)

    ## 其他 ##
    """ 1.other/kownperson 我可能认识的人 """
    _other_kownperson = bind_api(path='/other/kownperson',
                                 payload_type='user',
                                 payload_list=True,
                                 allowed_param=[],
                                 require_auth=True)
    """ 2.other/shorturl短URL变长URL """
    _other_shorturl = bind_api(path='/other/shorturl',
                               payload_type='json',
                               allowed_param=['url'],
                               require_auth=True)
    """ 3.other/videokey 获取视频上传的KEY """
    _other_videokey = bind_api(path='/other/videokey',
                               payload_type='json',
                               allowed_param=[],
                               require_auth=True)
    """ Get the authenticated user """

    def me(self):
        return self.user.info()

    """ Internal use only """

    def _build_api_path(self):
        """bind all api function to its namespace"""
        self._bind_api_namespace(
            'timeline',
            home=self._statuses_home_timeline,
            public=self._statuses_public_timeline,
            user=self._statuses_user_timeline,
            users=self._statuses_users_timeline,
            mentions=self._statuses_mentions_timeline,
            topic=self._statuses_ht_timeline,
            broadcast=self._statuses_broadcast_timeline,
            special=self._statuses_special_timeline,
            area=self._statuses_area_timeline,
            # ids
            homeids=self._statuses_home_timeline_ids,
            userids=self._statuses_user_timeline_ids,
            usersids=self._statuses_users_timeline_ids,
            broadcastids=self._statuses_broadcast_timeline_ids,
            mentionsids=self._statuses_mentions_timeline_ids)
        self._bind_api_namespace('tweet',
                                 show=self._t_show,
                                 add=self._t_add,
                                 delete=self._t_del,
                                 retweet=self._t_re_add,
                                 reply=self._t_reply,
                                 addpic=self._t_add_pic,
                                 retweetcount=self._t_re_count,
                                 retweetlist=self._t_re_list,
                                 comment=self._t_comment,
                                 addmusic=self._t_add_music,
                                 addvideo=self._t_add_video,
                                 list=self._t_list)
        self._bind_api_namespace(
            'user',
            info=self._user_info,
            update=self._user_update,
            updatehead=self._user_update_head,
            userinfo=self._user_other_info,
        )
        self._bind_api_namespace(
            'friends',
            fanslist=self._friends_fanslist,
            idollist=self._friends_idollist,
            blacklist=self._friends_blacklist,
            speciallist=self._friends_speciallist,
            add=self._friends_add,
            delete=self._friends_del,
            addspecial=self._friends_addspecial,
            deletespecial=self._friends_delspecial,
            addblacklist=self._friends_addblacklist,
            deleteblacklist=self._friends_delblacklist,
            check=self._friends_check,
            userfanslist=self._friends_user_fanslist,
            useridollist=self._friends_user_idollist,
            userspeciallist=self._friends_user_speciallist,
        )
        self._bind_api_namespace(
            'private',
            add=self._private_add,
            delete=self._private_del,
            inbox=self._private_recv,
            outbox=self._private_send,
        )
        self._bind_api_namespace(
            'search',
            user=self._search_user,
            tweet=self._search_t,
            userbytag=self._search_userbytag,
        )
        self._bind_api_namespace('trends',
                                 topic=self._trends_ht,
                                 tweet=self._trends_t)
        self._bind_api_namespace(
            'info',
            update=self._info_update,
        )
        self._bind_api_namespace(
            'fav',
            addtweet=self._fav_addt,
            deletetweet=self._fav_delt,
            listtweet=self._fav_list_t,
            addtopic=self._fav_addht,
            deletetopic=self._fav_delht,
            listtopic=self._fav_list_ht,
        )
        self._bind_api_namespace(
            'topic',
            ids=self._ht_ids,
            info=self._ht_info,
        )
        self._bind_api_namespace(
            'tag',
            add=self._tag_add,
            delete=self._tag_del,
        )
        self._bind_api_namespace(
            'other',
            kownperson=self._other_kownperson,
            shorturl=self._other_shorturl,
            videokey=self._other_videokey,
            videoinfo=self._t_getvideoinfo,
        )
        self.t = self.tweet
        self.statuses = self.timeline  # fix 时间线 相关

    def _bind_api_namespace(self, base, **func_map):
        """ bind api to its path"""
        if base == '':
            for fname in func_map:
                setattr(self, fname, func_map[fname])
        else:
            if callable(getattr(self, base, None)):
                func_map['__call__'] = getattr(self, base)
            mapper = type('ApiPathMapper', (object, ), func_map)()
            setattr(self, base, mapper)

    # TODO: more general method
    @staticmethod
    def _pack_image(filename, contentname, max_size=1024, **params):
        """Pack image from file into multipart-formdata post body"""
        # image must be less than 700kb in size
        try:
            if os.path.getsize(filename) > (max_size * 1024):
                raise QWeiboError('File is too big, must be less than 700kb.')
        except os.error:
            raise QWeiboError('Unable to access file')

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise QWeiboError('Could not determine file type')
        file_type = file_type[0]
        if file_type.split('/')[0] != 'image':
            raise QWeiboError('Invalid file type for image: %s' % file_type)

        # build the mulitpart-formdata body
        BOUNDARY = 'QqWeIbObYaNdElF----'  # qqweibo by andelf
        body = []
        for key, val in params.items():
            if val is not None:
                body.append('--' + BOUNDARY)
                body.append('Content-Disposition: form-data; name="%s"' % key)
                body.append('Content-Type: text/plain; charset=UTF-8')
                body.append('Content-Transfer-Encoding: 8bit')
                body.append('')
                val = convert_to_utf8_bytes(val)
                body.append(val)
        fp = open(filename, 'rb')
        body.append('--' + BOUNDARY)
        body.append(
            'Content-Disposition: form-data; name="%s"; filename="%s"' %
            (contentname, filename.encode('utf-8')))
        body.append('Content-Type: %s' % file_type)
        body.append('Content-Transfer-Encoding: binary')
        body.append('')
        body.append(fp.read())
        body.append('--%s--' % BOUNDARY)
        body.append('')
        fp.close()
        body.append('--%s--' % BOUNDARY)
        body.append('')
        # fix py3k
        for i in range(len(body)):
            body[i] = convert_to_utf8_bytes(body[i])
        body = b'\r\n'.join(body)
        # build headers
        headers = {
            'Content-Type': 'multipart/form-data; boundary=%s' % BOUNDARY,
            'Content-Length': len(body)
        }

        return headers, body
예제 #46
0
파일: api.py 프로젝트: UniIsland/citypk
class API(object):
    """Mblog API"""
    def __init__(self,
                 auth_handler=None,
                 host='api.t.sina.com.cn',
                 search_host='api.t.sina.com.cn',
                 cache=None,
                 secure=False,
                 api_root='',
                 search_root='',
                 retry_count=0,
                 retry_delay=0,
                 retry_errors=None,
                 source=None,
                 parser=None,
                 log=None):
        self.auth = auth_handler
        self.host = host
        if source == None:
            if auth_handler != None:
                self.source = self.auth._consumer.key
        else:
            self.source = source
        self.search_host = search_host
        self.api_root = api_root
        self.search_root = search_root
        self.cache = cache
        self.secure = secure
        self.retry_count = retry_count
        self.retry_delay = retry_delay
        self.retry_errors = retry_errors
        self.parser = parser or ModelParser()
        self.log = log

    """ statuses/public_timeline """
    public_timeline = bind_api(path='/statuses/public_timeline.json',
                               payload_type='status',
                               payload_list=True,
                               allowed_param=[])
    """ statuses/home_timeline """
    home_timeline = bind_api(
        path='/statuses/home_timeline.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/friends_timeline """
    friends_timeline = bind_api(
        path='/statuses/friends_timeline.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/comment """
    comment = bind_api(path='/statuses/comment.json',
                       method='POST',
                       payload_type='comments',
                       allowed_param=['id', 'cid', 'comment'],
                       require_auth=True)
    """ statuses/comment_destroy """
    comment_destroy = bind_api(path='/statuses/comment_destroy/{id}.json',
                               method='DELETE',
                               payload_type='comments',
                               allowed_param=['id'],
                               require_auth=True)
    """ statuses/comments_timeline """
    comments = bind_api(path='/statuses/comments.json',
                        payload_type='comments',
                        payload_list=True,
                        allowed_param=['id', 'count', 'page'],
                        require_auth=True)
    """ statuses/comments_timeline """
    comments_timeline = bind_api(
        path='/statuses/comments_timeline.json',
        payload_type='comments',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/comments_by_me """
    comments_by_me = bind_api(
        path='/statuses/comments_by_me.json',
        payload_type='comments',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/user_timeline """
    user_timeline = bind_api(path='/statuses/user_timeline.json',
                             payload_type='status',
                             payload_list=True,
                             allowed_param=[
                                 'id', 'user_id', 'screen_name', 'since_id',
                                 'max_id', 'count', 'page'
                             ])
    """ statuses/mentions """
    mentions = bind_api(path='/statuses/mentions.json',
                        payload_type='status',
                        payload_list=True,
                        allowed_param=['since_id', 'max_id', 'count', 'page'],
                        require_auth=True)
    """ statuses/counts """
    counts = bind_api(path='/statuses/counts.json',
                      payload_type='counts',
                      payload_list=True,
                      allowed_param=['ids'],
                      require_auth=True)
    """ statuses/unread """
    unread = bind_api(path='/statuses/unread.json', payload_type='counts')
    """ statuses/retweeted_by_me """
    retweeted_by_me = bind_api(
        path='/statuses/retweeted_by_me.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/retweeted_to_me """
    retweeted_to_me = bind_api(
        path='/statuses/retweeted_to_me.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/retweets_of_me """
    retweets_of_me = bind_api(
        path='/statuses/retweets_of_me.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/show """
    get_status = bind_api(path='/statuses/show.json',
                          payload_type='status',
                          allowed_param=['id'])
    """ statuses/update """
    update_status = bind_api(path='/statuses/update.json',
                             method='POST',
                             payload_type='status',
                             allowed_param=['status', 'lat', 'long', 'source'],
                             require_auth=True)
    ## TODO: reflect change in upstream
    """ statuses/upload_url_text """
    update_status_img = bind_api(path='/statuses/upload_url_text.json',
                                 method='POST',
                                 payload_type='status',
                                 allowed_param=['status', 'url', 'source'],
                                 require_auth=True)
    """ statuses/upload """

    def upload(self, filename, status, lat=None, long=None, source=None):
        if source is None:
            source = self.source
        headers, post_data = API._pack_image(filename,
                                             1024,
                                             source=source,
                                             status=status,
                                             lat=lat,
                                             long=long,
                                             contentname="pic")
        args = [status]
        allowed_param = ['status']

        if lat is not None:
            args.append(lat)
            allowed_param.append('lat')

        if long is not None:
            args.append(long)
            allowed_param.append('long')

        if source is not None:
            args.append(source)
            allowed_param.append('source')
        kargs = {
            'post_data': post_data,
            'headers': headers,
        }
        return bind_api(
            path='/statuses/upload.json',
            method='POST',
            payload_type='status',
            require_auth=True,
            allowed_param=allowed_param
            #        )(self, *args, post_data=post_data, headers=headers)
        )(self, *args, **kargs)

    """ statuses/reply """
    reply = bind_api(path='/statuses/reply.json',
                     method='POST',
                     payload_type='status',
                     allowed_param=['id', 'cid', 'comment'],
                     require_auth=True)
    """ statuses/repost """
    repost = bind_api(path='/statuses/repost.json',
                      method='POST',
                      payload_type='status',
                      allowed_param=['id', 'status'],
                      require_auth=True)
    """ statuses/destroy """
    destroy_status = bind_api(path='/statuses/destroy/{id}.json',
                              method='DELETE',
                              payload_type='status',
                              allowed_param=['id'],
                              require_auth=True)
    """ statuses/retweet """
    retweet = bind_api(path='/statuses/retweet/{id}.json',
                       method='POST',
                       payload_type='status',
                       allowed_param=['id'],
                       require_auth=True)
    """ statuses/retweets """
    retweets = bind_api(path='/statuses/retweets/{id}.json',
                        payload_type='status',
                        payload_list=True,
                        allowed_param=['id', 'count'],
                        require_auth=True)
    """ users/show """
    get_user = bind_api(path='/users/show.json',
                        payload_type='user',
                        allowed_param=['id', 'user_id', 'screen_name'])
    """ Get the authenticated user """

    def me(self):
        return self.get_user(screen_name=self.auth.get_username())

    """ users/search """
    search_users = bind_api(path='/users/search.json',
                            payload_type='user',
                            payload_list=True,
                            require_auth=True,
                            allowed_param=['q', 'per_page', 'page'])
    """ statuses/friends """
    friends = bind_api(
        path='/statuses/friends.json',
        payload_type='user',
        payload_list=True,
        allowed_param=['id', 'user_id', 'screen_name', 'page', 'cursor'])
    """ statuses/followers """
    followers = bind_api(
        path='/statuses/followers.json',
        payload_type='user',
        payload_list=True,
        allowed_param=['id', 'user_id', 'screen_name', 'page', 'cursor'])
    """ direct_messages """
    direct_messages = bind_api(
        path='/direct_messages.json',
        payload_type='direct_message',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ direct_messages/sent """
    sent_direct_messages = bind_api(
        path='/direct_messages/sent.json',
        payload_type='direct_message',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ direct_messages/new """
    new_direct_message = bind_api(
        path='/direct_messages/new.json',
        method='POST',
        payload_type='direct_message',
        allowed_param=['id', 'screen_name', 'user_id', 'text'],
        require_auth=True)
    """ direct_messages/destroy """
    destroy_direct_message = bind_api(
        path='/direct_messages/destroy/{id}.json',
        method='POST',
        payload_type='direct_message',
        allowed_param=['id'],
        require_auth=True)
    """ friendships/create """
    create_friendship = bind_api(
        path='/friendships/create.json',
        method='POST',
        payload_type='user',
        allowed_param=['id', 'user_id', 'screen_name', 'follow'],
        require_auth=True)
    """ friendships/destroy """
    destroy_friendship = bind_api(
        path='/friendships/destroy.json',
        method='POST',
        payload_type='user',
        allowed_param=['id', 'user_id', 'screen_name'],
        require_auth=True)
    """ friendships/exists """
    exists_friendship = bind_api(path='/friendships/exists.json',
                                 payload_type='json',
                                 allowed_param=['user_a', 'user_b'])
    """ friendships/show """
    show_friendship = bind_api(path='/friendships/show.json',
                               payload_type='friendship',
                               allowed_param=[
                                   'source_id', 'source_screen_name',
                                   'target_id', 'target_screen_name'
                               ])
    """ friends/ids """
    friends_ids = bind_api(
        path='/friends/ids.json',
        payload_type='user',
        allowed_param=['id', 'user_id', 'screen_name', 'cursor', 'count'],
        require_auth=True)
    """ followers/ids """
    followers_ids = bind_api(
        path='/followers/ids.json',
        payload_type='json',
        allowed_param=['id', 'page'],
    )
    """ account/verify_credentials """

    def verify_credentials(self):
        try:
            return bind_api(path='/account/verify_credentials.json',
                            payload_type='user',
                            require_auth=True)(self)
        except WeibopError:
            return False

    """ account/rate_limit_status """
    rate_limit_status = bind_api(path='/account/rate_limit_status.json',
                                 payload_type='json')
    """ account/update_delivery_device """
    set_delivery_device = bind_api(path='/account/update_delivery_device.json',
                                   method='POST',
                                   allowed_param=['device'],
                                   payload_type='user',
                                   require_auth=True)
    """account/get_privacy"""
    get_privacy = bind_api(path='/account/get_privacy.json',
                           payload_type='json')
    """account/update_privacy"""
    update_privacy = bind_api(
        path='/account/update_privacy.json',
        payload_type='json',
        method='POST',
        allow_param=['comment', 'message', 'realname', 'geo', 'badge'],
        require_auth=True)
    """ account/update_profile_colors """
    update_profile_colors = bind_api(
        path='/account/update_profile_colors.json',
        method='POST',
        payload_type='user',
        allowed_param=[
            'profile_background_color', 'profile_text_color',
            'profile_link_color', 'profile_sidebar_fill_color',
            'profile_sidebar_border_color'
        ],
        require_auth=True)
    """ account/update_profile_image """

    def update_profile_image(self, filename):
        headers, post_data = API._pack_image(filename=filename,
                                             max_size=700,
                                             source=self.source)
        return bind_api(path='/account/update_profile_image.json',
                        method='POST',
                        payload_type='user',
                        require_auth=True)(self,
                                           post_data=post_data,
                                           headers=headers)

    """ account/update_profile_background_image """

    def update_profile_background_image(self, filename, *args, **kargs):
        headers, post_data = API._pack_image(filename, 800)
        bind_api(path='/account/update_profile_background_image.json',
                 method='POST',
                 payload_type='user',
                 allowed_param=['tile'],
                 require_auth=True)(self, post_data=post_data, headers=headers)

    """ account/update_profile """
    update_profile = bind_api(
        path='/account/update_profile.json',
        method='POST',
        payload_type='user',
        allowed_param=['name', 'url', 'location', 'description'],
        require_auth=True)
    """ favorites """
    favorites = bind_api(path='/favorites/{id}.json',
                         payload_type='status',
                         payload_list=True,
                         allowed_param=['id', 'page'])
    """ favorites/create """
    create_favorite = bind_api(path='/favorites/create/{id}.json',
                               method='POST',
                               payload_type='status',
                               allowed_param=['id'],
                               require_auth=True)
    """ favorites/destroy """
    destroy_favorite = bind_api(path='/favorites/destroy/{id}.json',
                                method='POST',
                                payload_type='status',
                                allowed_param=['id'],
                                require_auth=True)
    """ notifications/follow """
    enable_notifications = bind_api(
        path='/notifications/follow.json',
        method='POST',
        payload_type='user',
        allowed_param=['id', 'user_id', 'screen_name'],
        require_auth=True)
    """ notifications/leave """
    disable_notifications = bind_api(
        path='/notifications/leave.json',
        method='POST',
        payload_type='user',
        allowed_param=['id', 'user_id', 'screen_name'],
        require_auth=True)
    """ blocks/create """
    create_block = bind_api(path='/blocks/create.json',
                            method='POST',
                            payload_type='user',
                            allowed_param=['id', 'user_id', 'screen_name'],
                            require_auth=True)
    """ blocks/destroy """
    destroy_block = bind_api(path='/blocks/destroy.json',
                             method='DELETE',
                             payload_type='user',
                             allowed_param=['id', 'user_id', 'screen_name'],
                             require_auth=True)
    """ blocks/exists """

    def exists_block(self, *args, **kargs):
        try:
            bind_api(path='/blocks/exists.json',
                     allowed_param=['id', 'user_id', 'screen_name'],
                     require_auth=True)(self, *args, **kargs)
        except WeibopError:
            return False
        return True

    """ blocks/blocking """
    blocks = bind_api(path='/blocks/blocking.json',
                      payload_type='user',
                      payload_list=True,
                      allowed_param=['page'],
                      require_auth=True)
    """ blocks/blocking/ids """
    blocks_ids = bind_api(path='/blocks/blocking/ids.json',
                          payload_type='json',
                          require_auth=True)
    """ statuses/repost """
    report_spam = bind_api(path='/report_spam.json',
                           method='POST',
                           payload_type='user',
                           allowed_param=['id', 'user_id', 'screen_name'],
                           require_auth=True)
    """ saved_searches """
    saved_searches = bind_api(path='/saved_searches.json',
                              payload_type='saved_search',
                              payload_list=True,
                              require_auth=True)
    """ saved_searches/show """
    get_saved_search = bind_api(path='/saved_searches/show/{id}.json',
                                payload_type='saved_search',
                                allowed_param=['id'],
                                require_auth=True)
    """ saved_searches/create """
    create_saved_search = bind_api(path='/saved_searches/create.json',
                                   method='POST',
                                   payload_type='saved_search',
                                   allowed_param=['query'],
                                   require_auth=True)
    """ saved_searches/destroy """
    destroy_saved_search = bind_api(path='/saved_searches/destroy/{id}.json',
                                    method='DELETE',
                                    payload_type='saved_search',
                                    allowed_param=['id'],
                                    require_auth=True)
    """ help/test """

    def test(self):
        try:
            bind_api(path='/help/test.json', )(self)
        except WeibopError:
            return False
        return True

    def create_list(self, *args, **kargs):
        return bind_api(path='/%s/lists.json' % self.auth.get_username(),
                        method='POST',
                        payload_type='list',
                        allowed_param=['name', 'mode', 'description'],
                        require_auth=True)(self, *args, **kargs)

    def destroy_list(self, slug):
        return bind_api(path='/%s/lists/%s.json' %
                        (self.auth.get_username(), slug),
                        method='DELETE',
                        payload_type='list',
                        require_auth=True)(self)

    def update_list(self, slug, *args, **kargs):
        return bind_api(path='/%s/lists/%s.json' %
                        (self.auth.get_username(), slug),
                        method='POST',
                        payload_type='list',
                        allowed_param=['name', 'mode', 'description'],
                        require_auth=True)(self, *args, **kargs)

    lists = bind_api(path='/{user}/lists.json',
                     payload_type='list',
                     payload_list=True,
                     allowed_param=['user', 'cursor'],
                     require_auth=True)

    lists_memberships = bind_api(path='/{user}/lists/memberships.json',
                                 payload_type='list',
                                 payload_list=True,
                                 allowed_param=['user', 'cursor'],
                                 require_auth=True)

    lists_subscriptions = bind_api(path='/{user}/lists/subscriptions.json',
                                   payload_type='list',
                                   payload_list=True,
                                   allowed_param=['user', 'cursor'],
                                   require_auth=True)

    list_timeline = bind_api(
        path='/{owner}/lists/{slug}/statuses.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['owner', 'slug', 'since_id', 'max_id', 'count', 'page'])

    get_list = bind_api(path='/{owner}/lists/{slug}.json',
                        payload_type='list',
                        allowed_param=['owner', 'slug'])

    def add_list_member(self, slug, *args, **kargs):
        return bind_api(path='/%s/%s/members.json' %
                        (self.auth.get_username(), slug),
                        method='POST',
                        payload_type='list',
                        allowed_param=['id'],
                        require_auth=True)(self, *args, **kargs)

    def remove_list_member(self, slug, *args, **kargs):
        return bind_api(path='/%s/%s/members.json' %
                        (self.auth.get_username(), slug),
                        method='DELETE',
                        payload_type='list',
                        allowed_param=['id'],
                        require_auth=True)(self, *args, **kargs)

    list_members = bind_api(path='/{owner}/{slug}/members.json',
                            payload_type='user',
                            payload_list=True,
                            allowed_param=['owner', 'slug', 'cursor'])

    def is_list_member(self, owner, slug, user_id):
        try:
            return bind_api(path='/%s/%s/members/%s.json' %
                            (owner, slug, user_id),
                            payload_type='user')(self)
        except WeibopError:
            return False

    subscribe_list = bind_api(path='/{owner}/{slug}/subscribers.json',
                              method='POST',
                              payload_type='list',
                              allowed_param=['owner', 'slug'],
                              require_auth=True)

    unsubscribe_list = bind_api(path='/{owner}/{slug}/subscribers.json',
                                method='DELETE',
                                payload_type='list',
                                allowed_param=['owner', 'slug'],
                                require_auth=True)

    list_subscribers = bind_api(path='/{owner}/{slug}/subscribers.json',
                                payload_type='user',
                                payload_list=True,
                                allowed_param=['owner', 'slug', 'cursor'])

    def is_subscribed_list(self, owner, slug, user_id):
        try:
            return bind_api(path='/%s/%s/subscribers/%s.json' %
                            (owner, slug, user_id),
                            payload_type='user')(self)
        except WeibopError:
            return False

    """ trends/available """
    trends_available = bind_api(path='/trends/available.json',
                                payload_type='json',
                                allowed_param=['lat', 'long'])
    """ trends/location """
    trends_location = bind_api(path='/trends/{woeid}.json',
                               payload_type='json',
                               allowed_param=['woeid'])
    """ search """
    search = bind_api(search_api=True,
                      path='/search.json',
                      payload_type='search_result',
                      payload_list=True,
                      allowed_param=[
                          'q', 'lang', 'locale', 'rpp', 'page', 'since_id',
                          'geocode', 'show_user'
                      ])
    search.pagination_mode = 'page'
    """ trends """
    trends = bind_api(path='/trends.json',
                      payload_type='trends',
                      payload_list=True,
                      allowed_param=['user_id', 'count', 'page'],
                      require_auth=True)
    """trends/statuses"""
    trends_statuses = bind_api(path='/trends/statuses.json',
                               payload_type='status',
                               payload_list=True,
                               allowed_param=['trend_name'],
                               require_auth=True)
    """trends/follow"""
    trends_follow = bind_api(path='/trends/follow.json',
                             method='POST',
                             allowed_param=['trend_name'],
                             require_auth=True)
    """trends/destroy"""
    trends_destroy = bind_api(path='/trends/destroy.json',
                              method='DELETE',
                              allowed_param=['trend_id'],
                              require_auth=True)
    """ trends/current """
    trends_current = bind_api(search_api=True,
                              path='/trends/current.json',
                              payload_type='json',
                              allowed_param=['exclude'])
    """ trends/hourly"""
    trends_hourly = bind_api(search_api=True,
                             path='/trends/hourly.json',
                             payload_type='trends',
                             allowed_param=[])
    """ trends/daily """
    trends_daily = bind_api(search_api=True,
                            path='/trends/daily.json',
                            payload_type='trends',
                            allowed_param=[])
    """ trends/weekly """
    trends_weekly = bind_api(search_api=True,
                             path='/trends/weekly.json',
                             payload_type='json',
                             allowed_param=[])
    """ Tags """
    tags = bind_api(
        path='/tags.json',
        payload_type='tags',
        payload_list=True,
        allowed_param=['user_id'],
        require_auth=True,
    )
    tag_create = bind_api(
        path='/tags/create.json',
        payload_type='tags',
        method='POST',
        allowed_param=['tags'],
        payload_list=True,
        require_auth=True,
    )
    tag_suggestions = bind_api(
        path='/tags/suggestions.json',
        payload_type='tags',
        require_auth=True,
        payload_list=True,
    )
    tag_destroy = bind_api(
        path='/tags/destroy.json',
        payload_type='json',
        method='POST',
        require_auth=True,
        allowed_param=['tag_id'],
    )
    tag_destroy_batch = bind_api(
        path='/tags/destroy_batch.json',
        payload_type='json',
        method='DELETE',
        require_auth=True,
        payload_list=True,
        allowed_param=['ids'],
    )
    """ Internal use only """

    @staticmethod
    def _pack_image(filename,
                    max_size,
                    source=None,
                    status=None,
                    lat=None,
                    long=None,
                    contentname="image"):
        """Pack image from file into multipart-formdata post body"""
        # image must be less than 700kb in size
        try:
            if os.path.getsize(filename) > (max_size * 1024):
                raise WeibopError('File is too big, must be less than 700kb.')
        #except os.error, e:
        except os.error:
            raise WeibopError('Unable to access file')

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise WeibopError('Could not determine file type')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise WeibopError('Invalid file type for image: %s' % file_type)

        # build the mulitpart-formdata body
        fp = open(filename, 'rb')
        BOUNDARY = 'Tw3ePy'
        body = []
        if status is not None:
            body.append('--' + BOUNDARY)
            body.append('Content-Disposition: form-data; name="status"')
            body.append('Content-Type: text/plain; charset=US-ASCII')
            body.append('Content-Transfer-Encoding: 8bit')
            body.append('')
            body.append(status)
        if source is not None:
            body.append('--' + BOUNDARY)
            body.append('Content-Disposition: form-data; name="source"')
            body.append('Content-Type: text/plain; charset=US-ASCII')
            body.append('Content-Transfer-Encoding: 8bit')
            body.append('')
            body.append(source)
        if lat is not None:
            body.append('--' + BOUNDARY)
            body.append('Content-Disposition: form-data; name="lat"')
            body.append('Content-Type: text/plain; charset=US-ASCII')
            body.append('Content-Transfer-Encoding: 8bit')
            body.append('')
            body.append(lat)
        if long is not None:
            body.append('--' + BOUNDARY)
            body.append('Content-Disposition: form-data; name="long"')
            body.append('Content-Type: text/plain; charset=US-ASCII')
            body.append('Content-Transfer-Encoding: 8bit')
            body.append('')
            body.append(long)
        body.append('--' + BOUNDARY)
        body.append('Content-Disposition: form-data; name="' + contentname +
                    '"; filename="%s"' % filename)
        body.append('Content-Type: %s' % file_type)
        body.append('Content-Transfer-Encoding: binary')
        body.append('')
        body.append(fp.read())
        body.append('--' + BOUNDARY + '--')
        body.append('')
        fp.close()
        body.append('--' + BOUNDARY + '--')
        body.append('')
        body = '\r\n'.join(body)
        # build headers
        headers = {
            'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
            'Content-Length': len(body)
        }

        return headers, body
예제 #47
0
파일: api.py 프로젝트: ceciet/Pandora
class API(object):
    '''
    classdocs
    '''
    def __init__(self,
                 key,
                 secret,
                 api_url=config.get('api_url'),
                 session_url=config.get('session_url'),
                 format="json",
                 sign_method="md5",
                 version="2.0"):
        '''
        Constructor
        '''
        self.app_key = key

        self.app_secret = secret

        self.gatewayUrl = api_url

        self.sessinkeyUrl = session_url

        self.format = format

        self.sign_method = sign_method

        self.api_version = version

        self.session = ""

#--------------------- 掌柜说API ------------------------------

#判断是否是粉丝

    jianghu_fan_check = bind_api(method='taobao.jianghu.fan.check')
    #关注一个掌柜说
    jianghu_fan_follow = bind_api(method='taobao.jianghu.fan.follow')

    #--------------------- 物流宝API ------------------------------

    #查询库存详情
    wlb_inventory_detail_get = bind_api(
        method='taobao.wlb.inventory.detail.get')
    #库存同步
    wlb_inventory_sync = bind_api(method='taobao.wlb.inventory.sync')
    #根据商品ID查询所有库存变更记录
    wlb_inventorylog_query = bind_api(method='taobao.wlb.inventorylog.query')
    #添加单个物流宝商品
    wlb_item_add = bind_api(method='taobao.wlb.item.add')
    #添加商品授权规则
    wlb_item_authorization_add = bind_api(
        method='taobao.wlb.item.authorization.add')
    #删除授权关系
    wlb_item_authorization_delete = bind_api(
        method='taobao.wlb.item.authorization.delete')
    #查询授权关系
    wlb_item_authorization_query = bind_api(
        method='taobao.wlb.item.authorization.query')
    #创建商品组合关系
    wlb_item_combination_create = bind_api(
        method='taobao.wlb.item.combination.create')
    #删除商品组合关系
    wlb_item_combination_delete = bind_api(
        method='taobao.wlb.item.combination.delete')
    #根据商品id查询商品组合关系
    wlb_item_combination_get = bind_api(
        method='taobao.wlb.item.combination.get')
    #创建商品的代销关系
    wlb_item_consignment_create = bind_api(
        method='taobao.wlb.item.consignment.create')
    #删除商品的代销关系
    wlb_item_consignment_delete = bind_api(
        method='taobao.wlb.item.consignment.delete')
    #分页查询物流宝商品的代销关系
    wlb_item_consignment_page_get = bind_api(
        method='taobao.wlb.item.consignment.page.get')
    #查询可代销的物流宝商品
    wlb_item_consignment_query = bind_api(
        method='taobao.wlb.item.consignment.query')
    #商品删除
    wlb_item_delete = bind_api(method='taobao.wlb.item.delete')
    #根据商品ID获取商品信息
    wlb_item_get = bind_api(method='taobao.wlb.item.get')
    #根据物流宝商品ID查询商品映射关系
    wlb_item_map_get = bind_api(method='taobao.wlb.item.map.get')
    #根据外部实体查询映射的物流宝商品id
    wlb_item_map_get_by_extentity = bind_api(
        method='taobao.wlb.item.map.get.by.extentity')
    #分页查询商品
    wlb_item_query = bind_api(method='taobao.wlb.item.query')
    #商品映射同步
    wlb_item_synchronize = bind_api(method='taobao.wlb.item.synchronize')
    #删除商品映射同步
    wlb_item_synchronize_delete = bind_api(
        method='taobao.wlb.item.synchronize.delete')
    #物流宝商品修改
    wlb_item_update = bind_api(method='taobao.wlb.item.update')
    #物流宝通知消息确认
    wlb_notify_message_confirm = bind_api(
        method='taobao.wlb.notify.message.confirm')
    #物流宝通知消息查询接口
    wlb_notify_message_page_get = bind_api(
        method='taobao.wlb.notify.message.page.get')
    #取消物流宝订单
    wlb_order_cancel = bind_api(method='taobao.wlb.order.cancel')
    #物流宝订单已发货通知接口
    wlb_order_consign = bind_api(method='taobao.wlb.order.consign')
    #创建物流宝订单
    wlb_order_create = bind_api(method='taobao.wlb.order.create')
    #分页查询物流宝订单
    wlb_order_page_get = bind_api(method='taobao.wlb.order.page.get')
    #新增物流宝订单调度规则
    wlb_order_schedule_rule_add = bind_api(
        method='taobao.wlb.order.schedule.rule.add')
    #修改订单调度规则
    wlb_order_schedule_rule_update = bind_api(
        method='taobao.wlb.order.schedule.rule.update')
    #分页查询物流宝订单商品详情
    wlb_orderitem_page_get = bind_api(method='taobao.wlb.orderitem.page.get')
    #删除订单调度规则
    wlb_orderschedulerule_delete = bind_api(
        method='taobao.wlb.orderschedulerule.delete')
    #查询某个卖家的所有订单调度规则
    wlb_orderschedulerule_query = bind_api(
        method='taobao.wlb.orderschedulerule.query')
    #物流宝订单流转状态查询
    wlb_orderstatus_get = bind_api(method='taobao.wlb.orderstatus.get')
    #补货统计查询
    wlb_replenish_statistics = bind_api(
        method='taobao.wlb.replenish.statistics')
    #查询商家定购的所有服务
    wlb_subscription_query = bind_api(method='taobao.wlb.subscription.query')
    #通过物流订单编号查询物流信息
    wlb_tmsorder_query = bind_api(method='taobao.wlb.tmsorder.query')
    #根据交易号获取物流宝订单
    wlb_tradeorder_get = bind_api(method='taobao.wlb.tradeorder.get')
    #根据物流宝订单编号查询物流宝订单概要信息
    wlb_wlborder_get = bind_api(method='taobao.wlb.wlborder.get')

    #--------------------- 淘客API ------------------------------

    #淘宝客类目推广URL
    taobaoke_caturl_get = bind_api(method='taobao.taobaoke.caturl.get')
    #淘客商品转换
    taobaoke_items_convert = bind_api(method='taobao.taobaoke.items.convert')
    #查询淘宝客推广商品详细信息
    taobaoke_items_detail_get = bind_api(
        method='taobao.taobaoke.items.detail.get')
    #查询淘宝客推广商品
    taobaoke_items_get = bind_api(method='taobao.taobaoke.items.get')
    #淘宝客关键词搜索URL
    taobaoke_listurl_get = bind_api(method='taobao.taobaoke.listurl.get')
    #淘宝客报表查询
    taobaoke_report_get = bind_api(method='taobao.taobaoke.report.get')
    #淘客店铺转换
    taobaoke_shops_convert = bind_api(method='taobao.taobaoke.shops.convert')
    #淘宝客店铺搜索
    taobaoke_shops_get = bind_api(method='taobao.taobaoke.shops.get')
    #工具联盟注册校验
    taobaoke_tool_relation = bind_api(method='taobao.taobaoke.tool.relation')
    #虚拟卡查询
    taobaoke_virtualcard_get = bind_api(
        method='taobao.taobaoke.virtualcard.get')

    #--------------------- 评价API ------------------------------

    #新增单个评价
    traderate_add = bind_api(method='taobao.traderate.add')
    #针对父子订单新增批量评价
    traderate_list_add = bind_api(method='taobao.traderate.list.add')
    #搜索评价信息
    traderates_get = bind_api(method='taobao.traderates.get')
    #商品评价查询接口
    traderates_search = bind_api(method='taobao.traderates.search')

    #--------------------- 营销API ------------------------------

    #定向优惠活动名称与描述违禁词检查
    marketing_promotion_kfc = bind_api(method='taobao.marketing.promotion.kfc')
    #查询商品定向优惠策略
    marketing_promotions_get = bind_api(
        method='taobao.marketing.promotions.get')
    #查询人群标签
    marketing_tags_get = bind_api(method='taobao.marketing.tags.get')
    #查询某个卖家的店铺优惠券领取活动
    promotion_activity_get = bind_api(method='taobao.promotion.activity.get')
    #买家查询当前所有优惠券信息
    promotion_coupon_buyer_search = bind_api(
        method='taobao.promotion.coupon.buyer.search')
    #通过接口可以查询某个店铺优惠券的买家详细信息
    promotion_coupondetail_get = bind_api(
        method='taobao.promotion.coupondetail.get')
    #查询卖家优惠券
    promotion_coupons_get = bind_api(method='taobao.promotion.coupons.get')
    #限时打折详情查询
    promotion_limitdiscount_detail_get = bind_api(
        method='taobao.promotion.limitdiscount.detail.get')
    #限时打折查询
    promotion_limitdiscount_get = bind_api(
        method='taobao.promotion.limitdiscount.get')
    #搭配套餐查询
    promotion_meal_get = bind_api(method='taobao.promotion.meal.get')

    #--------------------- 信息安全API ------------------------------

    #关键词过滤匹配
    kfc_keyword_search = bind_api(method='taobao.kfc.keyword.search')

    #--------------------- 物流API ------------------------------

    #查询地址区域
    areas_get = bind_api(method='taobao.areas.get')
    #新增运费模板
    delivery_template_add = bind_api(method='taobao.delivery.template.add')
    #删除运费模板
    delivery_template_delete = bind_api(
        method='taobao.delivery.template.delete')
    #获取用户指定运费模板信息
    delivery_template_get = bind_api(method='taobao.delivery.template.get')
    #修改运费模板
    delivery_template_update = bind_api(
        method='taobao.delivery.template.update')
    #获取用户下所有模板
    delivery_templates_get = bind_api(method='taobao.delivery.templates.get')
    #卖家地址库新增接口
    logistics_address_add = bind_api(method='taobao.logistics.address.add')
    #卖家地址库修改
    logistics_address_modify = bind_api(
        method='taobao.logistics.address.modify')
    #删除卖家地址库
    logistics_address_remove = bind_api(
        method='taobao.logistics.address.remove')
    #查询卖家地址库
    logistics_address_search = bind_api(
        method='taobao.logistics.address.search')
    #查询物流公司信息
    logistics_companies_get = bind_api(method='taobao.logistics.companies.get')
    #无需物流(虚拟)发货处理
    logistics_dummy_send = bind_api(method='taobao.logistics.dummy.send')
    #自己联系物流(线下物流)发货
    logistics_offline_send = bind_api(method='taobao.logistics.offline.send')
    #取消物流订单接口
    logistics_online_cancel = bind_api(method='taobao.logistics.online.cancel')
    #确认发货通知接口
    logistics_online_confirm = bind_api(
        method='taobao.logistics.online.confirm')
    #在线订单发货处理(支持货到付款)
    logistics_online_send = bind_api(method='taobao.logistics.online.send')
    #批量查询物流订单,返回详细信息
    logistics_orders_detail_get = bind_api(
        method='taobao.logistics.orders.detail.get')
    #批量查询物流订单
    logistics_orders_get = bind_api(method='taobao.logistics.orders.get')
    #查询支持起始地到目的地范围的物流公司
    logistics_partners_get = bind_api(method='taobao.logistics.partners.get')
    #物流流转信息查询
    logistics_trace_search = bind_api(method='taobao.logistics.trace.search')
    #添加邮费模板
    postage_add = bind_api(method='taobao.postage.add')
    #删除单个运费模板
    postage_delete = bind_api(method='taobao.postage.delete')
    #获取单个运费模板
    postage_get = bind_api(method='taobao.postage.get')
    #修改邮费模板
    postage_update = bind_api(method='taobao.postage.update')
    #获取卖家的运费模板
    postages_get = bind_api(method='taobao.postages.get')
    #异步批量物流发货api
    topats_delivery_send = bind_api(method='taobao.topats.delivery.send')

    #--------------------- 在线订购API ------------------------------

    #订单记录导出
    vas_order_search = bind_api(method='taobao.vas.order.search')
    #订购记录导出
    vas_subsc_search = bind_api(method='taobao.vas.subsc.search')
    #订购关系查询
    vas_subscribe_get = bind_api(method='taobao.vas.subscribe.get')

    #--------------------- 交易API ------------------------------

    #获取异步任务结果
    topats_result_get = bind_api(method='taobao.topats.result.get')
    #异步获取淘宝卖家绑定的支付宝账户的财务明细
    topats_trade_accountreport_get = bind_api(
        method='taobao.topats.trade.accountreport.get')
    #异步批量获取交易订单详情api
    topats_trades_fullinfo_get = bind_api(
        method='taobao.topats.trades.fullinfo.get')
    #交易订单帐务查询
    trade_amount_get = bind_api(method='taobao.trade.amount.get')
    #卖家关闭一笔交易
    trade_close = bind_api(method='taobao.trade.close')
    #获取交易确认收货费用
    trade_confirmfee_get = bind_api(method='taobao.trade.confirmfee.get')
    #获取单笔交易的详细信息
    trade_fullinfo_get = bind_api(method='taobao.trade.fullinfo.get')
    #获取单笔交易的部分信息(性能高)
    trade_get = bind_api(method='taobao.trade.get')
    #对一笔交易添加备注
    trade_memo_add = bind_api(method='taobao.trade.memo.add')
    #修改一笔交易备注
    trade_memo_update = bind_api(method='taobao.trade.memo.update')
    #更新交易订单的销售属性
    trade_ordersku_update = bind_api(method='taobao.trade.ordersku.update')
    #修改订单邮费价格
    trade_postage_update = bind_api(method='taobao.trade.postage.update')
    #延长交易收货时间
    trade_receivetime_delay = bind_api(method='taobao.trade.receivetime.delay')
    #更改交易的收货地址
    trade_shippingaddress_update = bind_api(
        method='taobao.trade.shippingaddress.update')
    #交易快照查询
    trade_snapshot_get = bind_api(method='taobao.trade.snapshot.get')
    #搜索当前会话用户作为买家达成的交易记录
    trades_bought_get = bind_api(method='taobao.trades.bought.get')
    #搜索当前会话用户作为卖家已卖出的交易数据
    trades_sold_get = bind_api(method='taobao.trades.sold.get')
    #搜索当前会话用户作为卖家已卖出的增量交易数据
    trades_sold_increment_get = bind_api(
        method='taobao.trades.sold.increment.get')

    #--------------------- 淘画报API ------------------------------

    #获取指定画报列表
    poster_appointedposters_get = bind_api(
        method='taobao.poster.appointedposters.get')
    #根据频道ID获取频道信息
    poster_channel_get = bind_api(method='taobao.poster.channel.get')
    #获取画报所有频道
    poster_channels_get = bind_api(method='taobao.poster.channels.get')
    #根据画报ID获取商品
    poster_postauctions_get = bind_api(method='taobao.poster.postauctions.get')
    #获取画报详情
    poster_posterdetail_get = bind_api(method='taobao.poster.posterdetail.get')
    #获取指定频道Id的画报列表
    poster_posters_get = bind_api(method='taobao.poster.posters.get')
    #搜索画报
    poster_posters_search = bind_api(method='taobao.poster.posters.search')

    #--------------------- 商品API ------------------------------

    #查询用户售后服务模板
    aftersale_get = bind_api(method='taobao.aftersale.get')
    #添加一个商品
    item_add = bind_api(method='taobao.item.add')
    #删除单条商品
    item_delete = bind_api(method='taobao.item.delete')
    #得到单个商品信息
    item_get = bind_api(method='taobao.item.get')
    #删除商品图片
    item_img_delete = bind_api(method='taobao.item.img.delete')
    #添加商品图片
    item_img_upload = bind_api(method='taobao.item.img.upload')
    #商品关联子图
    item_joint_img = bind_api(method='taobao.item.joint.img')
    #商品关联属性图
    item_joint_propimg = bind_api(method='taobao.item.joint.propimg')
    #更新商品价格
    item_price_update = bind_api(method='taobao.item.price.update')
    #删除属性图片
    item_propimg_delete = bind_api(method='taobao.item.propimg.delete')
    #添加或修改属性图片
    item_propimg_upload = bind_api(method='taobao.item.propimg.upload')
    #宝贝/SKU库存修改
    item_quantity_update = bind_api(method='taobao.item.quantity.update')
    #橱窗推荐一个商品
    item_recommend_add = bind_api(method='taobao.item.recommend.add')
    #取消橱窗推荐一个商品
    item_recommend_delete = bind_api(method='taobao.item.recommend.delete')
    #添加SKU
    item_sku_add = bind_api(method='taobao.item.sku.add')
    #删除SKU
    item_sku_delete = bind_api(method='taobao.item.sku.delete')
    #获取SKU
    item_sku_get = bind_api(method='taobao.item.sku.get')
    #更新商品SKU的价格
    item_sku_price_update = bind_api(method='taobao.item.sku.price.update')
    #更新SKU信息
    item_sku_update = bind_api(method='taobao.item.sku.update')
    #根据商品ID列表获取SKU信息
    item_skus_get = bind_api(method='taobao.item.skus.get')
    #获取用户宝贝详情页模板名称
    item_templates_get = bind_api(method='taobao.item.templates.get')
    #更新商品信息
    item_update = bind_api(method='taobao.item.update')
    #商品下架
    item_update_delisting = bind_api(method='taobao.item.update.delisting')
    #一口价商品上架
    item_update_listing = bind_api(method='taobao.item.update.listing')
    #根据外部ID取商品
    items_custom_get = bind_api(method='taobao.items.custom.get')
    #搜索商品信息
    items_get = bind_api(method='taobao.items.get')
    #得到当前会话用户库存中的商品列表
    items_inventory_get = bind_api(method='taobao.items.inventory.get')
    #批量获取商品信息
    items_list_get = bind_api(method='taobao.items.list.get')
    #获取当前会话用户出售中的商品列表
    items_onsale_get = bind_api(method='taobao.items.onsale.get')
    #搜索商品信息
    items_search = bind_api(method='taobao.items.search')
    #上传一个产品,不包括产品非主图和属性图片
    product_add = bind_api(method='taobao.product.add')
    #获取一个产品的信息
    product_get = bind_api(method='taobao.product.get')
    #删除产品非主图
    product_img_delete = bind_api(method='taobao.product.img.delete')
    #上传单张产品非主图,如果需要传多张,可调多次
    product_img_upload = bind_api(method='taobao.product.img.upload')
    #删除产品属性图
    product_propimg_delete = bind_api(method='taobao.product.propimg.delete')
    #上传单张产品属性图片,如果需要传多张,可调多次
    product_propimg_upload = bind_api(method='taobao.product.propimg.upload')
    #修改一个产品,可以修改主图,不能修改子图片
    product_update = bind_api(method='taobao.product.update')
    #获取产品列表
    products_get = bind_api(method='taobao.products.get')
    #搜索产品信息
    products_search = bind_api(method='taobao.products.search')
    #根据外部ID取商品SKU
    skus_custom_get = bind_api(method='taobao.skus.custom.get')

    #--------------------- 收藏夹API ------------------------------

    #添加收藏夹
    favorite_add = bind_api(method='taobao.favorite.add')
    #查询
    favorite_search = bind_api(method='taobao.favorite.search')

    #--------------------- 退款API ------------------------------

    #单笔退款详情
    refund_get = bind_api(method='taobao.refund.get')
    #创建退款留言/凭证
    refund_message_add = bind_api(method='taobao.refund.message.add')
    #退款留言/凭证列表查询
    refund_messages_get = bind_api(method='taobao.refund.messages.get')
    #卖家拒绝退款
    refund_refuse = bind_api(method='taobao.refund.refuse')
    #查询买家申请的退款列表
    refunds_apply_get = bind_api(method='taobao.refunds.apply.get')
    #查询卖家收到的退款列表
    refunds_receive_get = bind_api(method='taobao.refunds.receive.get')

    #--------------------- 系统时间API ------------------------------

    #--------------------- 旺旺API ------------------------------

    #平均等待时长
    wangwang_eservice_avgwaittime_get = bind_api(
        method='taobao.wangwang.eservice.avgwaittime.get')
    #获取具体的聊天记录
    wangwang_eservice_chatlog_get = bind_api(
        method='taobao.wangwang.eservice.chatlog.get')
    #获取聊天对象列表,查询时间段
    wangwang_eservice_chatpeers_get = bind_api(
        method='taobao.wangwang.eservice.chatpeers.get')
    #聊天记录查询
    wangwang_eservice_chatrecord_get = bind_api(
        method='taobao.wangwang.eservice.chatrecord.get')
    #获取评价详细
    wangwang_eservice_evals_get = bind_api(
        method='taobao.wangwang.eservice.evals.get')
    #客服评价统计
    wangwang_eservice_evaluation_get = bind_api(
        method='taobao.wangwang.eservice.evaluation.get')
    #获取组成员列表
    wangwang_eservice_groupmember_get = bind_api(
        method='taobao.wangwang.eservice.groupmember.get')
    #获取登录日志
    wangwang_eservice_loginlogs_get = bind_api(
        method='taobao.wangwang.eservice.loginlogs.get')
    #客服未回复人数
    wangwang_eservice_noreplynum_get = bind_api(
        method='taobao.wangwang.eservice.noreplynum.get')
    #日累计在线时长
    wangwang_eservice_onlinetime_get = bind_api(
        method='taobao.wangwang.eservice.onlinetime.get')
    #客服接待数
    wangwang_eservice_receivenum_get = bind_api(
        method='taobao.wangwang.eservice.receivenum.get')
    #获取分流权重接口
    wangwang_eservice_streamweigths_get = bind_api(
        method='taobao.wangwang.eservice.streamweigths.get')

    #--------------------- 主动通知业务API ------------------------------

    #开通增量消息服务
    increment_customer_permit = bind_api(
        method='taobao.increment.customer.permit')
    #关闭用户的增量消息服务
    increment_customer_stop = bind_api(method='taobao.increment.customer.stop')
    #查询应用为用户开通的增量消息服务
    increment_customers_get = bind_api(method='taobao.increment.customers.get')
    #获取商品变更通知信息
    increment_items_get = bind_api(method='taobao.increment.items.get')
    #获取退款变更通知信息
    increment_refunds_get = bind_api(method='taobao.increment.refunds.get')
    #获取交易和评价变更通知信息
    increment_trades_get = bind_api(method='taobao.increment.trades.get')

    #--------------------- 类目API ------------------------------

    #查询B商家被授权品牌列表和类目列表
    itemcats_authorize_get = bind_api(method='taobao.itemcats.authorize.get')
    #获取后台供卖家发布商品的标准商品类目
    itemcats_get = bind_api(method='taobao.itemcats.get')
    #获取标准商品类目属性
    itemprops_get = bind_api(method='taobao.itemprops.get')
    #获取标准类目属性值
    itempropvalues_get = bind_api(method='taobao.itempropvalues.get')

    #--------------------- 店铺API ------------------------------

    #添加卖家自定义类目
    sellercats_list_add = bind_api(method='taobao.sellercats.list.add')
    #获取前台展示的店铺内卖家自定义商品类目
    sellercats_list_get = bind_api(method='taobao.sellercats.list.get')
    #更新卖家自定义类目
    sellercats_list_update = bind_api(method='taobao.sellercats.list.update')
    #获取卖家店铺的基本信息
    shop_get = bind_api(method='taobao.shop.get')
    #获取卖家店铺剩余橱窗数量
    shop_remainshowcase_get = bind_api(method='taobao.shop.remainshowcase.get')
    #更新店铺基本信息
    shop_update = bind_api(method='taobao.shop.update')
    #获取前台展示的店铺类目
    shopcats_list_get = bind_api(method='taobao.shopcats.list.get')

    #--------------------- 淘花API ------------------------------

    #有声读物专辑详情
    taohua_audioreader_album_get = bind_api(
        method='taobao.taohua.audioreader.album.get')
    #获取我的有声书库专辑列表
    taohua_audioreader_myalbums_get = bind_api(
        method='taobao.taohua.audioreader.myalbums.get')
    #获取我的有声书库单曲列表
    taohua_audioreader_mytracks_get = bind_api(
        method='taobao.taohua.audioreader.mytracks.get')
    #获取花匠推荐的有声读物专辑列表
    taohua_audioreader_recommend_get = bind_api(
        method='taobao.taohua.audioreader.recommend.get')
    #搜索有声读物专辑
    taohua_audioreader_search = bind_api(
        method='taobao.taohua.audioreader.search')
    #有声读物单曲试听地址
    taohua_audioreader_track_auditionurl_get = bind_api(
        method='taobao.taohua.audioreader.track.auditionurl.get')
    #有声读物单曲下载地址
    taohua_audioreader_track_downloadurl_get = bind_api(
        method='taobao.taohua.audioreader.track.downloadurl.get')
    #有声读物单曲详情
    taohua_audioreader_tracks_get = bind_api(
        method='taobao.taohua.audioreader.tracks.get')
    #用户是否购买过该商品
    taohua_boughtitem_is = bind_api(method='taobao.taohua.boughtitem.is')
    #获取子类目列表
    taohua_childcates_get = bind_api(method='taobao.taohua.childcates.get')
    #获取文档目录
    taohua_directory_get = bind_api(method='taobao.taohua.directory.get')
    #我喜欢商品
    taohua_item_like = bind_api(method='taobao.taohua.item.like')
    #对指定商品进行评论
    taohua_itemcomment_add = bind_api(method='taobao.taohua.itemcomment.add')
    #获取淘花指定商品的评论列表
    taohua_itemcomments_get = bind_api(method='taobao.taohua.itemcomments.get')
    #文档详情
    taohua_itemdetail_get = bind_api(method='taobao.taohua.itemdetail.get')
    #获取商品支付链接
    taohua_itempayurl_get = bind_api(method='taobao.taohua.itempayurl.get')
    #获取商品资源下载地址
    taohua_itemresurl_get = bind_api(method='taobao.taohua.itemresurl.get')
    #商品搜索列表接口
    taohua_items_search = bind_api(method='taobao.taohua.items.search')
    #获取最新的更新信息
    taohua_latestupdateinfo_get = bind_api(
        method='taobao.taohua.latestupdateinfo.get')
    #查询买家订单列表
    taohua_orders_get = bind_api(method='taobao.taohua.orders.get')
    #获取商品预览链接
    taohua_previewurl_get = bind_api(method='taobao.taohua.previewurl.get')
    #获取小二推荐的商品
    taohua_staffrecitems_get = bind_api(
        method='taobao.taohua.staffrecitems.get')

    #--------------------- 媒体平台API ------------------------------

    #新增图片分类信息
    picture_category_add = bind_api(method='taobao.picture.category.add')
    #获取图片分类信息
    picture_category_get = bind_api(method='taobao.picture.category.get')
    #删除图片空间图片
    picture_delete = bind_api(method='taobao.picture.delete')
    #获取图片信息
    picture_get = bind_api(method='taobao.picture.get')
    #上传单张图片
    picture_upload = bind_api(method='taobao.picture.upload')

    #--------------------- 分销API ------------------------------

    #获取供应商的合作关系信息
    fenxiao_cooperation_get = bind_api(method='taobao.fenxiao.cooperation.get')
    #更新合作关系等级
    fenxiao_cooperation_update = bind_api(
        method='taobao.fenxiao.cooperation.update')
    #新增等级折扣
    fenxiao_discount_add = bind_api(method='taobao.fenxiao.discount.add')
    #修改等级折扣
    fenxiao_discount_update = bind_api(method='taobao.fenxiao.discount.update')
    #获取折扣信息
    fenxiao_discounts_get = bind_api(method='taobao.fenxiao.discounts.get')
    #查询商品下载记录
    fenxiao_distributor_items_get = bind_api(
        method='taobao.fenxiao.distributor.items.get')
    #获取分销商信息
    fenxiao_distributors_get = bind_api(
        method='taobao.fenxiao.distributors.get')
    #分销商等级查询
    fenxiao_grades_get = bind_api(method='taobao.fenxiao.grades.get')
    #获取分销用户登录信息
    fenxiao_login_user_get = bind_api(method='taobao.fenxiao.login.user.get')
    #确认收款
    fenxiao_order_confirm_paid = bind_api(
        method='taobao.fenxiao.order.confirm.paid')
    #查询采购单信息
    fenxiao_orders_get = bind_api(method='taobao.fenxiao.orders.get')
    #添加产品
    fenxiao_product_add = bind_api(method='taobao.fenxiao.product.add')
    #更新产品
    fenxiao_product_update = bind_api(method='taobao.fenxiao.product.update')
    #查询产品线列表
    fenxiao_productcats_get = bind_api(method='taobao.fenxiao.productcats.get')
    #查询产品列表
    fenxiao_products_get = bind_api(method='taobao.fenxiao.products.get')

    #--------------------- 店铺会员管理API ------------------------------

    #卖家查询等级规则
    crm_grade_get = bind_api(method='taobao.crm.grade.get')
    #卖家创建一个分组
    crm_group_add = bind_api(method='taobao.crm.group.add')
    #将一个分组添加到另外一个分组
    crm_group_append = bind_api(method='taobao.crm.group.append')
    #删除分组
    crm_group_delete = bind_api(method='taobao.crm.group.delete')
    #分组移动
    crm_group_move = bind_api(method='taobao.crm.group.move')
    #修改一个已经存在的分组
    crm_group_update = bind_api(method='taobao.crm.group.update')
    #查询卖家的分组
    crm_groups_get = bind_api(method='taobao.crm.groups.get')
    #查询分组任务是否完成
    crm_grouptask_check = bind_api(method='taobao.crm.grouptask.check')
    #编辑会员资料
    crm_memberinfo_update = bind_api(method='taobao.crm.memberinfo.update')
    #获取卖家的会员(基本查询)
    crm_members_get = bind_api(method='taobao.crm.members.get')
    #给一批会员添加一个分组
    crm_members_group_batchadd = bind_api(
        method='taobao.crm.members.group.batchadd')
    #批量删除分组
    crm_members_groups_batchdelete = bind_api(
        method='taobao.crm.members.groups.batchdelete')
    #增量获取卖家会员
    crm_members_increment_get = bind_api(
        method='taobao.crm.members.increment.get')
    #获取卖家会员(高级查询)
    crm_members_search = bind_api(method='taobao.crm.members.search')
    #分组规则添加
    crm_rule_add = bind_api(method='taobao.crm.rule.add')
    #分组规则删除
    crm_rule_delete = bind_api(method='taobao.crm.rule.delete')
    #设置规则适用的分组
    crm_rule_group_set = bind_api(method='taobao.crm.rule.group.set')
    #获取规则
    crm_rules_get = bind_api(method='taobao.crm.rules.get')
    #卖家取消店铺vip的优惠
    crm_shopvip_cancel = bind_api(method='taobao.crm.shopvip.cancel')

    #--------------------- 聚划算API ------------------------------

    #根据类目获取商品Id列表
    ju_catitemids_get = bind_api(method='taobao.ju.catitemids.get')
    #获取当日的生活服务类城市
    ju_cities_get = bind_api(method='taobao.ju.cities.get')
    #获取生活服务类的团信息接口
    ju_citygroup_get = bind_api(method='taobao.ju.citygroup.get')
    #根据城市获取生活服务团商品
    ju_cityitems_get = bind_api(method='taobao.ju.cityitems.get')
    #根据终端类型分配团
    ju_group_assign = bind_api(method='taobao.ju.group.assign')
    #根据团id获取团对象
    ju_group_get = bind_api(method='taobao.ju.group.get')
    #根据终端类型获取组id列表
    ju_groupids_get = bind_api(method='taobao.ju.groupids.get')
    #根据终端类型和平台ID获取商品id列表
    ju_itemids_get = bind_api(method='taobao.ju.itemids.get')
    #根据商品id列表获取商品列表
    ju_items_get = bind_api(method='taobao.ju.items.get')
    #根据终端类型随机分配一个今天的商品列表
    ju_todayitems_get = bind_api(method='taobao.ju.todayitems.get')

    #--------------------- 无线画报API ------------------------------

    #取频道信息
    huabao_channel_get = bind_api(method='taobao.huabao.channel.get')
    #取画报频道
    huabao_channels_get = bind_api(method='taobao.huabao.channels.get')
    #取画报详情
    huabao_poster_get = bind_api(method='taobao.huabao.poster.get')
    #取得画报相关商品信息
    huabao_poster_goodsinfo_get = bind_api(
        method='taobao.huabao.poster.goodsinfo.get')
    #取指定频道Id的画报列表
    huabao_posters_get = bind_api(method='taobao.huabao.posters.get')
    #获取指定画报列表
    huabao_specialposters_get = bind_api(
        method='taobao.huabao.specialposters.get')

    #--------------------- 子账号管理API ------------------------------

    #查询指定账户的子账号列表
    sellercenter_subusers_get = bind_api(
        method='taobao.sellercenter.subusers.get')

    #--------------------- 酒店API ------------------------------

    #酒店发布接口
    hotel_add = bind_api(method='taobao.hotel.add')
    #单酒店查询接口
    hotel_get = bind_api(method='taobao.hotel.get')
    #根据酒店名称/别名获得对应酒店
    hotel_name_get = bind_api(method='taobao.hotel.name.get')
    #单订单查询接口
    hotel_order_get = bind_api(method='taobao.hotel.order.get')
    #多订单查询接口
    hotel_orders_search = bind_api(method='taobao.hotel.orders.search')
    #商品发布接口
    hotel_room_add = bind_api(method='taobao.hotel.room.add')
    #单商品查询接口
    hotel_room_get = bind_api(method='taobao.hotel.room.get')
    #商品图片删除接口
    hotel_room_img_delete = bind_api(method='taobao.hotel.room.img.delete')
    #商品图片上传接口
    hotel_room_img_upload = bind_api(method='taobao.hotel.room.img.upload')
    #商品更新接口
    hotel_room_update = bind_api(method='taobao.hotel.room.update')
    #多商品查询接口
    hotel_rooms_search = bind_api(method='taobao.hotel.rooms.search')
    #酒店发布者发布酒店增量查询接口
    hotel_sold_hotels_increment_get = bind_api(
        method='taobao.hotel.sold.hotels.increment.get')
    #搜索当前会话用户作为卖家已卖出的增量交易数据
    hotel_sold_orders_increment_get = bind_api(
        method='taobao.hotel.sold.orders.increment.get')
    #房型发布者发布房型增量查询接口
    hotel_sold_types_increment_get = bind_api(
        method='taobao.hotel.sold.types.increment.get')
    #房型发布接口
    hotel_type_add = bind_api(method='taobao.hotel.type.add')
    #根据房型名称/别名获得对应房型
    hotel_type_name_get = bind_api(method='taobao.hotel.type.name.get')
    #酒店更新接口
    hotel_update = bind_api(method='taobao.hotel.update')
    #多酒店查询接口
    hotels_search = bind_api(method='taobao.hotels.search')

    #--------------------- 用户API ------------------------------

    #获取单个用户信息
    user_get = bind_api(method='taobao.user.get')
    #获取多个用户信息
    users_get = bind_api(method='taobao.users.get')

    #--------------------- 淘代码API ------------------------------

    #获取淘代码相关信息
    taocode_get = bind_api(method='taobao.taocode.get')
예제 #48
0
파일: api.py 프로젝트: redu/redupy
class Redu(object):
    def __init__(self,
                 consumer_key,
                 consumer_secret,
                 pin=None,
                 model_factory=None,
                 base_url="http://redu.com.br/api/"):
        self.client = HttpClient(consumer_key, consumer_secret, pin)
        self.base_url = base_url
        self.model_factory = model_factory or ModelFactory

    def getAuthorizeUrl(self):
        return self.client.getAuthorizeUrl()

    def initClient(self, pin):
        self.client.initClient(pin)

    getMe = bind_api(path="me", mehtod="get", payload_type="user")

    getUser = bind_api(path="users/{0}", method="get", payload_type="user")

    getUserBySpace = bind_api(path="spaces/{0}/users",
                              method="get",
                              payload_type="user")

    getEnvironment = bind_api(path="environments/{0}",
                              method="get",
                              payload_type="environment")

    postEnvironment = bind_api(
        path="environments",
        method="post",
        payload_type="environment",
        payload_params=["name", "path", "initials", "description"])

    editEnvironment = bind_api(
        path="environments/{0}",
        method="put",
        send_type="environment",
        payload_params=["name", "path", "initials", "description"])

    deleteEnvironment = bind_api(path="environments/{0}", method="delete")

    getSubjectsBySpace = bind_api(path="spaces/{0}/subjects",
                                  method="get",
                                  payload_type="subject")

    getSubject = bind_api(path="subjects/{0}",
                          method="get",
                          payload_type="subject")

    getSpace = bind_api(path="spaces/{0}", method="get", payload_type="space")

    editSpace = bind_api(path="spaces/{0}",
                         method="put",
                         payload_params=['name', 'description'],
                         send_type="space")

    postSpace = bind_api(path="courses/{0}/spaces",
                         method="post",
                         payload_type='space',
                         payload_params=['name', 'description'])

    getSpaceByCourse = bind_api(path="courses/{0}/spaces",
                                method="get",
                                payload_type="space")

    deleteSpace = bind_api(path="spaces/{0}", method="delete")

    getStatus = bind_api(path="statuses/{0}",
                         method="get",
                         payload_type="status")

    getAnswers = bind_api(path="statuses/{0}/answers",
                          method="get",
                          payload_type="status")

    postAnswer = bind_api(path="statuses/{0}/answers",
                          method="post",
                          payload_type="status",
                          payload_params=["text"])

    getStatusByUser = bind_api(path="users/{0}/statuses",
                               method="get",
                               payload_type="status",
                               querry_params=["type", "page"])

    getTimelineByUser = bind_api(path="users/{0}/statuses/timeline",
                                 method="get",
                                 payload_type="status",
                                 querry_params=["type", "page"])

    postStatusUser = bind_api(path="users/{0}/statuses",
                              method="post",
                              payload_type="status",
                              payload_params=["text"])

    getTimelineBySpace = bind_api(path="spaces/{0}/statuses/timeline",
                                  method="get",
                                  payload_type="status",
                                  querry_params=["type", "page"])

    getStatusBySpace = bind_api(path="spaces/{0}/statuses",
                                method="get",
                                payload_type="status",
                                querry_params=["type", "page"])

    postStatusSpace = bind_api(path="spaces/{0}/statuses",
                               method="post",
                               payload_type="status",
                               payload_params=["text"])

    getStatusByLecture = bind_api(path="lectures/{0}/statuses",
                                  method="get",
                                  payload_type="status",
                                  querry_params=["type", "page"])

    postStatusLecture = bind_api(path="lectures/{0}/statuses",
                                 method="post",
                                 payload_type="status",
                                 payload_params=["text"])

    deleteStatus = bind_api(path="statuses/{0}", method="delete")

    getCourse = bind_api(path="courses/{0}",
                         method="get",
                         payload_type="course")

    postCourse = bind_api(
        path="environments/{0}/courses",
        method="post",
        payload_type="course",
        payload_params=["name", "path", "description", "workload"])

    editCourse = bind_api(
        path="courses/{0}",
        method="put",
        send_type="course",
        payload_params=["name", "path", "description", "workload"])

    getCoursesByEnvironment = bind_api(path="environments/{0}/courses",
                                       method="get",
                                       payload_type="course")

    deleteCourse = bind_api(path="courses/{0}", method="delete")

    getEnrollment = bind_api(path="enrollments/{0}",
                             method="get",
                             payload_type="enrollment")

    postEnrollment = bind_api(path="courses/{0}/enrollments",
                              method="post",
                              payload_type="enrollment",
                              payload_params=["email"])

    getEnrolmentsByCourse = bind_api(path="courses/{0}/enrollments",
                                     method="get",
                                     payload_type="enrollment")

    deleteEnrollment = bind_api(path="enrollments/{0}", method="delete")

    getChatsByUser = bind_api(path='users/{0}/chats',
                              method='get',
                              payload_type='chat')

    getChat = bind_api(path='chats/{0}', method='get', payload_type='chat')

    getChatMessagesByChat = bind_api(path='chats/{0}/chat_messages',
                                     method='get',
                                     payload_type='chat_message')

    getChatMessage = bind_api(path='chat_messages/{0}',
                              method='get',
                              payload_type='chat_message')
예제 #49
0
class API(object):
    """Twitter API"""
    def __init__(self,
                 auth_handler=None,
                 host='api.twitter.com',
                 search_host='search.twitter.com',
                 cache=None,
                 secure=False,
                 api_root='/1',
                 search_root='',
                 retry_count=0,
                 retry_delay=0,
                 retry_errors=None,
                 parser=None):
        self.auth = auth_handler
        self.host = host
        self.search_host = search_host
        self.api_root = api_root
        self.search_root = search_root
        self.cache = cache
        self.secure = secure
        self.retry_count = retry_count
        self.retry_delay = retry_delay
        self.retry_errors = retry_errors
        self.parser = parser or ModelParser()

    """ statuses/public_timeline """
    public_timeline = bind_api(path='/statuses/public_timeline.json',
                               payload_type='status',
                               payload_list=True,
                               allowed_param=[])
    """ statuses/home_timeline """
    home_timeline = bind_api(
        path='/statuses/home_timeline.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/friends_timeline """
    friends_timeline = bind_api(
        path='/statuses/friends_timeline.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/user_timeline """
    user_timeline = bind_api(path='/statuses/user_timeline.json',
                             payload_type='status',
                             payload_list=True,
                             allowed_param=[
                                 'id', 'user_id', 'screen_name', 'since_id',
                                 'max_id', 'count', 'page', 'include_rts'
                             ])
    """ statuses/mentions """
    mentions = bind_api(path='/statuses/mentions.json',
                        payload_type='status',
                        payload_list=True,
                        allowed_param=['since_id', 'max_id', 'count', 'page'],
                        require_auth=True)
    """/statuses/:id/retweeted_by.format"""
    retweeted_by = bind_api(path='/statuses/{id}/retweeted_by.json',
                            payload_type='status',
                            payload_list=True,
                            allowed_param=['id', 'count', 'page'],
                            require_auth=True)
    """/statuses/:id/retweeted_by/ids.format"""
    retweeted_by_ids = bind_api(path='/statuses/{id}/retweeted_by/ids.json',
                                payload_type='ids',
                                allowed_param=['id', 'count', 'page'],
                                require_auth=True)
    """ statuses/retweeted_by_me """
    retweeted_by_me = bind_api(
        path='/statuses/retweeted_by_me.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/retweeted_to_me """
    retweeted_to_me = bind_api(
        path='/statuses/retweeted_to_me.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/retweets_of_me """
    retweets_of_me = bind_api(
        path='/statuses/retweets_of_me.json',
        payload_type='status',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ statuses/show """
    get_status = bind_api(path='/statuses/show.json',
                          payload_type='status',
                          allowed_param=['id'])
    """ statuses/update """
    update_status = bind_api(path='/statuses/update.json',
                             method='POST',
                             payload_type='status',
                             allowed_param=[
                                 'status', 'in_reply_to_status_id', 'lat',
                                 'long', 'source', 'place_id'
                             ],
                             require_auth=True)
    """ statuses/destroy """
    destroy_status = bind_api(path='/statuses/destroy.json',
                              method='DELETE',
                              payload_type='status',
                              allowed_param=['id'],
                              require_auth=True)
    """ statuses/retweet """
    retweet = bind_api(path='/statuses/retweet/{id}.json',
                       method='POST',
                       payload_type='status',
                       allowed_param=['id'],
                       require_auth=True)
    """ statuses/retweets """
    retweets = bind_api(path='/statuses/retweets/{id}.json',
                        payload_type='status',
                        payload_list=True,
                        allowed_param=['id', 'count'],
                        require_auth=True)
    """ users/show """
    get_user = bind_api(path='/users/show.json',
                        payload_type='user',
                        allowed_param=['id', 'user_id', 'screen_name'])
    """ Perform bulk look up of users from user ID or screenname """

    def lookup_users(self, user_ids=None, screen_names=None):
        return self._lookup_users(list_to_csv(user_ids),
                                  list_to_csv(screen_names))

    _lookup_users = bind_api(path='/users/lookup.json',
                             payload_type='user',
                             payload_list=True,
                             allowed_param=['user_id', 'screen_name'],
                             require_auth=True)
    """ Get the authenticated user """

    def me(self):
        return self.get_user(screen_name=self.auth.get_username())

    """ users/search """
    search_users = bind_api(path='/users/search.json',
                            payload_type='user',
                            payload_list=True,
                            require_auth=True,
                            allowed_param=['q', 'per_page', 'page'])
    """ statuses/friends """
    friends = bind_api(
        path='/statuses/friends.json',
        payload_type='user',
        payload_list=True,
        allowed_param=['id', 'user_id', 'screen_name', 'page', 'cursor'])
    """ statuses/followers """
    followers = bind_api(
        path='/statuses/followers.json',
        payload_type='user',
        payload_list=True,
        allowed_param=['id', 'user_id', 'screen_name', 'page', 'cursor'])
    """ direct_messages """
    direct_messages = bind_api(
        path='/direct_messages.json',
        payload_type='direct_message',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ direct_messages/sent """
    sent_direct_messages = bind_api(
        path='/direct_messages/sent.json',
        payload_type='direct_message',
        payload_list=True,
        allowed_param=['since_id', 'max_id', 'count', 'page'],
        require_auth=True)
    """ direct_messages/new """
    send_direct_message = bind_api(
        path='/direct_messages/new.json',
        method='POST',
        payload_type='direct_message',
        allowed_param=['user', 'screen_name', 'user_id', 'text'],
        require_auth=True)
    """ direct_messages/destroy """
    destroy_direct_message = bind_api(path='/direct_messages/destroy.json',
                                      method='DELETE',
                                      payload_type='direct_message',
                                      allowed_param=['id'],
                                      require_auth=True)
    """ friendships/create """
    create_friendship = bind_api(
        path='/friendships/create.json',
        method='POST',
        payload_type='user',
        allowed_param=['id', 'user_id', 'screen_name', 'follow'],
        require_auth=True)
    """ friendships/destroy """
    destroy_friendship = bind_api(
        path='/friendships/destroy.json',
        method='DELETE',
        payload_type='user',
        allowed_param=['id', 'user_id', 'screen_name'],
        require_auth=True)
    """ friendships/exists """
    exists_friendship = bind_api(path='/friendships/exists.json',
                                 payload_type='json',
                                 allowed_param=['user_a', 'user_b'])
    """ friendships/show """
    show_friendship = bind_api(path='/friendships/show.json',
                               payload_type='friendship',
                               allowed_param=[
                                   'source_id', 'source_screen_name',
                                   'target_id', 'target_screen_name'
                               ])
    """ friends/ids """
    friends_ids = bind_api(
        path='/friends/ids.json',
        payload_type='ids',
        allowed_param=['id', 'user_id', 'screen_name', 'cursor'])
    """ friendships/incoming """
    friendships_incoming = bind_api(path='/friendships/incoming.json',
                                    payload_type='ids',
                                    allowed_param=['cursor'])
    """ friendships/outgoing"""
    friendships_outgoing = bind_api(path='/friendships/outgoing.json',
                                    payload_type='ids',
                                    allowed_param=['cursor'])
    """ followers/ids """
    followers_ids = bind_api(
        path='/followers/ids.json',
        payload_type='ids',
        allowed_param=['id', 'user_id', 'screen_name', 'cursor'])
    """ account/verify_credentials """

    def verify_credentials(self):
        try:
            return bind_api(path='/account/verify_credentials.json',
                            payload_type='user',
                            require_auth=True)(self)
        except TweepError:
            return False

    """ account/rate_limit_status """
    rate_limit_status = bind_api(path='/account/rate_limit_status.json',
                                 payload_type='json')
    """ account/update_delivery_device """
    set_delivery_device = bind_api(path='/account/update_delivery_device.json',
                                   method='POST',
                                   allowed_param=['device'],
                                   payload_type='user',
                                   require_auth=True)
    """ account/update_profile_colors """
    update_profile_colors = bind_api(
        path='/account/update_profile_colors.json',
        method='POST',
        payload_type='user',
        allowed_param=[
            'profile_background_color', 'profile_text_color',
            'profile_link_color', 'profile_sidebar_fill_color',
            'profile_sidebar_border_color'
        ],
        require_auth=True)
    """ account/update_profile_image """

    def update_profile_image(self, filename):
        headers, post_data = API._pack_image(filename, 700)
        return bind_api(path='/account/update_profile_image.json',
                        method='POST',
                        payload_type='user',
                        require_auth=True)(self,
                                           post_data=post_data,
                                           headers=headers)

    """ account/update_profile_background_image """

    def update_profile_background_image(self, filename, *args, **kargs):
        headers, post_data = API._pack_image(filename, 800)
        bind_api(path='/account/update_profile_background_image.json',
                 method='POST',
                 payload_type='user',
                 allowed_param=['tile'],
                 require_auth=True)(self, post_data=post_data, headers=headers)

    """ account/update_profile """
    update_profile = bind_api(
        path='/account/update_profile.json',
        method='POST',
        payload_type='user',
        allowed_param=['name', 'url', 'location', 'description'],
        require_auth=True)
    """ favorites """
    favorites = bind_api(path='/favorites.json',
                         payload_type='status',
                         payload_list=True,
                         allowed_param=['id', 'page'])
    """ favorites/create """
    create_favorite = bind_api(path='/favorites/create/{id}.json',
                               method='POST',
                               payload_type='status',
                               allowed_param=['id'],
                               require_auth=True)
    """ favorites/destroy """
    destroy_favorite = bind_api(path='/favorites/destroy/{id}.json',
                                method='DELETE',
                                payload_type='status',
                                allowed_param=['id'],
                                require_auth=True)
    """ notifications/follow """
    enable_notifications = bind_api(
        path='/notifications/follow.json',
        method='POST',
        payload_type='user',
        allowed_param=['id', 'user_id', 'screen_name'],
        require_auth=True)
    """ notifications/leave """
    disable_notifications = bind_api(
        path='/notifications/leave.json',
        method='POST',
        payload_type='user',
        allowed_param=['id', 'user_id', 'screen_name'],
        require_auth=True)
    """ blocks/create """
    create_block = bind_api(path='/blocks/create.json',
                            method='POST',
                            payload_type='user',
                            allowed_param=['id', 'user_id', 'screen_name'],
                            require_auth=True)
    """ blocks/destroy """
    destroy_block = bind_api(path='/blocks/destroy.json',
                             method='DELETE',
                             payload_type='user',
                             allowed_param=['id', 'user_id', 'screen_name'],
                             require_auth=True)
    """ blocks/exists """

    def exists_block(self, *args, **kargs):
        try:
            bind_api(path='/blocks/exists.json',
                     allowed_param=['id', 'user_id', 'screen_name'],
                     require_auth=True)(self, *args, **kargs)
        except TweepError:
            return False
        return True

    """ blocks/blocking """
    blocks = bind_api(path='/blocks/blocking.json',
                      payload_type='user',
                      payload_list=True,
                      allowed_param=['page'],
                      require_auth=True)
    """ blocks/blocking/ids """
    blocks_ids = bind_api(path='/blocks/blocking/ids.json',
                          payload_type='json',
                          require_auth=True)
    """ report_spam """
    report_spam = bind_api(path='/report_spam.json',
                           method='POST',
                           payload_type='user',
                           allowed_param=['id', 'user_id', 'screen_name'],
                           require_auth=True)
    """ saved_searches """
    saved_searches = bind_api(path='/saved_searches.json',
                              payload_type='saved_search',
                              payload_list=True,
                              require_auth=True)
    """ saved_searches/show """
    get_saved_search = bind_api(path='/saved_searches/show/{id}.json',
                                payload_type='saved_search',
                                allowed_param=['id'],
                                require_auth=True)
    """ saved_searches/create """
    create_saved_search = bind_api(path='/saved_searches/create.json',
                                   method='POST',
                                   payload_type='saved_search',
                                   allowed_param=['query'],
                                   require_auth=True)
    """ saved_searches/destroy """
    destroy_saved_search = bind_api(path='/saved_searches/destroy/{id}.json',
                                    method='DELETE',
                                    payload_type='saved_search',
                                    allowed_param=['id'],
                                    require_auth=True)
    """ help/test """

    def test(self):
        try:
            bind_api(path='/help/test.json', )(self)
        except TweepError:
            return False
        return True

    def create_list(self, *args, **kargs):
        return bind_api(path='/%s/lists.json' % self.auth.get_username(),
                        method='POST',
                        payload_type='list',
                        allowed_param=['name', 'mode', 'description'],
                        require_auth=True)(self, *args, **kargs)

    def destroy_list(self, slug):
        return bind_api(path='/%s/lists/%s.json' %
                        (self.auth.get_username(), slug),
                        method='DELETE',
                        payload_type='list',
                        require_auth=True)(self)

    def update_list(self, slug, *args, **kargs):
        return bind_api(path='/%s/lists/%s.json' %
                        (self.auth.get_username(), slug),
                        method='POST',
                        payload_type='list',
                        allowed_param=['name', 'mode', 'description'],
                        require_auth=True)(self, *args, **kargs)

    lists = bind_api(path='/{user}/lists.json',
                     payload_type='list',
                     payload_list=True,
                     allowed_param=['user', 'cursor'],
                     require_auth=True)

    lists_memberships = bind_api(path='/{user}/lists/memberships.json',
                                 payload_type='list',
                                 payload_list=True,
                                 allowed_param=['user', 'cursor'],
                                 require_auth=True)

    lists_subscriptions = bind_api(path='/{user}/lists/subscriptions.json',
                                   payload_type='list',
                                   payload_list=True,
                                   allowed_param=['user', 'cursor'],
                                   require_auth=True)

    list_timeline = bind_api(path='/{owner}/lists/{slug}/statuses.json',
                             payload_type='status',
                             payload_list=True,
                             allowed_param=[
                                 'owner', 'slug', 'since_id', 'max_id',
                                 'per_page', 'page'
                             ])

    get_list = bind_api(path='/{owner}/lists/{slug}.json',
                        payload_type='list',
                        allowed_param=['owner', 'slug'])

    def add_list_member(self, slug, *args, **kargs):
        return bind_api(path='/%s/%s/members.json' %
                        (self.auth.get_username(), slug),
                        method='POST',
                        payload_type='list',
                        allowed_param=['id'],
                        require_auth=True)(self, *args, **kargs)

    def remove_list_member(self, slug, *args, **kargs):
        return bind_api(path='/%s/%s/members.json' %
                        (self.auth.get_username(), slug),
                        method='DELETE',
                        payload_type='list',
                        allowed_param=['id'],
                        require_auth=True)(self, *args, **kargs)

    list_members = bind_api(path='/{owner}/{slug}/members.json',
                            payload_type='user',
                            payload_list=True,
                            allowed_param=['owner', 'slug', 'cursor'])

    def is_list_member(self, owner, slug, user_id):
        try:
            return bind_api(path='/%s/%s/members/%s.json' %
                            (owner, slug, user_id),
                            payload_type='user')(self)
        except TweepError:
            return False

    subscribe_list = bind_api(path='/{owner}/{slug}/subscribers.json',
                              method='POST',
                              payload_type='list',
                              allowed_param=['owner', 'slug'],
                              require_auth=True)

    unsubscribe_list = bind_api(path='/{owner}/{slug}/subscribers.json',
                                method='DELETE',
                                payload_type='list',
                                allowed_param=['owner', 'slug'],
                                require_auth=True)

    list_subscribers = bind_api(path='/{owner}/{slug}/subscribers.json',
                                payload_type='user',
                                payload_list=True,
                                allowed_param=['owner', 'slug', 'cursor'])

    def is_subscribed_list(self, owner, slug, user_id):
        try:
            return bind_api(path='/%s/%s/subscribers/%s.json' %
                            (owner, slug, user_id),
                            payload_type='user')(self)
        except TweepError:
            return False

    """ trends/available """
    trends_available = bind_api(path='/trends/available.json',
                                payload_type='json',
                                allowed_param=['lat', 'long'])
    """ trends/location """
    trends_location = bind_api(path='/trends/{woeid}.json',
                               payload_type='json',
                               allowed_param=['woeid'])
    """ search """
    search = bind_api(search_api=True,
                      path='/search.json',
                      payload_type='search_result',
                      payload_list=True,
                      allowed_param=[
                          'q', 'lang', 'locale', 'rpp', 'page', 'since_id',
                          'geocode', 'show_user', 'max_id', 'since', 'until',
                          'result_type'
                      ])
    search.pagination_mode = 'page'
    """ trends """
    trends = bind_api(path='/trends.json', payload_type='json')
    """ trends/current """
    trends_current = bind_api(path='/trends/current.json',
                              payload_type='json',
                              allowed_param=['exclude'])
    """ trends/daily """
    trends_daily = bind_api(path='/trends/daily.json',
                            payload_type='json',
                            allowed_param=['date', 'exclude'])
    """ trends/weekly """
    trends_weekly = bind_api(path='/trends/weekly.json',
                             payload_type='json',
                             allowed_param=['date', 'exclude'])
    """ geo/reverse_geocode """
    reverse_geocode = bind_api(path='/geo/reverse_geocode.json',
                               payload_type='json',
                               allowed_param=[
                                   'lat', 'long', 'accuracy', 'granularity',
                                   'max_results'
                               ])
    """ geo/nearby_places """
    nearby_places = bind_api(path='/geo/nearby_places.json',
                             payload_type='json',
                             allowed_param=[
                                 'lat', 'long', 'ip', 'accuracy',
                                 'granularity', 'max_results'
                             ])
    """ geo/id """
    geo_id = bind_api(path='/geo/id/{id}.json',
                      payload_type='json',
                      allowed_param=['id'])
    """ Internal use only """

    @staticmethod
    def _pack_image(filename, max_size):
        """Pack image from file into multipart-formdata post body"""
        # image must be less than 700kb in size
        try:
            if os.path.getsize(filename) > (max_size * 1024):
                raise TweepError('File is too big, must be less than 700kb.')
        except os.error, e:
            raise TweepError('Unable to access file')

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise TweepError('Could not determine file type')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise TweepError('Invalid file type for image: %s' % file_type)

        # build the mulitpart-formdata body
        fp = open(filename, 'rb')
        BOUNDARY = 'Tw3ePy'
        body = []
        body.append('--' + BOUNDARY)
        body.append(
            'Content-Disposition: form-data; name="image"; filename="%s"' %
            filename)
        body.append('Content-Type: %s' % file_type)
        body.append('')
        body.append(fp.read())
        body.append('--' + BOUNDARY + '--')
        body.append('')
        fp.close()
        body = '\r\n'.join(body)

        # build headers
        headers = {
            'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
            'Content-Length': len(body)
        }

        return headers, body