py.lib

Yohn Y. 2022-08-14 Parent:cab7fedf8432

34:84b54a8a6d4c Go to Latest

py.lib/db/ldap.py

+ Возможность обработки параметров конфигурации перед добавлением в класс конфигурации . Переформатирование части кода по PEP

History
1 # coding: utf-8
3 from ldap3 import Server, Connection, SIMPLE, SUBTREE
5 LDAP_PAGE = 1000
8 class LdapError(Exception): pass
11 class LdapRes:
12 def __init__(self, dn, attrib):
13 self.dn = dn
14 self.attr = attrib
16 def __getitem__(self, item):
17 return self.attr[item]
19 def __iter__(self):
20 return iter(self.attr)
22 def __repr__(self):
23 return '<LdapRes: dn: %s>' % self.dn
25 @classmethod
26 def fromLdapQuery(cls, q):
27 if not isinstance(q, dict):
28 raise LdapError('LdapRes: Parsing Error, not ldap response item')
29 if not (('dn' in q) and ('attributes' in q)):
30 raise LdapError('LdapRes: Parsing Error, format mismatch')
32 return cls(q['dn'], q['attributes'])
35 class Ldap:
36 def __init__(self, host, user, passwd, timeout=60, queryTimeout=300, **kwa):
37 if 'baseDN' in kwa:
38 self._baseDN = kwa['baseDN']
39 del kwa['baseDN']
40 else:
41 self._baseDN = None
42 ldapSrv = Server(host, connect_timeout=timeout, **kwa)
43 self._conn = self._makeConnFabric(ldapSrv, authentication=SIMPLE,
44 user=user, password=passwd,
45 check_names=True, lazy=True,
46 auto_referrals=False, raise_exceptions=True, auto_range=True
47 )
48 self.queryTimeout = queryTimeout
50 def __call__(self, filter, attrib, queryTimeout=None, baseDN=None):
51 if baseDN is None:
52 if self._baseDN is None:
53 raise LdapError('No base dn on query execution')
54 baseDN = self._baseDN
55 if queryTimeout is None:
56 queryTimeout = self.queryTimeout
57 try:
58 conn = self._conn()
59 with conn:
60 conn.open()
61 conn.bind()
63 res = conn.extend.standard.paged_search(baseDN,
64 filter, attributes=attrib, paged_size=LDAP_PAGE,
65 generator=False,
66 search_scope=SUBTREE, time_limit=queryTimeout
67 )
69 for i in res:
70 if i['type'] == 'searchResEntry':
71 yield LdapRes.fromLdapQuery(i)
73 except Exception as e:
74 raise LdapError("Error on get data (%s): %s" % (type(e), str(e)), *e.args[1:])
76 def getList(self, *a, **kwa):
77 return [i for i in self(*a, **kwa)]
79 @staticmethod
80 def _makeConnFabric(*a, **kwa):
81 def _func():
82 return Connection(*a, **kwa)
84 return _func