jbloomer / SnipeIT-PythonAPI

Python Interface to the SnipeIT (https://github.com/snipe/snipe-it) API
80 stars 37 forks source link

API Helper #19

Open variable opened 4 years ago

variable commented 4 years ago

Yesterday I tried the API, while it works, but every method requires me to specify the url and token is a bit convoluted, please I don't know why the result is a json string but not jsonified into python dictionary:

assets = Assets()
result = assets.getDetailsBySerial(url, token, 896424002550010736)
result = json.loads(result)

Without having to rewrite everything, I have created a helper factory to wrap these 2 pain points:

def snipeit_api_factory(kls):
    """
    Return an instance of the wrapped snipe-it API class to avoid specifying url and token for every method
    And jsonify the result
    """
    SNIPEIT_URL = ''
    SNIPEIT_TOKEN = ''

    def jsonify(func):
        def wrapper(*args, **kwargs):
            return json.loads(func(*args, **kwargs))
        return wrapper

    class Cls(kls):
        def __getattribute__(self, item):
            attr = kls.__getattribute__(self, item)
            if isinstance(attr, types.MethodType):
                return jsonify(partial(attr, settings.SNIPEIT_URL, settings.SNIPEIT_TOKEN))
            return attr
    return Cls()

Usage:

assets = snipeit_api_factory(Assets)
a.get()
a.getDetailsBySerial(896424002550010736)

If you are happy with this helper I will submit a pull request to add this into the repo.