class _Callable(object):
def __init__(self, client, name):
self._client = client
self._name = name
def __getattr__(self, attr):
if attr=='get':
return _Executable(self._client, 'GET', self._name)
if attr=='post':
return _Executable(self._client, 'POST', self._name)
name = '%s/%s' % (self._name, attr)
print name
return _Callable(self._client, name)
def __str__(self):
return '_Callable (%s)' % self._name
这是一个递归函数
当调用比如user.show.get 构成了多层的属性访问
重写__getattr__逐级转化成user/show 直到遇见get或post,来执行请求
class _Executable(object):
def __init__(self, client, method, path):
self._client = client
self._method = method
self._path = path
def __call__(self, **kw):
method = _METHOD_MAP[self._method]
if method==_HTTP_POST and 'pic' in kw:
method = _HTTP_UPLOAD
return _http_call('%s%s.json' % (self._client.api_url, self._path), method, self._client.access_token, **kw)
def __str__(self):
return '_Executable (%s %s)' % (self._method, self._path)
利用__call__来接受传入参数 进一步判定请求类型 如果带有图片则成为upload
_http_call方法进行url生成
user.show.get(uid=12345)
最终生成的url为https://api.weibo.com/2/users/show.json?uid=12345
请求后的返回进行json解析