将 fastapi 与 AWS websocket api 网关结合使用
我有一个 FastAPI 在 REST api 下的 EC2 上工作,并带有一些端点。现在我想在 websocket api 下使用它。为此,我有几个问题:
- 在我的 FastAPI 上,我应该做什么?我读过他们介绍了 mangnum 和 magnum 的处理程序 main,但他们总是只有一个端点,而我有几个端点。
- 此外,他们总是使用 lambda 函数。我可以使用 EC2 吗?
- 在这种情况下 $connection 和 $disconnection 如何工作?我必须在 fastapi 中引入什么才能仍然使用我的端点?
我的 fastapi 内的进程可能需要很长时间才能响应(例如 20 秒)。因此,我需要转向 websocket 以避免超时。如果您认为我可以以不同的方式提供更好的解决方案,我很乐意了解。
I have a FastAPI working on an EC2 under REST api with some endpoints. Now I would like to use it under a websocket api. To do this I have a few questions:
- On my FastAPI, what shoud I do? I have read they introduce mangnum and a handler main for magnum, but they always have only one endpoint and I have several endpoints.
- Also, they always use a lambda function. Could I use an EC2?
- How do $connection and $disconnection work in this case? What do I have to introduce in my fastapi so I can still use my endpoints?
Processes inside my fastapi can take long to answer (eg. 20s). Therefore, I need to move to websocket to avoid timeouts. If you think I can have a better solution in a different way I'll happy to know about it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(1)
我在同一个问题上花了几个星期的时间。我尝试了无数的配置,最终我没有使用FastAPI。我用基本的 lambda_handler(event, context) 函数替换了 @app.websocket,以便我可以按照 AWS 文档使用连接、断开连接和发送消息处理程序。直到今天我仍然不知道如何使用 FastAPI 来做到这一点,这让我很烦恼。您找到解决方案了吗?
这有帮助 - https://docs.aws.amazon.com/code-samples/latest/catalog/code-catalog-python-cross_service-apigateway_websocket_chat.html
编辑此内容以添加我正在使用 python。
I have spent weeks on this same issue. I tried countless configurations and in the end I ended up not using FastAPI. I replaced my @app.websocket with a basic lambda_handler(event, context) function so that I could use the the connect, disconnect and sendmessage handlers as per AWS documentation. To the day I still can't figure out how to do it with FastAPI and it bugs me. Have you found a solution to this?
This helped - https://docs.aws.amazon.com/code-samples/latest/catalog/code-catalog-python-cross_service-apigateway_websocket_chat.html
Editing this to add that I am using python.