how to handle byte-like values with Python 2 and 3

Viewed 45

I am trying to make a Python 2 code compatible with and Python 3. I am using python-ldap. In Python 3 the values of the queried attributes of the objects are returned as byte-like objects:

[('CN=user,CN=Users,DC=excample,DC=com', {'displayName': [b'Test User'], 'objectSid': [b'\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xa0e\xcf~xK\x9b_\xe7|\x87p\t\x1c\x01\x00'], 'sAMAccountName': [b'user'], 'pwdLastSet': [b'132144982087435710'], 'whenChanged': [b'20191020171614.0Z']})]
for item in data:
    for key, value in item[1].items():
       print(value[0])
       print(type(value[0]))

And I get:

b'Test User'
<class 'bytes'>
b'\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xa0e\xcf~xK\x9b_\xe7|\x87p\t\x1c\x01\x00'
<class 'bytes'>
b'user'
<class 'bytes'>
b'132144982087435710'
<class 'bytes'>
b'20191020171614.0Z'
<class 'bytes'>

In Python 2:

[('CN=user,CN=Users,DC=excample,DC=com', {'displayName': ['Test User'], 'objectSid': ['\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xa0e\xcf~xK\x9b_\xe7|\x87p\t\x1c\x01\x00'], 'sAMAccountName': ['user'], 'pwdLastSet': ['132144982087435710'], 'whenChanged': ['20191020171614.0Z']})]

and with the loop:

for item in data:
    for key, value in item[1].items():
       print(value[0])
       print(type(value[0]))

I get:

132144982087435710
<type 'str'>
e���J=��}e�O
<type 'str'>
Test User
<type 'str'>
user
<type 'str'>
20191020171614.0Z
<type 'str'>

So I cannot make any string operations and keep get the following:

TypeError: a bytes-like object is required, not 'str'

or with time() methods:

TypeError: strptime() argument 0 must be str, not <class 'bytes'>

I went through this, but I cannot get it work. decode() wont help, firstly the objectSid is a specific combination of hex and big-endian and little-endian, so it must be decoded in a different way, for which I already have wrote function. Secondly I need the data as byte-like objects as well. In Python 2 that wasn't an issue, since I could do byte-like objects operation as well as string and list operation.

Thanks

0 Answers
Related