如何从Python中的AWS中的lambda函数返回二进制数据? [英] How to return binary data from lambda function in AWS in Python?

查看:122
本文介绍了如何从Python中的AWS中的lambda函数返回二进制数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获取python lambda返回二进制数据. 缩略图的节点模板可以正常工作但是我无法让python lambda正常工作.以下是我的lambda中的相关代码行. print("image_data " + image_64_encode)行将base64编码的图像打印到日志中.

I cannot get python lambda to return binary data. The node-template for thumbnail images works fine but I cannot get a python lambda to work. Below is the relevant lines from my lambda. The print("image_data " + image_64_encode) line prints a base64 encoded image to the logs.

def lambda_handler(event, context):
    img_base64 = event.get('base64Image')
    if img_base64 is None:
        return respond(True, "No base64Image key")

    img = base64.decodestring(img_base64)
    name = uuid.uuid4()
    path = '/tmp/{}.png'.format(name)

    print("path " + path)

    image_result = open(path, 'wb')
    image_result.write(img)
    image_result.close()

    process_image(path)

    image_processed_path = '/tmp/{}-processed.png'.format(name)
    print("image_processed_path " + image_processed_path)
    image_processed = open(image_processed_path, 'rb')
    image_processed_data = image_processed.read()
    image_processed.close()
    image_64_encode = base64.encodestring(image_processed_data)

    print("image_data " + image_64_encode)


    return respond(False, image_64_encode)


def respond(err, res):
    return {
        'statusCode': '400' if err else '200',
        'body': res,
        'headers': {
            'Content-Type': 'image/png',
        },
        'isBase64Encoded': 'true'
    }

是否有任何指向我做错事情的指针?

Any pointers to what I'm doing wrong?

推荐答案

执行上述所有步骤均不适用于我的情况,因为具有对content-type = */*的二进制支持会将所有响应转换为二进制.

Following all the steps above didn't work on my case, because having the binary support for content-type = */* will convert all responses to binary.

我的情况:

  • 多个lambda函数返回json(文本),而只有一个lambda函数返回二进制文件.全部都启用了 lambda代理.

lambda位于API网关中

The lambdas are in an API Gateway

API网关在CloudFront后面

The API Gateway is behind CloudFront

提示: 我注意到API网关中的重要信息->设置

Hint: I have notice an important information in the API Gateway -> Settings

报价:

API网关将查看 Content-Type Accept HTTP标头,以决定如何处理正文.

API Gateway will look at the Content-Type and Accept HTTP headers to decide how to handle the body.

这意味着 Content-Type 响应标头必须与 Accept 请求标头

This means that the Content-Type response header must match Accept request header

解决方案:

  1. 在API网关中将二进制媒体类型设置为您的mime类型:image/jpg

  1. Set Binary Media Types in API gateway to your mime type: image/jpg

在您的HTTP请求中设置Accept: image/jpg

In your HTTP request set Accept: image/jpg

在您的HTTP响应集中设置Content-Type: image/jpg

In your HTTP response set Content-Type: image/jpg

{
  "isBase64Encoded": True,
  "statusCode": 200,
  "headers": { "content-type": "image/jpg"},
  "body":  base64.b64encode(content_bytes).decode("utf-8")
}

  1. 接下来,我们必须告诉CloudFront接受请求中的'Accept'标头.因此,在CloudFront分发中,单击您的API网关实例(可单击ID),然后将其重定向到CloudFront实例后,转到 Behaviour 标签,选择API的路径模式(例如:/api/* ),然后点击修改按钮.
  1. Next we must tell CloudFront to accept the 'Accept' header from the request. So, in CloudFront distribution, click on your API Gateway instance (ID is clickable) and once redirected to CloudFront instance go to Behaviour tab, select the path-pattern of your API (example: /api/*) and click on Edit button.

在新屏幕上,您必须将接受标头添加到白名单.

On the new screen, you have to add Accept header to Whitelist.

注意1:如果您有多种文件类型,则必须将它们全部添加到API网关设置的二进制媒体类型

Note 1: If you have multiple file types, you must add them all to Binary Media Types in the API gateway settings

注意2:对于那些来自无服务器的用户,并希望在部署Lambda时设置二进制类型,请查看以下文章:

Note 2: For those coming from serverless and want to set the binary types when deploying your lambdas, then check this post: setting binary media types for API gateway

plugins:
  - serverless-apigw-binary

custom:
  apigwBinary:
    types:
- 'image/jpeg'

用于Cloudfront的serverless.yml文件应包含:

The serverless.yml file for cloudfront should contain:

resources:
    WebAppCloudFrontDistribution:
      Type: AWS::CloudFront::Distribution
      Properties:
        DistributionConfig:
          ...
          CacheBehaviors:
            ...
            - 
              #API calls
              ...
              ForwardedValues:
                ...
                Headers:
                  - Authorization
                  - Accept

这篇关于如何从Python中的AWS中的lambda函数返回二进制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆