singleton

This commit is contained in:
root 2012-10-25 20:40:44 +02:00
parent f63cc8d5d0
commit 54c2dbb64b

View file

@ -188,19 +188,29 @@ class YunoHostError(Exception):
else: else:
self.desc = code self.desc = code
def singleton(cls):
instances = {}
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance
@singleton
class YunoHostLDAP(object): class YunoHostLDAP(object):
""" Specific LDAP functions for YunoHost """ """ Specific LDAP functions for YunoHost """
conn = None
def __enter__(self, password=False): def __enter__(self, password=False):
self.__init__(password)
return self
def __init__(self, password=False):
""" """
Connect to LDAP base Connect to LDAP base
Initialize to localhost, base yunohost.org, prompt for password Initialize to localhost, base yunohost.org, prompt for password
""" """
if self.conn is None:
self.conn = ldap.initialize('ldap://localhost:389') self.conn = ldap.initialize('ldap://localhost:389')
self.base = 'dc=yunohost,dc=org' self.base = 'dc=yunohost,dc=org'
if password: if password:
@ -214,7 +224,6 @@ class YunoHostLDAP(object):
self.conn.simple_bind_s('cn=admin,' + self.base, self.pwd) self.conn.simple_bind_s('cn=admin,' + self.base, self.pwd)
except ldap.INVALID_CREDENTIALS: except ldap.INVALID_CREDENTIALS:
raise YunoHostError(13, _('Invalid credentials')) raise YunoHostError(13, _('Invalid credentials'))
return self
def __exit__(self, type, value, traceback): def __exit__(self, type, value, traceback):
self.disconnect() self.disconnect()