【问题标题】:Decode a pickled file that has been encoded as a Blob解码已编码为 Blob 的腌制文件
【发布时间】:2018-02-22 00:43:45
【问题描述】:

概述:

我正在尝试让保存/加载功能作为我正在构建的网络应用程序的一部分工作,但在我下载文件后无法正确重新加载文件。

后端:

我在 python 中有一个列表,看起来像

[[bytes, bytes, int, list, list, str], [...], [...], etc].

这是我关心的数据。然后我用

腌制它
with open(file_path, 'wb') as fp:
   pickle.dump(save_this_arr, fp) 

并使用 Flask 的 send_file 发送:

return send_file(file_path, as_attachment=True)

前端:

在前端,我正在创建一个blob,编码一个数据url,然后将其设置为隐藏<iframe>的src:

let blob = new Blob([response.data], { type: "application/octet-stream" });
let url = window.URL.createObjectURL(blob);
self.downloader.src = url 

这很好用,并为我提供了一个可以重新上传的文件。

问题:

我被困在如何正确解码 URL 以便我可以 pickle.load 结果。下面的两个链接似乎是我需要的,但是当我将它应用到我的代码时,我得到了 UnicodeDecodeErrors。

当前尝试:

with open(file_path, "rb") as fid:
     contents = fid.read()
data = urllib.parse.parse_qs(contents, encoding='utf-16')
with open(file_path, 'wb') as fid:
    fid.write(text)
with open(file_path, 'rb') as fid:
    myList = pickle.load(fid)

编辑:

最初的问题是关于解码 url,因为我误解了 window.URL.createObjectURL(blob) 在做什么。从this blog post,我意识到我们实际上是在创建对内存中 blob 的引用。所以我真正想做的是在 Python 中读取一个 Blob。

参考资料:

Url decode UTF-8 in Python

decoding URL encoded byte stream data in python

【问题讨论】:

    标签: javascript python flask pickle


    【解决方案1】:

    我不确定为什么我无法直接解码 blob,但在写入文件之前编码为 base64 字符串是可行的。

    后端(写入磁盘):

    import base64
    with open(file_path, 'wb') as fp:
        data = pickle.dumps(save_this_arr)
        encoded = base64.b64encode(data)
        fp.write(encoded)
    

    前端(从问题复制 - 没有变化):

    let blob = new Blob([response.data], { type: "application/octet-stream" });
    let url = window.URL.createObjectURL(blob);
    self.downloader.src = url 
    

    后端(从磁盘读取):

    with open(file_path, "rb") as fid:
        contents = fid.read()
        decoded = base64.b64decode(contents)
        myList = pickle.loads(decoded)
    

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 2014-10-10
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多