meilisearch-python icon indicating copy to clipboard operation
meilisearch-python copied to clipboard

Create Class for every ressources

Open alallema opened this issue 3 years ago • 6 comments

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.

alallema avatar Jul 27 '22 14:07 alallema

Would like to tackle this, just want to know if the issue is open to PR submissions?

elamc-2 avatar Jul 31 '22 09:07 elamc-2

Hi @ElamC, Yes of course, precisely! 😃

alallema avatar Jul 31 '22 14:07 alallema

@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?

elamc-2 avatar Aug 03 '22 14:08 elamc-2

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?

alallema avatar Aug 04 '22 09:08 alallema

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]

sanders41 avatar Aug 04 '22 10:08 sanders41

#513 Introduces this to the project so there are still changes to be made to ensure other resources also return class models

elamc-2 avatar Aug 07 '22 15:08 elamc-2