【发布时间】:2020-09-19 01:04:08
【问题描述】:
总结
我有一个使用 gunicorn 启动的烧瓶服务器,它创建了一个我想从 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 上,以防安全组接受所有出站和入站流量。
Lambda 函数
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)))
Flask 端点
@app.route('/api/v1/my_project', methods=['GET', 'POST'])
def my_project():
content = request.get_json()
...
return jsonify(full_pre_json)
Gunicorn 配置
bind = "0.0.0.0:8000"
workers = 1
timeout = 3 * 60 # 3 minutes
【问题讨论】:
-
ip_of_ec2是私有IP还是公共IP? -
我相信是公开的
标签: python flask amazon-ec2 aws-lambda gunicorn