简体   繁体   中英

Can't connect to Lambda or EC2 from my local computer through python requests

I'm new at AWS and I'm trying to deploy a simple lambda service and call it from my local computer.

Lambda:

import json
import pandas
def lambda_handler(event, context):
    message = 'Hello {} {}!'.format(event['first_name'], 
                                    event['last_name'])  
    return { 
        'message' : message
    } 

When I run a test on AWS env it does work, but when I try to do the same kind of test on python I get the 502 error with rest API on API gateway, and error 500 on HTTP API also on API gateway.

Test AWS: { "first_name": "alooo", "last_name": "arrombado" }

Local Python Test:

import resquests
r2 = requests.post('https://ia81y8e8ye.execute-api.eu-west-3.amazonaws.com/default/PortAPI',
                   json = {'first_name':'jose','last_name':'example'})
r2
<Response [502]>

The same kind of problem happen on EC2 instance when try to deploy an python flask API.

With Lambda I didn't use any kind of permission, so I think it has a open traffic. In other hand, in EC2 I set inbound and outbound, all communications to anywhere.

I don't know if more info is needed.

Thanks for the help.

If you run the following:

print(r2.content)

you will see that you get:

b'{"message": "Internal server error"}'

This likely means that your lambda most likely failed . In that case you have to check CloudWatch Logs and search for any error message.

And this can happen because you may be using incorrect event in your function, and/or returning incorrect response type. Structure of event object for proxy integration is here for reference. Other reason could by missing pandas in your lambda.

Example of correct lambda function

Assuming lambda proxy integration, the correct function would be:

import json

def lambda_handler(event, context):    
    
    body = json.loads(event['body'])
    
    print(body)
    
    message = 'Hello {} {}!'.format(body['first_name'], 
                                    body['last_name'])  
    return {
        "statusCode": 200,
        'body' : message
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM