【问题标题】:Send MySQL blob content as a json response将 MySQL blob 内容作为 json 响应发送
【发布时间】:2016-09-24 16:17:48
【问题描述】:

我有以下 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 框架。 最好的方法是什么?

【问题讨论】:

    标签: python mysql json rest blob


    【解决方案1】:

    为防止数据丢失,发送二进制数据的最佳方法是编码为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.xml 中。例如,您可以发送一个 URL 来下载照片。

    【讨论】:

    • 感谢它的工作。但是我可以知道为什么不建议通过 JSON 发送二进制数据并让它从 URL 下载吗?
    • 这在很大程度上取决于您的实现,但是让您的客户端解码 base64 字符串可能是不必要的,特别是因为它可以像大多数浏览器一样单独下载和显示图像。
    【解决方案2】:

    首先如何使用 blob:

    http://www.mysqltutorial.org/python-mysql-blob/

    要将您的图像发送到您的模板:

    def imageResponseView(...) .... 返回响应

    将 url 绑定到该视图

    使用&lt;img src = "//url_to_that_view" /&gt;显示图片

    发件人:I have an image's HTTPResponse. How do I display it in a Django template?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2019-03-10
      • 2023-03-13
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多