Python aws-lambda return xml 文件到 aws-api-gateway

Python aws-lambda return xml file to aws-api-gateway

我正在尝试使用 API 网关和 Lambda 在 Amazon Web Service 中构建 RESTful 服务。 API 网关方法之一旨在 return 来自 DynamoDB 的单个记录 table 来自 S3 的相应资源。此资源是一个 XML 文件,但我不知道如何以可下载文件的方式从 Lambda 函数 return 此内容。 我正在使用 Python 对 lambda 进行编码,到目前为止它看起来像这样:

import json
from lxml import etree

def get_item_handler(event, context):
    # Validate request
    # ...
    # End validation

    logger.info('Querying by id:{0}'.format(event["id"]))
    query_kwargs = {
        'Select': "ALL_ATTRIBUTES",
        'Limit': event["PageSize"] if "PageSize" in event else settings.DEFAULT_PAGE_SIZE,
        'KeyConditionExpression': Key('id').eq(event["id"])
    }

    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table(settings.TABLE_NAME)
    response = table.query(**query_kwargs)

    if "format" in event and event["format"] and response["Items"]:
        response_format = event["format"].lower()
        item = json.loads(json.dumps(response['Items'], cls=DecimalEncoder))[0]
        if response_format == "xml":    
            s3_path = get_item_path(item) # Form path to the item in S3
            resource = os.path.join(s3_path , item["resource"])
            local_file = '/tmp/{0}'.format(item["resource"])
            s3_client = boto3.client('s3')
            transfer = S3Transfer(s3_client)
            transfer.download_file(settings.BUCKET_NAME, resource, local_file)
            xml = etree.parse(local_file)
            return etree.tostring(xml)

    return json.dumps(response['Items'], cls=DecimalEncoder)

API网关设置为application/xml,return是一个内容为xml的字符串,但这不是我想要的,我需要到 return XML 作为一个文件。

对于可下载文件,您需要设置两个响应headers:

Content-Type: application/xml
Content-Disposition: attachment; filename="myfile.xml"

此设置在 API 网关中完成。你说你已经配置了Content-Type,所以我相信你现在需要的是配置Content-Disposition

由于 Zanon 已回复,您需要为 Content-Type 设置回复 headers:application/xml 和 Content-Disposition:附件;文件名="myfile.xml".

听起来你已经有 Content-Type: application/xml 工作了。

设置Content-Disposition:附件; filename="myfile.xml" header,首先转到您的方法的“方法响应”页面。在 "HTTP Status" 下,单击 200 行左侧的 triangle/arrow 将其展开。接下来点击 "Add Header"。输入 Content-Disposition 作为 header 名称,然后单击复选框图标进行保存。这声明响应将发送 Content-Disposition header。接下来,您必须将一个值映射到 header。为此,请转到您的方法的集成响应页面。展开 200 行和 Header 映射部分。在 Header 映射下,您现在应该看到 Content-Disposition。单击 Content-Disposition 右侧的映射值 space 为其定义映射。在这种情况下,我们可以只使用一个常量值,所以输入 'attachment; filename="myfile.xml"'。请务必包括单引号。然后单击复选标记图标进行保存。

您现在应该能够通过控制台测试您的 API 方法并看到 Content-Disposition header 被设置为附件;文件名="myfile.xml"。请记住 re-deploy 您的 API 去让更改在控制台外生效。