django bytesIO到base64字符串&作为JSON返回 [英] django bytesIO to base64 String & return as JSON
本文介绍了django bytesIO到base64字符串&作为JSON返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用python 3&我有这段代码,试图使base64脱离流并作为json返回-但不起作用。
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())
在我看来,我有:
hm =mymap()
strHM = hm.generate(data)
return HttpResponse(json.dumps({"img": strHM}),content_type="application/json" )
获取错误不是JSON可序列化的。 base64.b64encode(stream.getvalue())似乎给出了字节数
getting error is not JSON serializable. base64.b64encode(stream.getvalue()) seems giving bytes
推荐答案
在Python 3.x中, base64.b64encode
接受 bytes
对象,并返回 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=='
您需要使用 bytes.decode
:
You need to convert it to str
object, using bytes.decode
:
return base64.b64encode(stream.getvalue()).decode()
这篇关于django bytesIO到base64字符串&作为JSON返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文