I'm writing a python REST client for an API.
The API needs authentication and I would like to have many API client objects running on the same script.
My current code for the API is something like this:
class RestAPI:
def __init__(self, id):
self.id = id
self.fetch()
def fetch(self):
requests.get(self.url+self.id, auth=self.apikey)
class CustomModel(RestAPI):
url = 'http://example.com/custommodel/'
And I would like to use the API like that:
api_admin = Api('adminmytoken')
api_user = Api('usertoken')
…
my_title = api_admin.CustomModel(2).Title
api_user.CustomModel(2).Title # raises because api_user is not authorized
The problem is that each object needs to know it's apikey depending on the client I want to use.
That pattern looks like to me to a "class factory": all the classes of RestAPI need to know of the provided token.
How is it possible to cleanly do that without giving manually the token to each model ?
Aucun commentaire:
Enregistrer un commentaire