import os import json import boto3 from botocore.exceptions import ClientError from pydantic import BaseModel, ValidationError class InputData(BaseModel): title: str text: str keywords: list def get_secret(): secret_name = "secret-manager" region_name = "us-east-1" # Create a Secrets Manager client session = boto3.session.Session() client = session.client( service_name='secretsmanager', region_name=region_name ) try: get_secret_value_response = client.get_secret_value( SecretId=secret_name ) except ClientError as e: # Handle the exception raise e secret = get_secret_value_response['SecretString'] return json.loads(secret) # Return the secret as a dictionary def lambda_handler(event, context): # Retrieve secrets secrets = get_secret() aws_access_key = secrets['AWS_ACCESS_KEY_ID'] aws_secret_access_key = secrets['AWS_SECRET_ACCESS_KEY'] # DynamoDB tablosunun adını çevresel değişkenden al table_name = os.environ['DYNAMODB_TABLE_NAME'] # Initialize DynamoDB resource dynamodb = boto3.resource( 'dynamodb', aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_access_key, region_name='us-east-1' ) # DynamoDB tablosuna erişim table = dynamodb.Table(table_name) lambda_name = 'LAMBDA_FUNCTION_NAME' lambda_client = boto3.client('lambda') try: # Body'den JSON verilerini al. body = json.loads(event.get('body', '{}')) # Verileri Pydantic ile doğrula. data = InputData(**body) # DynamoDB'ye kaydetme işlemi. table.put_item( Item={ 'title': data.title, 'text': data.text, 'keywords': ','.join(data.keywords) # Listeyi string olarak kaydet. } ) # Lambda fonksiyonunu çağırma işlemi. lambda_payload = { 'text': data.text, 'title': data.title, 'keywords': data.keywords } response_invoke = lambda_client.invoke( FunctionName=lambda_name, InvocationType='RequestResponse', Payload=json.dumps(lambda_payload) ) return { 'statusCode': 200, 'body': json.dumps({ 'message': 'Data successfully saved!', 'data': data.dict() # Doğrulanmış verileri döndür. }) } except ValidationError as e: return { 'statusCode': 400, 'body': json.dumps({ 'message': 'Invalid input data', 'errors': e.errors() }) } except Exception as e: return { 'statusCode': 500, 'body': json.dumps({ 'message': 'Internal server error', 'error': str(e) }) }