首页 > 解决方案 > 在 AWS Lambda 中部署 Python Flask Web 服务

问题描述

我编写了以下代码并使用部署包在 AWS Lambda 中进行了部署:

from flask import Flask,jsonify,request
app = Flask(__name__)

books = [
{'id': 0,
 'title': 'A Fire Upon the Deep',
 'author': 'Vernor Vinge',
 'first_sentence': 'The coldsleep itself was dreamless.',
 'year_published': '1992'},
{'id': 1,
 'title': 'The Ones Who Walk Away From Omelas',
 'author': 'Ursula K. Le Guin',
 'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',
 'published': '1973'},
{'id': 2,
 'title': 'Dhalgren',
 'author': 'Samuel R. Delany',
 'first_sentence': 'to wound the autumnal city.',
 'published': '1975'}
]



@app.route("/listbooks",methods=['GET'])
def hello():
return jsonify(books)

@app.route("/getbookbyid",methods=['GET'])
def getBybookid(event,context):
if 'id' in request.args:
    id=int(request.args['id'])

results=[]

for book in books:
    if book['id']==id:
        results.append(book)
return  jsonify(results)

我已将 API Gateway 配置为针对 GET 请求命中 lambda 函数。当我尝试使用邮递员到达终点时,我得到:

在请求上下文错误之外工作

任何指针

标签: python-3.xamazon-web-servicesflaskaws-lambda

解决方案


错误消息“在请求上下文之外工作”是 Flask 错误,而不是 API Gateway 或 Lambda 错误。当您的 Flask 应用程序尝试在request请求上下文之外访问或使用它的任何东西时,就会发生这种情况。

正如@BSQL 所暗示的,这似乎是因为您的代码缩进不正确。


推荐阅读