Как я могу настроить свой собственный s3 putevent, который запускает AWS лямбда? - PullRequest
0 голосов
/ 08 февраля 2019

Было бы очень полезно полностью помочь, если бы кто-то мог провести меня через это, я пытался пройти через структуру событий, но это было не очень полезно!

Aws lambda Структура события

Я все еще не в состоянии понять, что многие из вас присутствовали на этом вопросе, но я не в состоянии понять вас. Я совершенно новичок в aws.

Я прошел через структуру событий,он говорит, что вы найдете здесь идентификатор конфигурации "configurationId": "идентификатор найден в конфигурации уведомлений корзины", но я не смог

, и я все еще меньше подсказываю о

«x-amz-request-id»: «идентификатор запроса, сгенерированный Amazon S3»,

«x-amz-id-2»: «хост Amazon S3, обработавший запрос» *

from __future__ import print_function

import boto3
from decimal import Decimal
import json
import urllib

print('Loading function')

rekognition = boto3.client('rekognition')
iot = boto3.client('iot-data')


# --------------- Helper Functions to call Rekognition APIs ------------------

def compare_faces(bucket, key, key_target, threshold=90):
    response = rekognition.compare_faces(
        SourceImage={
            "S3Object": {
                "Bucket": 'dacsup',
                "Name": 'obama.jpg',
            }
        },
        TargetImage={
            "S3Object": {
                "Bucket": 'targetts',
                "Name": 'obama2.jpg',
            }
        },
        SimilarityThreshold=threshold,
    )
    return response['SourceImageFace'], response['FaceMatches']

# --------------- Main handler ------------------


def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))
    key_target = "targetts/" + key
    try:
        response = compare_faces(bucket, key, key_target)
        print(response)
        mypayload = json.dumps(response)
        iotResponse = iot.publish(
            topic="rekognition/result",
            qos=1,
            payload=mypayload)
        print(iotResponse)
        return iotResponse
        print(response)
        return response
    except Exception as e:
        print(e)
        print("Error processing object {} from bucket {}. ".format(key, bucket) +
              "Make sure your object and bucket exist and your bucket is in the same region as this function.")
        raise e

----------------------- событие ------------------

{
  "Records": [
    {
      "eventVersion": "2.1",
      "eventTime": "2019-02-08T11:49:26.471Z",
      "requestParameters": {
        "sourceIPAddress": "My ip"
      },
      "s3": {
        "configurationId": "----------------",
        "object": {
          "eTag": "99b7ce351fec8c0e7b30fd194a8c81b3",
          "sequencer": "-----------",
          "key": "obama.jpg",
          "size": 5908
        },
        "bucket": {
          "arn": "  arn:aws:s3:::bucketname",
          "name": " dacsup ",
          "ownerIdentity": {
            "principalId": "Mypprincipalid"
          }
        },
        "s3SchemaVersion": "1.0"
      },
      "responseElements": {
        "x-amz-id-2": "-------------",
        "x-amz-request-id": "-----------"
      },
      "awsRegion": " us-east-2",
      "eventName": "ObjectCreated:Put",
      "userIdentity": {
        "principalId": "myrincipalid"
      },
      "eventSource": "aws:s3"
    }
  ]
}

ошибка ---------------------------- xxxxxxxxx ------------------------

START RequestId: 24820efa-d454-4ae4-9c49-e2eedd1c96ce Version: $LATEST
Received event: {
  "Records": [
    {
      "eventVersion": "2.1", 
      "eventTime": "2019-03-04T11:49:26.471Z", 
      "requestParameters": {
        "sourceIPAddress": "My ip"
      }, 
      "s3": {
        "configurationId": "", 
        "object": {
          "eTag": "99b7ce351fec8c0e7b30fd194a8c81b3 ", 
          "key": "obama.jpg", 
          "sequencer": "0A1B2C3D4E5F678901 ", 
          "size": 5908
        }, 
        "bucket": {
          "ownerIdentity": {
            "principalId": "My pid"
          }, 
          "name": " dacsup ", 
          "arn": "  arn:aws:s3:::dacsup "
        }, 
        "s3SchemaVersion": "1.0"
      }, 
      "responseElements": {
        "x-amz-id-2": "", 
        "x-amz-request-id": ""
      }, 
      "awsRegion": " us-east-2", 
      "eventName": "ObjectCreated:Put", 
      "userIdentity": {
        "principalId": "pid"
      }, 
      "eventSource": "aws:s3"
    }
  ]
}
An error occurred (InvalidS3ObjectException) when calling the CompareFaces operation: Unable to get object metadata from S3. Check object key, region and/or access permissions.
Error processing object obama.jpg from bucket . Make sure your object and bucket exist and your bucket is in the same region as this function.
An error occurred (InvalidS3ObjectException) when calling the CompareFaces operation: Unable to get object metadata from S3. Check object key, region and/or access permissions.: InvalidS3ObjectException
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 59, in lambda_handler
    raise e
InvalidS3ObjectException: An error occurred (InvalidS3ObjectException) when calling the CompareFaces operation: Unable to get object metadata from S3. Check object key, region and/or access permissions.

END RequestId: 24820efa-d454-4ae4-9c49-e2eedd1c96ce
REPORT RequestId: 24820efa-d454-4ae4-9c49-e2eedd1c96ce  Duration: 372.53 ms Billed Duration: 400 ms     Memory Size: 128 MB Max Memory Used: 67 MB  

1 Ответ

0 голосов
/ 08 февраля 2019

Это текущая версия Структура сообщения о событии .Все поля, которые вы упомянули, доступны здесь.

{  
   "Records":[  
      {  
         "eventVersion":"2.1",
         "eventSource":"aws:s3",
         "awsRegion":"us-west-2",
         "eventTime":The time, in ISO-8601 format, for example, 1970-01-01T00:00:00.000Z, when Amazon S3 finished processing the request,
         "eventName":"event-type",
         "userIdentity":{  
            "principalId":"Amazon-customer-ID-of-the-user-who-caused-the-event"
         },
         "requestParameters":{  
            "sourceIPAddress":"ip-address-where-request-came-from"
         },
         "responseElements":{  
            "x-amz-request-id":"Amazon S3 generated request ID",
            "x-amz-id-2":"Amazon S3 host that processed the request"
         },
         "s3":{  
            "s3SchemaVersion":"1.0",
            "configurationId":"ID found in the bucket notification configuration",
            "bucket":{  
               "name":"bucket-name",
               "ownerIdentity":{  
                  "principalId":"Amazon-customer-ID-of-the-bucket-owner"
               },
               "arn":"bucket-ARN"
            },
            "object":{  
               "key":"object-key",
               "size":object-size,
               "eTag":"object eTag",
               "versionId":"object version if bucket is versioning-enabled, otherwise null",
               "sequencer": "a string representation of a hexadecimal value used to determine event sequence, 
                   only used with PUTs and DELETEs"
            }
         },
         "glacierEventData": {
            "restoreEventData": {
               "lifecycleRestorationExpiryTime": "The time, in ISO-8601 format, for example, 1970-01-01T00:00:00.000Z, of Restore Expiry",
               "lifecycleRestoreStorageClass": "Source storage class for restore"
            }
         }
      }
   ]
}
...