【问题标题】:KeyError: 'requestContext', FastAPI, Mangum, ServerlessKeyError:'requestContext',FastAPI,Mangum,无服务器
【发布时间】:2020-09-02 16:47:46
【问题描述】:

我正在尝试使用无服务器框架来部署 Python Fast API WebApp。 是否与问题有关:

https://github.com/jordaneremieff/mangum/issues/126

当我使用无服务器、sls depoy 和调用函数部署它时,我收到以下错误:

[ERROR] KeyError: 'requestContext'
Traceback (most recent call last):
  File "/var/task/mangum/adapter.py", line 110, in __call__
    return self.handler(event, context)
  File "/var/task/mangum/adapter.py", line 130, in handler
    if "eventType" in event["requestContext"]:

我尝试过使用 python 3.8 和 3.7。 无法在网络上找到相同的解决方案。 还尝试使用参数 spec_version=2(我觉得这不是必需的)。

我觉得这里缺少一些东西,问题出在某个地方:

Adapter requires the information in the event and request context to form the ASGI connection scope.

想知道是否有人使用无服务器框架让 FastAPI 在 AWS Lambda 上工作。

我的处理程序:

from fastapi import FastAPI
from mangum import Mangum


app = FastAPI()
handler = Mangum(app)

@app.get("/ping")
def ping():
    return {'response': 'pong'}

serverless.yml:

provider:
  name: aws
  runtime: python3.8
  stage: dev
  region: ap-southeast-1
  memorySize: 256

functions:
  ping:
    handler: ping.handler
    events:
      - http:
          path: ping
          method: get
          cors: true

我的要求.txt

appnope==0.1.0
backcall==0.2.0
certifi==2020.6.20
chardet==3.0.4
click==7.1.2
decorator==4.4.2
fastapi==0.61.1
h11==0.9.0
httpcore==0.10.2
httptools==0.1.1
httpx==0.14.1
idna==2.10
ipython==7.17.0
ipython-genutils==0.2.0
jedi==0.17.2
mangum==0.9.2
parso==0.7.1
pexpect==4.8.0
pickleshare==0.7.5
prompt-toolkit==3.0.6
ptyprocess==0.6.0
pydantic==1.6.1
Pygments==2.6.1
requests==2.24.0
rfc3986==1.4.0
six==1.15.0
sniffio==1.1.0
starlette==0.13.6
traitlets==4.3.3
typing-extensions==3.7.4.2
urllib3==1.25.10
uvicorn==0.11.8
uvloop==0.14.0
wcwidth==0.2.5
websockets==8.1

【问题讨论】:

    标签: python aws-lambda serverless-framework fastapi


    【解决方案1】:

    问题在于 mangum 适配器期望输入类似于 AWS API Gateway shown here 指定的 event 内容。您会看到那里有一个 requestResponse 字典,Mangum 适配器似乎严格要求它运行。如果您的 AWS Lambda 事件不包含该键,那么您需要添加一个占位符字段或构造一个新的上下文字典以供其查找。

    这可以通过创建自定义处理程序as shown within this part of the Mangum docs 来完成。如果您不特别关心适配器读取的上下文内容,那么您可以获得具有以下内容的工作版本:

    def handler(event, context):
        event['requestContext'] = {}  # Adds a dummy field; mangum will process this fine
        
        asgi_handler = Mangum(app)
        response = asgi_handler(event, context)
    
        return response
    

    【讨论】:

    • 当我这样做时,我接下来会在 site-packages/mangum/adapter.py 中得到一个 KeyError: 'multiValueQueryStringParameters' 这是 Mangum 0.10.0。对于背景,我基本上是在尝试使用 sls invoke local --function myApp 在本地调用我的 lambda
    • 你能解决这个@JordanDimov 吗?
    猜你喜欢
    • 2023-01-05
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 2022-07-16
    • 2021-11-21
    • 2021-10-30
    • 1970-01-01
    • 2020-08-21
    相关资源
    最近更新 更多