src/pyams_ldap/query.py
changeset 0 94ee60dd51e1
child 8 bbc24a6bd6f0
equal deleted inserted replaced
-1:000000000000 0:94ee60dd51e1
       
     1 #
       
     2 # Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
       
     3 # All Rights Reserved.
       
     4 #
       
     5 # This software is subject to the provisions of the Zope Public License,
       
     6 # Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
       
     7 # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
       
     8 # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
       
     9 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
       
    10 # FOR A PARTICULAR PURPOSE.
       
    11 #
       
    12 
       
    13 __docformat__ = 'restructuredtext'
       
    14 
       
    15 
       
    16 # import standard library
       
    17 import logging
       
    18 logger = logging.getLogger('PyAMS (ldap)')
       
    19 
       
    20 # import interfaces
       
    21 
       
    22 # import packages
       
    23 
       
    24 
       
    25 class LDAPQuery(object):
       
    26     """Object representing an LDAP query"""
       
    27 
       
    28     def __init__(self, base_dn, filter_tmpl, scope, attributes):
       
    29         self.base_dn = base_dn
       
    30         self.filter_tmpl = filter_tmpl
       
    31         self.scope = scope
       
    32         self.attributes = attributes
       
    33 
       
    34     def __str__(self):
       
    35         return ('base_dn={base_dn}, filter_tmpl={filter_tmpl}, '
       
    36                 'scope={scope}, attributes={attributes}'.format(**self.__dict__))
       
    37 
       
    38     def execute(self, conn, **kwargs):
       
    39         key = (self.base_dn.format(**kwargs),
       
    40                self.filter_tmpl.format(**kwargs))
       
    41         logger.debug(">>> executing LDAP query: {0} (base {1}) <<< {1}".format(self.filter_tmpl,
       
    42                                                                                self.base_dn,
       
    43                                                                                str(kwargs.items())))
       
    44         ret = conn.search(search_scope=self.scope,
       
    45                           attributes=self.attributes,
       
    46                           *key)
       
    47         result, ret = conn.get_response(ret)
       
    48         if result is None:
       
    49             result = []
       
    50         else:
       
    51             result = [(r['dn'], r['attributes']) for r in result
       
    52                       if 'dn' in r]
       
    53         logger.debug("<<< LDAP result = {0}".format(str(result)))
       
    54         return result