Class 63rd AWS Project day 2 July 9th
Using all below services
IAM, Completed
KMS, Encrypt the password Completed
VPC,
EC2,(LB,AS,EBS,EFS),
Local to RDS, Completed
DynamoDB,
Lambda, Completed
API Gateway,
S3, Completed
CloudFront Completed
Route53,
ACM
Last Class 62nd Above service completed, using CloudFront Images stored in private bucket
It should retrieved from the s3 private bucket
Step1:
Need Create CloudFront distributed url select the Origin private while you creating
Step2: I have uploaded app_cloudfront.py take reference and execute rename app.py
>python app.py
https://github.com/Vakatisubbu/DigitalLibrary
Step4: KMS , password encrypted
Lambda using our project
lambda_function.py
import json
import pymysql
db_config = {
'host': 'aurorabd.csn64oem2jvs.us-east-1.rds.amazonaws.com',
'user': 'admin',
'password': 'admin123',
'database': 'digital_library'
}
def lambda_handler(event, context):
try:
# 🔍 Debug full event structure
print("FULL EVENT:", json.dumps(event))
# ✅ Pull query parameters
body = event if isinstance(event, dict) else {}
print("Query Params:", json.dumps(body))
# Extract
name = body.get('name')
mobile = body.get('mobile')
email = body.get('email')
password = body.get('password')
gender = body.get('gender')
location = body.get('location')
image = body.get('image')
if not all([name, mobile, email, password,gender,location,image]):
return {
"statusCode": 400,
"body": json.dumps({
"status": "fail",
"message": "Missing required fields",
"received": body # <-- debug: show what was received
})
}
conn = pymysql.connect(**db_config)
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
if cursor.fetchone():
cursor.close()
conn.close()
return {
"statusCode": 409,
"body": json.dumps({"status": "fail", "message": "Email already exists"})
}
cursor.execute("""
INSERT INTO users (name, mobile, email, password, gender, location, image)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""", (name, mobile, email, password, gender, location, image))
conn.commit()
cursor.close()
conn.close()
return {
"statusCode": 200,
"body": json.dumps({"status": "success", "message": "User created successfully"})
}
except Exception as e:
print("Exception:", str(e))
return {
"statusCode": 409,
"body": json.dumps({"status": "error", "message": str(e)})
}
C:\Users\Administrator\Desktop\Lambda>pip install pymysql -t.
Collecting pymysql
Using cached PyMySQL-1.1.1-py3-none-any.whl.metadata (4.4 kB)
Using cached PyMySQL-1.1.1-py3-none-any.whl (44 kB)
Installing collected packages: pymysql
Successfully installed pymysql-1.1.1
Select this files Zip it
pymysql
PyMySQL-1.1.1.dist-info
lambda_function.py
Step5: upload the zip folder
Step6:
API Gateway >Reset API > Resoure>SignUp> create Methods >GET >
Click Integration edit m
{
"name": "$input.params('name')",
"mobile": "$input.params('mobile')",
"email": "$input.params('email')",
"password":"$input.params('password')",
"gender": "$input.params('gender')",
"location":"$input.params('location')",
"image": "$input.params('image')"
}
Click Save
Click Deploy API
Step7:
Tested Query Script parameter
Step9: Create one more function name
ccit-lambda-function-Sigin.py
While Selecting the role Same role Lambda function we can not use,until unless the role has administrator permission
import json
import pymysql
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
db_config = {
'host': 'aurorabd.csn64oem2jvs.us-east-1.rds.amazonaws.com',
'user': 'admin',
'password': 'admin123',
'database': 'digital_library',
'connect_timeout': 5
}
def lambda_handler(event, context):
try:
# Debug logging
logger.info(f"Raw event structure: {json.dumps(event)}")
# Handle both proxy and non-proxy integrations
if event.get('queryStringParameters'):
data = event['queryStringParameters']
elif event.get('body'):
try:
body = event['body']
data = json.loads(body) if isinstance(body, str) else body
except json.JSONDecodeError:
data = {}
else:
data = event
logger.info(f"Parsed data: {data}")
email = data.get('email')
password = data.get('password')
if not email or not password:
return {
"statusCode": 400,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"status": "fail",
"message": "Email and password required",
"received": data
})
}
# Database connection
try:
conn = pymysql.connect(**db_config)
with conn.cursor() as cursor:
cursor.execute(
"SELECT id, name, email FROM users WHERE email = %s AND password = %s",
(email, password)
)
user = cursor.fetchone()
if user:
response = {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"status": "success",
"user": {
"id": user[0],
"name": user[1],
"email": user[2]
}
})
}
else:
response = {
"statusCode": 401,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"status": "fail",
"message": "Invalid credentials"
})
}
logger.info(f"Returning response: {response}")
return response
except pymysql.MySQLError as e:
logger.error(f"Database error: {str(e)}")
return {
"statusCode": 500,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"status": "error",
"message": "Database error"
})
}
except Exception as e:
logger.error(f"Unexpected error: {str(e)}")
return {
"statusCode": 500,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"status": "error",
"message": "Internal server error"
})
}
C:\Users\Administrator\Desktop\Lambda\SignIn>pip install pymysql -t.
Collecting pymysql
Using cached PyMySQL-1.1.1-py3-none-any.whl.metadata (4.4 kB)
Using cached PyMySQL-1.1.1-py3-none-any.whl (44 kB)
Installing collected packages: pymysql
Successfully installed pymysql-1.1.1
Step7: Create resource Signin
Delete the existing Option method
Click Create Method
Step8:Intergration
{
"email": "$input.params('email')",
"password": "$input.params('password')"
}
Click Save
Step 10: Create one more Lambda Function
For test
{
"body": "{\"email\":\"prabhu@gmail.com\",\"password\":\"prabhu\"}",
"queryStringParameters": null
}
Signup the detail using lambda function
import json
import pymysql
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
db_config = {
'host': 'aurorabd.csn64oem2jvs.us-east-1.rds.amazonaws.com',
'user': 'admin',
'password': 'admin123',
'database': 'digital_library',
'connect_timeout': 5
}
def lambda_handler(event, context):
try:
# Debug logging
logger.info(f"Raw event structure: {json.dumps(event)}")
# Handle both proxy and non-proxy integrations
if event.get('queryStringParameters'):
data = event['queryStringParameters']
elif event.get('body'):
try:
body = event['body']
data = json.loads(body) if isinstance(body, str) else body
except json.JSONDecodeError:
data = {}
else:
data = event
logger.info(f"Parsed data: {data}")
email = data.get('email')
password = data.get('password')
if not email or not password:
return {
"statusCode": 400,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"status": "fail",
"message": "Email and password required",
"received": data
})
}
# Database connection
try:
conn = pymysql.connect(**db_config)
with conn.cursor() as cursor:
cursor.execute(
"SELECT id, name, email FROM users WHERE email = %s AND password = %s",
(email, password)
)
user = cursor.fetchone()
if user:
response = {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"status": "success",
"user": {
"id": user[0],
"name": user[1],
"email": user[2]
}
})
}
else:
response = {
"statusCode": 401,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"status": "fail",
"message": "Invalid credentials"
})
}
logger.info(f"Returning response: {response}")
return response
except pymysql.MySQLError as e:
logger.error(f"Database error: {str(e)}")
return {
"statusCode": 500,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"status": "error",
"message": "Database error"
})
}
except Exception as e:
logger.error(f"Unexpected error: {str(e)}")
return {
"statusCode": 500,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({
"status": "error",
"message": "Internal server error"
})
}
Step11:
--Thanks
No comments:
Post a Comment