django bytesIO to base64 String & return as JSON
Question:
I am using python 3 & I have this code, trying to get base64 out of stream and returnn as json – but not working.
stream = BytesIO()
img.save(stream,format='png')
return base64.b64encode(stream.getvalue())
in my view, I have:
hm =mymap()
strHM = hm.generate(data)
return HttpResponse(json.dumps({"img": strHM}),content_type="application/json" )
getting error is not JSON serializable. base64.b64encode(stream.getvalue()) seems giving bytes
Answers:
In Python 3.x, base64.b64encode
accepts a bytes
object and returns a bytes
object.
>>> base64.b64encode(b'a')
b'YQ=='
>>> base64.b64encode(b'a').decode()
'YQ=='
You need to convert it to str
object, using bytes.decode
:
return base64.b64encode(stream.getvalue()).decode()
I think there is a simpler solution.
Simply get the bytes from the stream and pass them to b64encode.
b64encode(f.getvalue())
Output (also bytes)
b'c2VwYWwgbGVuZ3RoIChjbSksc2V...'
I am using python 3 & I have this code, trying to get base64 out of stream and returnn as json – but not working.
stream = BytesIO()
img.save(stream,format='png')
return base64.b64encode(stream.getvalue())
in my view, I have:
hm =mymap()
strHM = hm.generate(data)
return HttpResponse(json.dumps({"img": strHM}),content_type="application/json" )
getting error is not JSON serializable. base64.b64encode(stream.getvalue()) seems giving bytes
In Python 3.x, base64.b64encode
accepts a bytes
object and returns a bytes
object.
>>> base64.b64encode(b'a')
b'YQ=='
>>> base64.b64encode(b'a').decode()
'YQ=='
You need to convert it to str
object, using bytes.decode
:
return base64.b64encode(stream.getvalue()).decode()
I think there is a simpler solution.
Simply get the bytes from the stream and pass them to b64encode.
b64encode(f.getvalue())
Output (also bytes)
b'c2VwYWwgbGVuZ3RoIChjbSksc2V...'