Spaces:
Configuration error
Configuration error
File size: 3,183 Bytes
10aa31e 9887605 20947b2 10aa31e 20947b2 10aa31e 9887605 10aa31e 20947b2 10aa31e 20947b2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
import json
import os
import boto3
from pymongo import MongoClient
from dotenv import load_dotenv
load_dotenv()
# Çevresel değişkenlerden yapılandırma bilgilerini alıyoruz
DYNAMO_TABLE = os.getenv('DYNAMO_TABLE')
MONGO_URI = os.getenv('MONGO_URI')
INPUT_DB = os.getenv('INPUT_DB')
# AWS DynamoDB kaynağı
dynamodb = boto3.resource('dynamodb')
def lambda_handler(event, context):
"""AWS Lambda işleyici fonksiyonu."""
method = event['requestContext']['http']['method']
if method == 'POST':
return handle_post(event)
elif method == 'GET':
return handle_get(event)
else:
return {
'statusCode': 405,
'body': json.dumps('Method Not Allowed')
}
def handle_post(event):
"""POST isteklerini işleyin."""
table = dynamodb.Table(DYNAMO_TABLE)
try:
body = json.loads(event['body'])
title = body.get('title')
keywords = body.get('keywords')
text = body.get('text')
if not title or not keywords or not text:
return {
'statusCode': 400,
'body': json.dumps('Invalid input data')
}
# DynamoDB'ye veri ekleyin
table.put_item(
Item={
'title': title,
'keywords': keywords,
'text': text
}
)
# MongoDB'ye veri ekleyin
insert_data_into_input_db([{"title": title, "keywords": keywords, "text": text}])
return {
'statusCode': 200,
'body': json.dumps('Data inserted into DynamoDB and MongoDB!')
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps(f"Error: {str(e)}")
}
def handle_get(event):
"""GET isteklerini işleyin."""
table = dynamodb.Table(DYNAMO_TABLE)
try:
query_params = event.get('queryStringParameters', {})
title = query_params.get('title')
if not title:
return {
'statusCode': 400,
'body': json.dumps('Title parameter is required')
}
# DynamoDB'den veri alın
response = table.get_item(
Key={
'title': title
}
)
item = response.get('Item', {})
if not item:
return {
'statusCode': 404,
'body': json.dumps('Data not found')
}
return {
'statusCode': 200,
'body': json.dumps(item)
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps(f"Error: {str(e)}")
}
def connect_to_mongodb():
"""MongoDB'ye bağlan."""
client = MongoClient(MONGO_URI)
return client
def insert_data_into_input_db(data):
"""Input database'e veri ekle."""
client = connect_to_mongodb()
db = client[INPUT_DB]
collection = db['input'] # Kullanıcıdan alınacak verilerin saklandığı koleksiyon
collection.insert_many(data)
client.close()
|