Skip to content
Snippets Groups Projects
dmSudsApi.py 1.93 KiB
Newer Older
sveseli's avatar
sveseli committed
#!/usr/bin/env python

import os
import shutil
from functools import wraps
from decorator import decorator

from dm.common.exceptions.dmException import DmException
from dm.common.api.dmApi import DmApi

class DmSudsApi(DmApi):
    """ Base dm api class that utilizes suds calls. """

    SUDS_CACHE_DIR = '/tmp/suds'

    def __init__(self, username=None, password=None):
        DmApi.__init__(self, username=username, password=password)

    # Remove suds cache directory if it exists.
    # Workaround for bug in current suds package that leaves 
    # cache files behind, which may result in permission denied errors
    # for multiple users
    @classmethod
    def removeSudsCache(cls):
        if os.path.exists(cls.SUDS_CACHE_DIR):
            try:
                shutil.rmtree(cls.SUDS_CACHE_DIR)
            except Exception, ex:
                cls.getLogger().warn('Cannot remove suds cache %s: %s' % (cls.SUDS_CACHE_DIR, ex))
    
    # Exception decorator for api calls
    # Use two decorators for the sake of documentation
    @classmethod
    def executeSudsCall(cls, *dargs, **dkwargs):
        def internalCall(func):
            @wraps(func)
            def wrappedCall(func, *args, **kwargs):
                try:
                    response = func(*args, **kwargs)
                    cls.removeSudsCache()
                    return response
                except DmException, ex:
                    cls.removeSudsCache()
                    raise ex
                except Exception, ex:
                    cls.getLogger().exception('%s' % ex)
                    cls.removeSudsCache()
                    raise DmException(exception=ex)
            return decorator(wrappedCall, func)
        if len(dargs) == 1 and callable(dargs[0]):
            return internalCall(dargs[0])
        else:
            return internalCall

#######################################################################
# Testing.

if __name__ == '__main__':
    pass