javascript - 如何从 HTML 页面提供 Python 泡菜文件
问题描述
我正在尝试允许通过 Flask 应用程序下载 Python pickle 文件
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",
)
虽然下载文件工作正常,但下载的文件本身似乎已损坏,因为我在阅读时收到以下错误
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
关于下载脚本问题的任何提示?
谢谢你的帮助。
解决方案
基本上,您只需要更改两件事:
- 在该
download()
方法中,您需要将序列化的字节转换为整数列表。 - 然后,您需要更改 JavaScript 代码以读取此数字列表。
因此,您的代码应如下所示:
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)
现在,您可以pickle.load()
像这样读取腌制文件:
import pickle
with open("pickle.pkl", 'rb') as fin:
print(pickle.load(fin))
# prints: text