[英]How to serve a Python pickle file from a HTML page
I am trying to allow for downloading a Python pickle file from a Flask app through我试图允许通过 Flask 应用程序下载 Python 泡菜文件
import pickle
from flask import Flask, render_template_string
app = Flask(__name__)
template = """
<button onclick="download_file()" data-trigger-update-context="false">Download</button>
<script>
function download_file() {
mime_type = '{{ mime_type }}';
var blob = new Blob(['{{ file_content }}'], { type: mime_type });
var dlink = document.createElement('a');
dlink.download = 'pickle.pkl';
dlink.href = window.URL.createObjectURL(blob);
dlink.onclick = function (e) {
// revokeObjectURL needs a delay to work properly.
var that = this;
setTimeout(function () {
window.URL.revokeObjectURL(that.href);
}, 1500);
};
document.body.appendChild(dlink);
dlink.click();
dlink.remove();
}
</script>
"""
@app.route("/")
def download():
return render_template_string(
template,
file_content=pickle.dumps("text"),
mime_type="application/octet-stream",
)
While downloading the file works fine, the downloaded file itself seems corrupted as I get the following error while reading it虽然下载文件工作正常,但下载的文件本身似乎已损坏,因为我在阅读时收到以下错误
Python 3.7.6 | packaged by conda-forge | (default, Mar 23 2020, 23:03:20)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.14.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import pickle
In [2]: with open("pickle.pkl", "rb") as f:
...: pickle.load(f)
...:
---------------------------------------------------------------------------
UnpicklingError Traceback (most recent call last)
<ipython-input-2-b5282f4164d8> in <module>
1 with open("pickle.pkl", "rb") as f:
----> 2 pickle.load(f)
3
UnpicklingError: unpickling stack underflow
Any hint on the issue with the download script?关于下载脚本问题的任何提示?
Thanks for your help.谢谢你的帮助。
Basically, you need to change just two things:基本上,您只需要更改两件事:
download()
method, you need to convert the serialized bytes to a list of Integers.download()
方法中,您需要将序列化的字节转换为整数列表。 So, your code should look like this:因此,您的代码应如下所示:
import pickle
from flask import Flask, render_template_string
app = Flask(__name__)
template = """
<button onclick="download_file()" data-trigger-update-context="false">Download</button>
<script>
function download_file() {
let bytes_array = new Uint8Array({{file_content}}); //<--- add this
mime_type = '{{ mime_type }}';
var blob = new Blob([bytes_array], { type: mime_type }); //<-- change this
var dlink = document.createElement('a');
dlink.download = 'pickle.pkl';
dlink.href = window.URL.createObjectURL(blob);
dlink.onclick = function (e) {
// revokeObjectURL needs a delay to work properly.
var that = this;
setTimeout(function () {
window.URL.revokeObjectURL(that.href);
}, 1500);
};
document.body.appendChild(dlink);
dlink.click();
dlink.remove();
}
</script>
"""
@app.route("/")
def download():
return render_template_string(
template,
file_content=list(pickle.dumps("text")), # change this
mime_type="application/octet-stream",
)
if __name__ == '__main__':
app.run(debug = True)
Now, you can read the pickled file using pickle.load()
just like so:现在,您可以像这样使用
pickle.load()
读取腌制文件:
import pickle
with open("pickle.pkl", 'rb') as fin:
print(pickle.load(fin))
# prints: text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.