将 fastapi 与 AWS websocket api 网关结合使用

发布于 2025-01-14 12:40:28 字数 407 浏览 3 评论 0原文

我有一个 FastAPI 在 REST api 下的 EC2 上工作,并带有一些端点。现在我想在 websocket api 下使用它。为此,我有几个问题:

  1. 在我的 FastAPI 上,我应该做什么?我读过他们介绍了 mangnum 和 magnum 的处理程序 main,但他们总是只有一个端点,而我有几个端点。
  2. 此外,他们总是使用 lambda 函数。我可以使用 EC2 吗?
  3. 在这种情况下 $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:

  1. 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.
  2. Also, they always use a lambda function. Could I use an EC2?
  3. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绳情 2025-01-21 12:40:29

我在同一个问题上花了几个星期的时间。我尝试了无数的配置,最终我没有使用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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文