【发布时间】: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