如何在Python中实现SSE(服务器发送事件)服务器和客户端?

huangapple go评论61阅读模式
英文:

How to implement SSE (Server Sent Events) server and client in Python?

问题

我需要在Python中实现SSE服务器和客户端,以便在客户端订阅后随时向客户端发送事件。具体来说,我在服务器端使用Flask创建了一个API,客户端应该能够通过向该API发送GET请求来订阅事件通道。

我已经在线上找到了Python中SSE客户端的实现,这不应该是问题,但我找不到服务器端的实现。我只能找到服务器端的Javascript实现。

英文:

I need to implement both an SSE server and client in Python to be able to send to the clients events anytime i want after the client subscribed to it.
Specifically i have an API made with Flask in the server, the client should be able to subscribe to the event channel by sending a GET to that API.

I already found implementations of the SSE client in Python online and that shouldn't be a problem, but i can't find the server-side implementation. I can find just the Javascript implementation for the server.

答案1

得分: 3

我已经做了一些更多的研究并与其他人交流。首先,请确保始终搜索EventSource,因为这是HTML5规范中称呼它的方式。

您可以在https://pythonhosted.org/eventsource/找到一个示例,并在https://medium.com/code-zen/python-generator-and-html-server-sent-events-3cdf14140e56上找到更详细的实现方式。

最后,您所需做的就是保持HTTP连接保持打开状态。

英文:

I have done some more research and talking with others. First of all, make sure to always search for EventSource since that is what the HTML5 spec call it.

You can find one at https://pythonhosted.org/eventsource/ and a more guided way on how to implement it at https://medium.com/code-zen/python-generator-and-html-server-sent-events-3cdf14140e56

In the end, all you have to do is keep the HTTP connection open.

huangapple
  • 本文由 发表于 2023年4月4日 15:39:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75926691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定