【问题标题】:Python aws-lambda return xml file to aws-api-gatewayPython aws-lambda 将 xml 文件返回到 aws-api-gateway
【发布时间】:2017-03-28 02:32:19
【问题描述】:

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

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,它返回一个带有 xml 内容的字符串,但这不是我想要的,我需要将 XML 作为文件返回。

【问题讨论】:

    标签: python aws-lambda aws-api-gateway


    【解决方案1】:

    由于 Zanon 已经响应,您需要为 Content-Type: application/xml 和 Content-Disposition: attachment 设置响应头;文件名="myfile.xml"。

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

    设置 Content-Disposition: 附件; filename="myfile.xml" 标头,首先转到您的方法的方法响应页面。在“HTTP 状态”下,单击 200 行左侧的三角形/箭头将其展开。接下来单击“添加标题”。输入 Content-Disposition 作为标题名称,然后单击复选框图标进行保存。这声明响应将发送 Content-Disposition 标头。接下来,您必须将值映射到标题。为此,请转到您的方法的集成响应页面。展开 200 行和 Header Mappings 部分。在 Header Mappings 下,您现在应该可以看到 Content-Disposition。单击 Content-Disposition 右侧的 Mapping 值空间为其定义映射。在这种情况下,我们可以只使用一个常数值,所以输入 'attachment;文件名="myfile.xml"'。一定要包括单引号。然后点击对勾图标保存。

    您现在应该能够通过控制台测试您的 API 方法并看到 Content-Disposition 标头设置为附件;文件名="myfile.xml"。请记住重新部署您的 API 以使更改在控制台之外生效。

    【讨论】:

      【解决方案2】:

      对于一个可下载的文件,你需要设置两个响应头:

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

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

      【讨论】:

      • 如何设置 Content-Disposition?,我只找到 Content-Type 设置。谢谢
      猜你喜欢
      • 2017-04-19
      • 2021-07-29
      • 1970-01-01
      • 2019-02-08
      • 2018-11-28
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 2017-09-19
      相关资源
      最近更新 更多