我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用future.utils.native()。
def get_ldap_connection(dn=None, password=None): tls_configuration = None use_ssl = False try: cacert = configuration.get("ldap", "cacert") tls_configuration = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file=cacert) use_ssl = True except: pass server = Server(configuration.get("ldap", "uri"), use_ssl, tls_configuration) conn = Connection(server, native(dn), native(password)) if not conn.bind(): log.error("Cannot bind to ldap server: %s ", conn.last_error) raise AuthenticationError("Cannot bind to ldap server") return conn
def from_bytes(cls, mybytes, byteorder='big', signed=False): """ Return the integer represented by the given array of bytes. The mybytes argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol. The byteorder argument determines the byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. The signed keyword-only argument indicates whether two's complement is used to represent the integer. """ if byteorder not in ('little', 'big'): raise ValueError("byteorder must be either 'little' or 'big'") if isinstance(mybytes, unicode): raise TypeError("cannot convert unicode objects to bytes") # mybytes can also be passed as a sequence of integers on Py3. # Test for this: elif isinstance(mybytes, collections.Iterable): mybytes = newbytes(mybytes) b = mybytes if byteorder == 'big' else mybytes[::-1] if len(b) == 0: b = b'\x00' # The encode() method has been disabled by newbytes, but Py2's # str has it: num = int(native(b).encode('hex'), 16) if signed and (b[0] & 0x80): num = num - (2 ** (len(b)*8)) return cls(num) # def _twos_comp(val, bits): # """compute the 2's compliment of int value val""" # if( (val&(1<<(bits-1))) != 0 ): # val = val - (1<<bits) # return val
def group_contains_user(conn, search_base, group_filter, user_name_attr, username): search_filter = '(&({0}))'.format(group_filter) if not conn.search(native(search_base), native(search_filter), attributes=[native(user_name_attr)]): log.warning("Unable to find group for %s %s", search_base, search_filter) else: for entry in conn.entries: if username in getattr(entry, user_name_attr).values: return True return False
def groups_user(conn, search_base, user_filter, user_name_att, username): search_filter = "(&({0})({1}={2}))".format(user_filter, user_name_att, username) try: memberof_attr = configuration.get("ldap", "group_member_attr") except: memberof_attr = "memberOf" res = conn.search(native(search_base), native(search_filter), attributes=[native(memberof_attr)]) if not res: log.info("Cannot find user %s", username) raise AuthenticationError("Invalid username or password") if conn.response and memberof_attr not in conn.response[0]["attributes"]: log.warning("""Missing attribute "%s" when looked-up in Ldap database. The user does not seem to be a member of a group and therefore won't see any dag if the option filter_by_owner=True and owner_mode=ldapgroup are set""", memberof_attr) return [] user_groups = conn.response[0]["attributes"][memberof_attr] regex = re.compile("cn=([^,]*).*", re.IGNORECASE) groups_list = [] try: groups_list = [regex.search(i).group(1) for i in user_groups] except IndexError: log.warning("Parsing error when retrieving the user's group(s)." " Check if the user belongs to at least one group" " or if the user's groups name do not contain special characters") return groups_list
def _leveldb_write(db, *args, **kwargs): if kwargs: raise NotImplementedError('passing keyword arguments to ' 'LevelDB not supported') db.put(*list(map(native, args)))
def _leveldb_delete(db, *args, **kwargs): if kwargs: raise NotImplementedError('passing keyword arguments to ' 'LevelDB not supported') db.delete(*list(map(native, args)))
def _leveldb_reader(db, *args, **kwargs): if kwargs: raise NotImplementedError('passing keyword arguments to ' 'LevelDB not supported') return db.get(*list(map(native, args)))
def _BuildUri( handler ): return native( ToBytes( urljoin( BaseRequest.server_location, handler ) ) )
def convertBiocDocToKindredDocs(document): assert isinstance(document,bioc.BioCDocument) kindredDocs = [] for passage in document.passages: assert isinstance(passage,bioc.BioCPassage) text = passage.text offset = int(native(passage.offset)) entities = [] relations = [] for a in passage.annotations: assert isinstance(a,bioc.BioCAnnotation) entityType = a.infons['type'] sourceEntityID = a.id position = [] segments = [] for l in a.locations: assert isinstance(l,bioc.BioCLocation) startPos = int(native(l.offset)) - offset endPos = startPos + int(native(l.length)) position.append((startPos,endPos)) segments.append(text[startPos:endPos]) entityText = " ".join(segments) e = kindred.Entity(entityType,entityText,position,sourceEntityID) entities.append(e) for r in passage.relations: assert isinstance(r,bioc.BioCRelation) relationType = r.infons['type'] arguments = [] for n in r.nodes: assert isinstance(n,bioc.BioCNode) arguments.append((n.role,n.refid)) arguments = sorted(arguments) entityIDs = [ entityID for argName,entityID in arguments] argNames = [ argName for argName,entityID in arguments] r = kindred.Relation(relationType=relationType,entityIDs=entityIDs,argNames=argNames) relations.append(r) metadata = dict(document.infons) metadata.update(passage.infons) metadata['id'] = document.id relData = kindred.Document(text,entities=entities,relations=relations,metadata=metadata) kindredDocs.append(relData) return kindredDocs
def to_bytes(self, length, byteorder='big', signed=False): """ Return an array of bytes representing an integer. The integer is represented using length bytes. An OverflowError is raised if the integer is not representable with the given number of bytes. The byteorder argument determines the byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. The signed keyword-only argument determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised. """ if length < 0: raise ValueError("length argument must be non-negative") if length == 0 and self == 0: return newbytes() if signed and self < 0: bits = length * 8 num = (2**bits) + self if num <= 0: raise OverflowError("int too smal to convert") else: if self < 0: raise OverflowError("can't convert negative int to unsigned") num = self if byteorder not in ('little', 'big'): raise ValueError("byteorder must be either 'little' or 'big'") h = b'%x' % num s = newbytes((b'0'*(len(h) % 2) + h).zfill(length*2).decode('hex')) if signed: high_set = s[0] & 0x80 if self > 0 and high_set: raise OverflowError("int too big to convert") if self < 0 and not high_set: raise OverflowError("int too small to convert") if len(s) > length: raise OverflowError("int too big to convert") return s if byteorder == 'big' else s[::-1]
def try_login(username, password): conn = get_ldap_connection(configuration.get("ldap", "bind_user"), configuration.get("ldap", "bind_password")) search_filter = "(&({0})({1}={2}))".format( configuration.get("ldap", "user_filter"), configuration.get("ldap", "user_name_attr"), username ) search_scopes = { "LEVEL": LEVEL, "SUBTREE": SUBTREE, "BASE": BASE } search_scope = LEVEL if configuration.has_option("ldap", "search_scope"): search_scope = SUBTREE if configuration.get("ldap", "search_scope") == "SUBTREE" else LEVEL # todo: BASE or ONELEVEL? res = conn.search(native(configuration.get("ldap", "basedn")), native(search_filter), search_scope=native(search_scope)) # todo: use list or result? if not res: log.info("Cannot find user %s", username) raise AuthenticationError("Invalid username or password") entry = conn.response[0] conn.unbind() if 'dn' not in entry: # The search filter for the user did not return any values, so an # invalid user was used for credentials. raise AuthenticationError("Invalid username or password") try: conn = get_ldap_connection(entry['dn'], password) except KeyError as e: log.error(""" Unable to parse LDAP structure. If you're using Active Directory and not specifying an OU, you must set search_scope=SUBTREE in airflow.cfg. %s """ % traceback.format_exc()) raise LdapException("Could not parse LDAP structure. Try setting search_scope in airflow.cfg, or check logs") if not conn: log.info("Password incorrect for user %s", username) raise AuthenticationError("Invalid username or password")