【问题标题】:Dump pickle file and get download without saving it anywhere in Flask App转储pickle文件并下载而不将其保存在Flask App中的任何位置
【发布时间】:2020-10-10 06:12:01
【问题描述】:
@app.route('/', methods=['POST'])
def upload_file():
  if request.method == 'POST':

    if 'files[]' not in request.files:
      flash('No file part')
      return redirect(request.url)

    files = request.files.getlist('files[]')
    ...Processing my multiple uploaded files in Flask App...
    ...
    b64_encoded_list = base64.b64encode(json_encoded_list)
    print(b64_encoded_list)
    ## b64_encoded_list is a simple string ##
    buffer = BytesIO()
    buffer.write(b64_encoded_list)
    buffer.seek(0)
    flash('File(s) successfully uploaded')
    return send_file(buffer, mimetype="image/jpg", attachment_filename="license.pem", as_attachment=True)

现在我可以在 Web 应用程序部分发送和下载,但 .pem 文件已损坏,因为 b64_encoded_list 包含存储在 .pem 文件中的字符串的 b64 编码。但是从网络应用程序下载文件后,再次读取它给我一个错误 - encrypted = pickle.load(open(pemfile, "rb"))

错误 - UnpicklingError: 无效的加载键,'W'。

如何解决这个问题我也使用了 mimetype - application/x-x509-ca-cert,但还是同样的错误。

请帮忙!

提前致谢!!

【问题讨论】:

    标签: html python-3.x flask pickle pem


    【解决方案1】:

    您需要将输出写入类似文件的对象(例如内存中的文件),而不是将输出写入文件。

    您可以使用io.BytesIO

    https://docs.python.org/3/library/io.html#io.BytesIO

    然后,您将其发送给客户端。

    【讨论】:

    • 哦,那我将如何发送到客户端使在客户端下载 .pem 文件格式??
    • return send_file(BytesIO(b64_encoded_list.content), mimetype="application/x-x509-ca-cert", attachment_filename="file.pem", as_attachment=True) 注意 - b64_encoded_list 是一个字符串.我已经尝试过,但它不起作用,请你帮我解决这个问题!
    • buffer = BytesIO() buffer.write(b64_encoded_list) buffer.seek(0) return send_file(buffer, mimetype="application/x-x509-ca-cert",attachment_filename="license.pem ", as_attachment=True) 我已经这样做了,并在客户端下载成功,但是 .pem 已损坏,因为它包含 base64 编码以获取原始字符串,但是当尝试从下载的文件 - UnpicklingError: 无效的加载键,'W'。
    • 我认为您应该(为自己)写下一个列表,该列表应该在哪一个序列中发生,然后将其与您的代码(即您在做什么)进行比较。我不完全清楚你想要实现什么,我不知道你在 .pem 文件中想要什么(pem 通常用于证书)。我相信你可以自己弄清楚。祝你好运!
    猜你喜欢
    • 2013-05-20
    • 1970-01-01
    • 2020-10-10
    • 2016-02-19
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    相关资源
    最近更新 更多