如何从HTML页面中提供Python pickle文件?

问题描述 投票:1回答:1

我试图允许从Flask应用中通过

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

有没有提示下载脚本的问题?

谢谢你的帮助。

javascript python pickle
1个回答
1
投票

基本上,你只需要改变两件事。

  • 在... 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
© www.soinside.com 2019 - 2024. All rights reserved.