python - django bytesIO 到 base64 字符串并作为 JSON 返回

标签 python django python-3.x

我正在使用 python 3 并且我有这段代码,试图从流中获取 base64 并作为 json 返回 - 但没有工作。

       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()) 似乎给出字节数

最佳答案

在 Python 3.x 中,base64.b64encode接受一个 bytes 对象并返回一个 bytes 对象。

>>> base64.b64encode(b'a')
b'YQ=='
>>> base64.b64encode(b'a').decode()
'YQ=='

您需要将它转换为str 对象,使用bytes.decode :

return base64.b64encode(stream.getvalue()).decode()

关于python - django bytesIO 到 base64 字符串并作为 JSON 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27241996/

相关文章:

java - 在 Java 中压缩数据并在 Python 中解压缩

python - 如何仅从 Python 列表中获取不是字符串的元素?

javascript - 从 Django 为 D3 图直接输入数据

django - 使用 Django Rest 框架进行注册电子邮件验证

python - 为什么我在 python 3 中收到 'function upper(bytea)' 错误?

python - 为什么此代码在第 11 行引发 RecursionError?

python - Sendgrid 外发电子邮件将显示在我的已发送邮箱中

python - Django REST Framework - 教程 - 困惑

python - 如何阻止 bokeh 在 Jupyter Notebook 中打开新标签页?

python - 通过 python3 子进程发送管道命令