解码已编码为 Blob 的 pickled 文件

Decode a pickled file that has been encoded as a Blob

概览:

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

后端:

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

[[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,然后将其设置为隐藏的src <iframe>:

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

我不确定为什么我无法直接解码 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)