Files
StandOut/lambda_config/lambda_config.py
2024-04-25 12:54:31 +02:00

92 lines
2.4 KiB
Python

import os
import json
import boto3
from typing import Optional
from pydantic import BaseModel
from redirects_base import Redirects
s3_client = None
bucket_config = ''
bucket_data = ''
class S3Bucket(BaseModel):
name: str
ownerIdentity: dict
arn: str
class S3Object(BaseModel):
key: str
eTag: Optional[str | None] = None
size: Optional[int | None] = None
sequencer: Optional[str | None] = None
class S3Event(BaseModel):
s3SchemaVersion: str
bucket: S3Bucket
object: S3Object
class Record(BaseModel):
eventName: str
eventSource: str
eventTime: str
s3: S3Event
def lambda_handler(event: dict, context):
global s3_client, bucket_config, bucket_data
if s3_client is None:
print("Init Function")
bucket_config = os.environ.get('BUCKET_CONFIG', 'standout-config')
bucket_data = os.environ.get('BUCKET_DATA', 'standout-data')
print(f'Bucket Config: {bucket_config}')
print(f' Bucket Data: {bucket_data}')
s3_client = boto3.client('s3')
## Download redirects file
redirects = None
try:
resp = s3_client.get_object(
Bucket=bucket_config,
Key='redirects.json'
)
redirects = Redirects(**json.load(resp['Body']))
except s3_client.exceptions.NoSuchKey as e:
print(e)
# Oppure pagina "siamo spiacenti ma il contenuto non e' disponibile"
return {
"statusCode": 404
}
# Proces records
for r in event["Records"]:
record = Record(**r)
if record.eventSource != "aws:s3":
return False
print(f"Action: {record.eventName}")
print(f"Object:{record.s3}")
match record.eventName:
case "ObjectCreated:Put" | "ObjectCreated:Post":
print(f"Object add: {record.s3.object.key}")
key_components = record.s3.object.key.split('/')
# capire il numero di key components, aggiornare il modello
return True
case "ObjectCreated:Copy":
print(f"Object copy: {record.s3.object.key}")
return True
case "s3:ObjectRemoved:*":
print(f"Object remove: {record.s3.object.key}")
return True
case _:
print("Unknown action")
if __name__ == "__main__":
lambda_handler({}, None)