I have got the items from AWS dynamodb as dict which has a value in binary format. I am not able to retrieve the value of a binary content.
Below is the sample.
my_details = {'route': Binary(b'gAAAABgLNW9tNcpeclIy1LSs8wKYRy9uMxgr5V4TwJmEJNZ2WVlb3Z3LtIK3PewO2SDRYkvXAh8bcZ4Ej_jBjaNi8xhU1-P2FLpcGEX2g='), 'way': '5064', '
stop': Binary(b'\xf1J\xef\xa0\xac\xb1A0\xa9\\:'), 'name': 'cfcf57'}
print(type(my_details['route']))
print(my_details['route'])
print(my_details['way'])
I need value of the route key like below
gAAAABgLNW9tNcpeclIy1LSs8wKYRy9uMxgr5V4TwJmEJNZ2WVlb3Z3LtIK3PewO2SDRYkvXAh8bcZ4Ej_jBjaNi8xhU1-P2FLpcGEX2g=
I have tried to get the value of route using mydetails['route'] but got below error
<class 'boto3.dynamodb.types.Binary'>
Traceback (most recent call last):
File "C:/Users/Prabhakar/Documents/Projects/Test.py", line 18, in <module>
print(my_details['route'])
TypeError: __str__ returned non-string (type bytes)
Please let me know how can I retrieve the binary content in python dict.
when you call print(my_details['route']), the actual call is print(str(my_details['route'])).
boto3.dynamodb.types.Binary define is
class Binary:
"""A class for representing Binary in dynamodb
Especially for Python 2, use this class to explicitly specify
binary data for item in DynamoDB. It is essentially a wrapper around
binary. Unicode and Python 3 string types are not allowed.
"""
def __init__(self, value):
if not isinstance(value, BINARY_TYPES):
types = ', '.join([str(t) for t in BINARY_TYPES])
raise TypeError(f'Value must be of the following types: {types}')
self.value = value
def __eq__(self, other):
if isinstance(other, Binary):
return self.value == other.value
return self.value == other
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return f'Binary({self.value!r})'
def __str__(self):
return self.value
def __bytes__(self):
return self.value
def __hash__(self):
return hash(self.value)
then the actual call is print(my_details['route'].__str__()), the return type is bytes, so you get the type error:
TypeError: __str__ returned non-string (type bytes)
so what you need is just print(bytes(my_details['route'])), or print(str(bytes(my_details['route'])))
Python's types are really confusing!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With