I'm using https://pypi.python.org/pypi/twitter as the Twitter API library, but note that the method call has changed.
This library is not in the form of passing the URL of the API directly, but in the style of calling the method corresponding to the API. For example, for the API users / show, use the method twitter.users.show ()
.
By the way, the URL of users / show is https://api.twitter.com/1.1/users/show.json?screen_name=twitterdev It looks like this.
However, this method is not implemented in the Twitter class and TwitterCall class of this library, and the URL is assembled from the method name using __getattr__
to call the API.
As a code example, it looks like this
class A(object):
def __init__(self, cls, urlparts):
self.callable_cls = cls
self.urlparts = urlparts
def __getattr__(self, k):
print('called {}'.format(k))
try:
return object.__getattr__(self, k)
except AttributeError:
def extend_call(args):
return self.callable_cls(self.callable_cls, self.urlparts + (args,))
return extend_call(k)
def __call__(self, **kwargs):
return self.urlparts
a = A(A, ())
res = a.users.show()
print(res)
Doing this will return tuples ('users','show')
as a result.
From now on, I will make a URL https://api.twitter.com/1.1/users/show.json?screen_name=twitterdev and call it.
As an explanation, when ʻa.users is called, there is no field or method called ʻusers
, so __getattr__
is called. In it, ʻextend_call (users)is called and added as a tuple to
self.urlparts. Then, a.users.show is called, because there is no method called
show,
getattris called. This also goes into
self.urlpartsas a tuple. When it is finally called as a method,
call is called and returns the contents of
self.urlparts`.
I don't think I'll use this implementation method myself, but as a note
Recommended Posts