python - 将 MySQL blob 内容作为 json 响应发送

标签 python mysql json rest blob

我有以下 GET 方法的代码,该方法拍摄一张存储在 MySql 中的 blob 类型字段中的照片并返回。我想将它返回到 JSON 字符串内的客户端,其类型可以在 angularjs 应用程序中显示图像。

 def GET(self,r):
    user_data = CC.get_data(query) # holds the content of the blob field.
    print type(user_data) # prints <type 'str'>
    data = {'name': 'test',
           'photo': user_data}
    return json.dump(data)

这给出了,

UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0:
invalid start byte

我发现在一些网站上最好将照片作为字节数组发送。 我使用 web.py python 框架。 最好的方法是什么?

最佳答案

为了防止数据丢失,发送二进制数据最好的方法是将其编码为 base64

import base64

def GET(self,r):
    user_data = CC.get_data(query) # holds the content of the blob field.
    data = {'name': 'test',
           'photo': base64.b64encode(user_data)}
    return json.dump(data)

但是,确实不建议通过 JSON 发送二进制数据,特别是在 web 中。例如,您可以发送 URL 来下载照片。

关于python - 将 MySQL blob 内容作为 json 响应发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37464600/

相关文章:

java - 如何在 Spring @ResponseBody 中使用 Jackson 将 ArrayList<String> 转换为 JSON 对象

android - Realm.IO - 可以使用 createOrUpdateAllFromJson 解析 JSON 数组吗?

android - 多个 httpPost 到遥远的 Restful 服务 (JSON)

Python FTP 隐式 TLS 连接问题

python - 在 python 中计算频率的最干净的方法是什么

mysql - 无法使用vb.net将路径文件地址插入到mysql

php - 使用php调用存储过程

python |移动用户创建的文件夹中的特定文件

python - 在 python 中使用 selenium 填写用户名和密码

mysql csv文件导入问题