简体   繁体   English

如何从 HTML 页面提供 Python 泡菜文件

[英]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:基本上,您只需要更改两件事:

  • In the download() method, you need to convert the serialized bytes to a list of Integers.download()方法中,您需要将序列化的字节转换为整数列表。
  • Then, you need to change the JavaScript code to read this list of numbers.然后,您需要更改 JavaScript 代码以读取此数字列表。

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.

相关问题 从html页面提供javascript文件 - Serve javascript file from an html page 使用来自服务器的数据自动提供 html 页面? - Automatically serve html page with data from server? 如何使用Node.js服务HTML页面,然后将数据写入JSON文件 - How to use Node.js to serve an HTML page which then writes data to a JSON file 如何在服务器中提供用于反应的 html 文件 - how to serve html file used in react in server 可以使用单个node.js服务器文件来服务HTML页面和处理来自该页面的POST请求吗? - Can a single node.js server file be used to both serve a HTML page and process POST requests from said page? 如何在express.js中提供从服务器引用js文件并在客户端运行它的html? - How to serve html in express.js that references js file from server and run it on client side? 如何从高于我的服务器文件夹级别的目录在 Express 中提供 HTML 文件? - How do I serve an HTML file in Express from a directory which is a level above my server folder? 如何使用 NodeJS 在 web 应用程序中从 Azure blob 存储中提供 HTML 文件? - How can I serve an HTML file from Azure blob storage in a web app using NodeJS? 如何传递数据并从服务器向客户端提供html文件? - How can I pass data AND serve an html file from the server to the client? 如何从html页面调用python命令? - how to call python command from html page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM