Create Class for every ressources
Description
Currently, the python SDK contains only a few classes including Index and Client.
it would be nice to implement all the resources returned by the API of Meilisearch in class that would have the effect to return more precise types.
Basic example Every resource could be defined as a class like:
class DocumentsInfo():
results: List[Dict[str, Any]]
offset: int
limit: int
total: int
def get_documents(self, parameters: Optional[Dict[str, Any]] = None) -> DocumentsInfo:
See this repository as a perfect example.
Would like to tackle this, just want to know if the issue is open to PR submissions?
Hi @ElamC, Yes of course, precisely! 😃
@alallema are you looking to have values with snake case over the camelcase passed in by response:
enqueuedAt vs enqueued_at
Converting to snake case variables involves something like:
Dynamically (might cause a hit on performance but allows for custom attributes):
for key in task:
#regex: camel case to snake case
attr_key = re.sub(r'(?<=[a-z])(?=[A-Z])|[^a-zA-Z]', '_', key).strip('_').lower()
setattr(self, attr_key, task[key])
or:
class Task:
def __init__(self, task) -> None:
self.uid: int = task['uid']
self.enqueued_at: str = task['enqueuedAt']
Currently have got something like this:
@dataclass
class Task:
uid: int
enqueuedAt: str
Task(**result)
Is there a preference?
Hi @ElamC, Thank you so much for taking care of this ❤️. I prefer the second option also can't we use this library as it has been implemented here?
Hi @ElamC, Thank you so much for taking care of this ❤️. I prefer the second option also can't we use this library as it has been implemented here?
Just a note if you go this direction. Make sure to install camel-converter with the Pydantic extra pipenv install camel-converter[pydantic]
#513 Introduces this to the project so there are still changes to be made to ensure other resources also return class models