python-3.x - 在 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 函数。当我尝试使用邮递员到达终点时,我得到:
在请求上下文错误之外工作
任何指针
解决方案
错误消息“在请求上下文之外工作”是 Flask 错误,而不是 API Gateway 或 Lambda 错误。当您的 Flask 应用程序尝试在request
请求上下文之外访问或使用它的任何东西时,就会发生这种情况。
正如@BSQL 所暗示的,这似乎是因为您的代码缩进不正确。
推荐阅读
- android - 找不到带有哈希字符串“android-P”的目标安装缺少的平台并同步项目
- ffmpeg - 从 Raspberry Pi 上的 USB 摄像头获取原始 h264 数据包
- google-cloud-platform - Google Cloud IOT,通过 API 阻止通信
- javascript - 如何识别纯文本网站地址并将它们包装在 href 标记中?
- excel - 使用范围粘贴到活动单元格
- swift - 精灵不消失
- typescript - 返回 Promise 的 TypeScript 类型函数
- python - numpy 数组内存大于预期
- python - 带有 unicode 字符串的 json.loads
- javascript - 如何将未知数量的值作为键值对中的键传递?(Javascript)