First version of lambda config put object

This commit is contained in:
2024-05-01 10:42:56 +02:00
parent 0bc1265b68
commit e149ab7c80
4 changed files with 115 additions and 14 deletions

View File

@@ -3,7 +3,8 @@ import json
import boto3
from typing import Optional
from pydantic import BaseModel
from redirects_base import Redirects
import pydantic_core
from redirects_base import Content, Customer, Redirects, Tag
s3_client = None
bucket_config = ''
@@ -44,13 +45,16 @@ def lambda_handler(event: dict, context):
s3_client = boto3.client('s3')
## Download redirects file
redirects = None
redirects: Redirects
try:
resp = s3_client.get_object(
Bucket=bucket_config,
Key='redirects.json'
)
redirects = Redirects(**json.load(resp['Body']))
#resp = s3_client.get_object(
# Bucket=bucket_config,
# Key='redirects.json'
#)
#redirects = Redirects(**json.load(resp['Body']))
with open('/home/emanuele/dev/StandOut/lambda_config/redirects.json', 'r') as f:
#redirects = Redirects(**json.load(f))
redirects = Redirects.model_validate_json(f.read())
except s3_client.exceptions.NoSuchKey as e:
print(e)
# Oppure pagina "siamo spiacenti ma il contenuto non e' disponibile"
@@ -65,13 +69,47 @@ def lambda_handler(event: dict, context):
return False
print(f"Action: {record.eventName}")
print(f"Object:{record.s3}")
print(f"Object: {record.s3}")
# splitta la chiave per capire la directory
keys = record.s3.object.key.split('/')
file_name = keys[-1]
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
print(f"ObjectCreated: {record.s3.object.key}")
# crea il primo utente se necessario o selezionalo
if redirects.customers is None:
redirects.customers = {keys[0]: Customer(status='active')}
c = redirects.customers[keys[0]]
# crea un tag per l'utente, con contenuto nullo o selezionalo
if c.tags is None:
c.tags = {keys[1]: Tag(status="active", content=None)}
t = c.tags[keys[1]]
# crea un contenuto per il tag a seconda della lunghezza della chiave
if file_name == "url.txt":
with s3_client.get_object(Bucket=bucket_data, Key=record.s3.object.key)['Body'] as url_file:
content = Content(type='url', key=file_name, url=url_file.readline().decode().strip())
else:
content = Content(type='s3', key=file_name, url=None)
match len(keys):
case 4:
if t.content is None:
t.content = {keys[2]: content}
elif isinstance(t.content, dict):
t.content[keys[2]] = content
case 3:
t.content = content
case _:
print("Too long keys")
with open('/home/emanuele/dev/StandOut/lambda_config/redirects.json', 'w') as f:
f.write(redirects.model_dump_json(indent=2))
return True
@@ -89,4 +127,5 @@ def lambda_handler(event: dict, context):
if __name__ == "__main__":
lambda_handler({}, None)
with open('/home/emanuele/dev/StandOut/lambda_config/test.json', 'r') as f:
lambda_handler(json.load(f), None)