Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

python 3.x - Getting "Internal Server Error" 502:Bad Gateway Error

I have just started working on AWS. I am building a system connection between lambda, RDS MYSQL Database and API gateway.

Created a lambda function in python which inserts the data into the MYSQL database and configured API gateway with the lambda function. and when I am testing the lambda function within lambda console, everything is working fine. but when I am trying to call API from postman, it results in "message": "Internal server error" and 502 bad gateway.

import pymysql
import sys
import logging
import json

logger = logging.getLogger()
logger.setLevel(logging.INFO)

try:
    conn = pymysql.connect(
        host='',
        port=int(3306),
        user="",
        passwd="",
        db="")
except:
    logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
    sys.exit()

logger.info("SUCCESS: Connection to RDS mysql instance succeeded")

cursor=conn.cursor()

def lambda_handler(event, context):
    print(event)
    
    http_method = event['httpMethod']
    
    if http_method == "GET":
        Serial_Number = int(event['queryStringParameters']['Serial_Number'])
        platform = int(event['queryStringParameters']['platform'])
        architecture = int(event['queryStringParameters']['architecture'])
        
    elif http_method == "POST":
        body = json.loads(event['body'])
        
        Serial_Number = body['Serial_Number']
        platform = body['platform']
        architecture = body['architecture']
        
    return{
        'statusCode' : 200,
        'headers': {'Content-Type': 'application/json'},
        'body' : json.dumps(Insertion(Serial_Number, platform, architecture)),
        'messageReason' : "Successfully updated Details"
    }
    
def Insertion(Serial_Number, platform, architecture):
    item_count = 0
    
    with conn.cursor() as cur:
        cur.execute("insert into system_data (Serial_Number, platform, architecture) values(%s, %s, %s)", (Serial_Number, platform, architecture))

        conn.commit()
        cur.execute("select * from system_data")
        
        for row in cur:
            item_count += 1
            logger.info(row)
    return "Added %d items to RDS MySQL table" %(item_count)

But when I am trying to call API with postman, I am getting "internal server error" in postman.

question from:https://stackoverflow.com/questions/65841414/getting-internal-server-error-502bad-gateway-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Http status 502 in Api Gateway with Lambda Integration is related to a bad-formatted response from lambda. The valid structure of response is described in this guide https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format

This is why in lambda test console you get a 200 - OK response as it is a valid general json but testing from Api Gateway is not valid as is not the expected structure.

From your code, the problem is originated due to a non-valid field "messageReason" in response. Try removing this field and include it in headers or body


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...