首页 > 解决方案 > AWS Chalice - 发送文件作为响应

问题描述

我目前通过以下方式设置 API。

@app.route('/', cors=cors_config, methods=['GET'])
def index():
    request = app.current_request

    file_name = "orders.csv"
    file_path = '/tmp/{}_{}'.format("Life", file_name)

    with open(file_path, 'w') as csvFile:
        field_names = ["OrderID", "OrderedBy", "Agent"]
        writer = csv.DictWriter(csvFile, fieldnames=field_names)
        writer.writeheader()
        for item in range(10):
            writer.writerow(
                rowdict={
                    "OrderID": str(1), 
                    "OrderedBy": "noob",
                    "Agent": "pro"
                }
            )
        csvFile.close()

    with open(file_path, 'rb') as f:
        contents = f.read()
    f.close()

    file_size = os.path.getsize(file_path)

    headers = {'Content-Type': 'application/octet-stream', 
        'Content-Disposition': 'attachment; filename={}'.format(file_name),
        'Content-Length': str(os.path.getsize(file_path))
    }
    return Response(body=contents, headers=headers)

现在,当使用运行此代码时,我可以毫无问题地下载此处创建的文件。但是,在将其部署到我的 AWS 账户后,API 端点允许我下载一个文件,但它包含我想要的文件的二进制字符串。我阅读了一些其他帖子,这些帖子表明将 contentHandling 路径更新为 CONVERT_TO_BINARY (请参阅此处的答案),我这样做了,然后从 API Gateway 内部重新部署了 API(而不是通过 chalice deploy)。它仍然显示相同的行为。

有没有办法解决这个问题?

标签: amazon-web-servicesaws-lambdaaws-api-gatewaychalice

解决方案


推荐阅读