首页 > 解决方案 > 如何使用 Python 从 Google Cloud Function 发送具有正确名称的 zip 文件?

问题描述

我有生成 zip 文件并将其作为下载提供的代码。它在谷歌云函数中处理。生成和下载 zipfile 没问题,但我无法获得返回具有给定名称的 zip 文件的功能。下载始终默认为函数名称“fdsuitebuilder”。

这是代码;

from dsuite import DSuite
from flask import send_file

def main(request):
    ... #creating and filling a DSuite object called ds
    ffullname = ds.write("tmp", "output.stix")   
    return send_file(ffullname, mimetype='application/zip', attachment_filename='output.stix', as_attachment=True)

所以我在触发该函数时所期望的是生成一个名为 output.stix 的下载(实际上是一个 zip 文件),但我得到一个名为“fdsuitebuilder”的下载

我想这与 GCP 不是烧瓶有关,但如果有人知道生成正确下载名称的正确方法,我会很高兴知道!

问候

标签: pythonflaskgoogle-cloud-platformgoogle-cloud-functions

解决方案


以下对我有用:

from tempfile import mktemp
from flask import send_file


def test(request):
    fn = mktemp()
    with open(fn, "w") as f:
        f.write("Hello")
    return send_file(
        fn,
        mimetype="application/zip",
        attachment_filename="output.stix",
        as_attachment=True,
    )
$ curl -I https://us-central1-gcf-sendfile-test.cloudfunctions.net/test
HTTP/2 200
cache-control: public, max-age=43200
content-disposition: attachment; filename=output.stix
content-type: application/zip
etag: "1573510438.2602577-5-834405785"
expires: Tue, 12 Nov 2019 10:13:58 GMT
function-execution-id: 7sb3tp6j260y
last-modified: Mon, 11 Nov 2019 22:13:58 GMT
content-length: 5
date: Mon, 11 Nov 2019 22:13:58 GMT
server: Google Frontend

我看不出您的示例不起作用的原因。您能否确认它已成功部署您包含的版本?


推荐阅读