繁体   English   中英

在 AWS 中部署 Python Flask Web 服务 Lambda

[英]Deploying Python Flask Web service in AWS Lambda

我编写了以下代码并使用部署 package 部署在 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 网关来访问 lambda function 以获得 GET 请求。 当我尝试使用 postman 到达终点时,我得到:

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

任何指针

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

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

请添加以下行。 它会解决你的错误。

app.app_context().push()

-Prasanna.K

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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