I am learning and try to write python api client for some third-party API For simplicity:
I have 2 classes: Session, EndpointGroup:
class Session:
def __init__(self, token=None):
self.token = token
self.group1 = EndpointGroup
class EndpointGroup:
@classmethod
def ping(cls, token, **kwargs):
return f'Calling ping() with params: {kwargs} and token {token}'
I have many EndpointGroups which contain same-category api calls.
I want to give end-user to call methods like this:
session = Session(token='123')
r = session.group1.ping(data='somedata') # Calling ping with params: {'data':'somedata'} and token 123
I want to pass token to callable automaticly/implicitly so user don't have to on each call pass to callable something like session.group1.ping(data='somedata', token=session.token)
Is there "built-in" solution to do it? Because with _getattribute_ I only can access EndpointGroup class but not method which is called.
What i have already tried:
- Creating instances of EndpointGroup passing session/token (Don't like solution because it creates too many instances for each single session) with _getattribute_
- Let Session inherit EndpointGroup methods, but then I lose desirable "interface" like session.groupN.method_X to session.method_X
- Make in EndpointGroup class attr 'token' and On each call change it so method can access this token of current caller(session) (Don't like this solution because this way I will not be able to work asynchronously)
from Can classmethod/staticmethod access attributes of initial caller?
No comments:
Post a Comment