我有一个用gunicorn旋转的flask服务器,该服务器创建了一个我想从AWS lambda函数调用的端点。但是,当我在Lambda中运行测试时,它返回
"errorMessage": "HTTPConnectionPool(host='<ip_of_ec2>', port=8000): Max retries exceeded with url: /api/v1/my_project(Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7efec823ed60>: Failed to establish a new connection: [Errno 111] Connection refused'))",
"errorType": "ConnectionError",
"stackTrace": [
" File \"/var/lang/lib/python3.8/imp.py\", line 234, in load_module\n return load_source(name, filename, file)\n",
...
" File \"/var/task/requests/adapters.py\", line 516, in send\n raise ConnectionError(e, request=request)\n"
]
}
我需要在AWS中进行什么样的配置才能允许此调用,或者我缺少什么才能使lambda函数建立此连接。
不用说,一切都在本地工作(我可以运行curl来调用EC2上的端点并建立连接)。 Lambda和EC2位于同一vpc上,以防万一安全组接受所有出站和入站流量。
import requests
print('Loading function')
url = 'http://<ip_of_ec2>:8000/api/v1/my_project'
def respond(err, res=None):
return {
'statusCode': '400' if err else res.status_code,
'body': err.message if err else res.json(),
'headers': {
'Content-Type': 'application/json',
},
}
def call_project(claim, link):
return requests.post(url=url, json={"claim": claim, "link": link})
def lambda_handler(event, context):
operations = {
'POST': lambda x: call_project(**x)
}
operation = event['httpMethod']
if operation in operations:
payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body'])
return respond(None, operations[operation](payload))
else:
return respond(ValueError('Unsupported method "{}"'.format(operation)))
@app.route('/api/v1/my_project', methods=['GET', 'POST'])
def my_project():
content = request.get_json()
...
return jsonify(full_pre_json)
bind = "0.0.0.0:8000"
workers = 1
timeout = 3 * 60 # 3 minutes
尝试将AWS Lambda配置为具有执行角色,以便与同一VPC中的aws资源进行交互。
执行角色:https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html
教程:https://docs.aws.amazon.com/lambda/latest/dg/services-rds-tutorial.html