简体   繁体   English

Python aws-lambda返回xml文件到aws-api-gateway

[英]Python aws-lambda return xml file to aws-api-gateway

I'm trying to build an RESTful service in Amazon Web Service, using API Gateway and Lambdas. 我正在尝试使用API​​ Gateway和Lambdas在Amazon Web Service中构建RESTful服务。 One of the API Gateway method is intended to return a single record from a DynamoDB table of a corresponding resource from S3. API网关方法之一旨在从S3的相应资源的DynamoDB表返回单个记录。 This resource is an XML file, but I don't know how can I return this content from the Lambda function in a way that its served as a downloadable file. 该资源是XML文件,但是我不知道如何以可下载文件的方式从Lambda函数返回此内容。 I'm using Python to code the lambdas, and so far it looks like this: 我使用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)

The API Gateway is set to application/xml, and it returns an string with the xml content, but this is not what I want, I need to return the XML as a file. API网关设置为application / xml,它返回包含xml内容的字符串,但这不是我想要的,我需要将XML作为文件返回。

As Zanon already responded, you need to set response headers for Content-Type: application/xml and Content-Disposition: attachment; 由于Zanon已经响应,因此需要为Content-Type:application / xml和Content-Disposition:附件设置响应头; filename="myfile.xml". 文件名= “myfile.xml中”。

It sounds like you already have the Content-Type: application/xml working. 听起来您已经有了Content-Type:application / xml。

To set the Content-Disposition: attachment; 设置Content-Disposition:附件; filename="myfile.xml" header, first go to the Method Response page for your method. filename =“ myfile.xml”标头,请首先转到方法的“方法响应”页面。 Under "HTTP Status", click the triangle/arrow to the left of the 200 line to expand it. 在“ HTTP状态”下,单击200行左侧的三角形/箭头以将其展开。 Next click on "Add Header". 接下来单击“添加标题”。 Enter Content-Disposition as the header name and click on the checkbox icon to save. 输入Content-Disposition作为标题名称,然后单击复选框图标进行保存。 This declares that the response will send the Content-Disposition header. 这声明响应将发送Content-Disposition标头。 Next you have to map a value to the header. 接下来,您必须将一个值映射到标题。 To do this, go to the Integration Response page for your method. 为此,请转到您的方法的“集成响应”页面。 Expand the 200 line and the Header Mappings section. 展开200行和“页眉映射”部分。 Under Header Mappings you should now see the Content-Disposition. 在标题映射下,您现在应该看到内容处置。 Click on the Mapping value space to the right of Content-Disposition to define a mapping for it. 单击Content-Disposition右侧的Mapping值空间以为其定义映射。 In this case we can just use a constant value, so enter 'attachment; 在这种情况下,我们可以使用恒定值,因此输入“ attachment; filename="myfile.xml"'. 文件名= “myfile.xml中””。 Be sure to include the single quotes. 确保包括单引号。 Then click the checkmark icon to save. 然后单击复选标记图标进行保存。

You should now be able to test your API method via the console and see the Content-Disposition header being set to attachment; 现在,您应该能够通过控制台测试API方法,并看到Content-Disposition标头设置为附件; filename="myfile.xml". 文件名= “myfile.xml中”。 Remember to re-deploy your API go get the changes to take effect outside of the console. 记住要重新部署您的API,以使更改在控制台之外生效。

For a downloadable file, you need to set two response headers: 对于可下载文件,您需要设置两个响应头:

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

This setting is done in the API Gateway. 此设置在API网关中完成。 You said that you've already configured the Content-Type , so I believe that what you need now is to configure the Content-Disposition . 您说您已经配置了Content-Type ,所以我认为现在需要配置Content-Disposition

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM