Skip to content

Commit

Permalink
rearranged file structure
Browse files Browse the repository at this point in the history
  • Loading branch information
Hoggi90 committed Jan 8, 2025
1 parent 7a403e3 commit edef847
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 33 deletions.
105 changes: 72 additions & 33 deletions terraform/lambda/lambda_function.py
Original file line number Diff line number Diff line change
@@ -1,72 +1,111 @@
import os
import pymysql
import json
import os
from datetime import datetime

def lambda_handler(event, context):
# RDS connection details from environment variables
db_host = os.environ['DB_HOST']
db_user = os.environ['DB_USER']
db_password = os.environ['DB_PASSWORD']
db_name = os.environ['DB_NAME']

# Parse the incoming form data from API Gateway
# Handle different HTTP methods
if event.get("httpMethod") == "GET":
return get_visitors(event)
elif event.get("httpMethod") == "POST":
return post_visitor(event)
else:
return {
"statusCode": 405,
"body": json.dumps({"error": "Method Not Allowed"})
}

def get_visitors(event):
connection = None # Initialize the connection variable
try:
# Connect to the RDS database
connection = pymysql.connect(
host=os.environ['DB_HOST'],
user=os.environ['DB_USER'],
password=os.environ['DB_PASSWORD'],
database=os.environ['DB_NAME'],
cursorclass=pymysql.cursors.DictCursor
)

with connection.cursor() as cursor:
# Fetch data from the visitors table
cursor.execute("SELECT * FROM visitors")
visitors = cursor.fetchall() # Fetch all rows

# Convert datetime fields to string (ISO format)
for visitor in visitors:
if isinstance(visitor['created_at'], datetime):
visitor['created_at'] = visitor['created_at'].isoformat()

return {
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"body": json.dumps({"visitors": visitors})
}

except Exception as e:
return {
"statusCode": 500,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type", # Ensure headers are allowed
"Access-Control-Allow-Methods": "GET, POST",
},
"body": json.dumps({"error": "Error fetching data", "details": str(e)})
}

finally:
if connection:
connection.close()

def post_visitor(event):
connection = None # Initialize the connection variable
try:
body = json.loads(event.get("body", "{}")) # Safely parse JSON
body = json.loads(event["body"])
name = body.get("name")
location = body.get("location")

if not name or not location:
return {
"statusCode": 400,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"body": json.dumps({"error": "Missing 'name' or 'location' in request"})
}
except json.JSONDecodeError:
return {
"statusCode": 400,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"body": json.dumps({"error": "Invalid JSON format"})
}

try:
# Connect to the RDS database
connection = pymysql.connect(
host=db_host,
user=db_user,
password=db_password,
database=db_name,
host=os.environ['DB_HOST'],
user=os.environ['DB_USER'],
password=os.environ['DB_PASSWORD'],
database=os.environ['DB_NAME'],
cursorclass=pymysql.cursors.DictCursor
)

with connection.cursor() as cursor:
# Insert data into the RDS database
# Insert data into the visitors table
sql = "INSERT INTO visitors (name, location) VALUES (%s, %s)"
cursor.execute(sql, (name, location))
connection.commit()

return {
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"body": json.dumps({"message": "Data saved successfully!"})
}

except Exception as e:
print(f"Error: {e}")
return {
"statusCode": 500,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"body": json.dumps({"error": "Error saving data", "details": str(e)})
}

finally:
connection.close()
if connection:
connection.close()
Binary file modified terraform/lambda/lambda_function.zip
Binary file not shown.

0 comments on commit edef847

Please sign in to comment.