We receive data from an API call and we can't predict the nature of that data. The challenge is just to code a bullet-proof conversion (which I naively thought would be very easy) resulting in an iterable bunch of bytes (bytearray or bytes). I've tried a variety of approaches, even trying io.BytesIO, but some input types still get rejected (a code type kicks out, for example). Any suggestions? It shouldn't be this hard just to treat data as bytes. Thanks for any help.
def process_binary_object(self, api_data):
api_dat_size = sys.getsizeof(api_data)
if api_dat_size < 4 or api_dat_size > 4096: # somewhat arbitrary
return '0123'
if isinstance(api_data, bytes):
self.binary_seq = api_data
print("Conversion technique aa succeeded.")
else:
try:
self.binary_seq = api_data.tobytes()
print("Conversion technique bb succeeded.")
except (AttributeError, TypeError):
try:
self.binary_seq = bytearray(api_data)
print("Conversion technique cc succeeded.")
except (AttributeError, TypeError):
try:
mem_view = memoryview(api_data)
self.binary_seq = mem_view.tobytes()
print("Conversion technique dd succeeded.")
except (AttributeError, TypeError):
self.binary_seq = io.BytesIO(api_data)
print("Conversion technique ee succeeded.")
# some types still don't make it
first_four = self.binary_seq[:4]
return first_four