乐闻世界logo
搜索文章和话题

How do I close a Server-Send Events connection in Flask?

1个答案

1

In Flask, Server-Sent Events (SSE) is a technology that enables the server to proactively send information to the client. Typically, SSE establishes a persistent connection through which the server can push data to the client. However, in certain scenarios, closing this connection may be necessary. This can be achieved in several ways:

1. Client-Side Connection Closure

On the client side, the SSE connection can be closed using JavaScript. This is typically done by invoking the close() method of the EventSource object. For example:

javascript
var eventSource = new EventSource("/path/to/sse"); // When no longer needed eventSource.close();

2. Server-Side Connection Closure

On the server side, Flask does not provide a built-in method to directly close SSE connections, as these connections are maintained by continuously sending data chunks to keep the connection active. However, we can indirectly close the connection by stopping data transmission on the server side. The following is an example implementation in a Flask application:

python
from flask import Flask, Response import time app = Flask(__name__) @app.route('/stream') def stream(): def generate(): for i in range(10): # Send 10 data chunks and then close yield f"data: {i}\n\n" time.sleep(1) yield "event: close\n\n" # Notify the client to close the connection return Response(generate(), mimetype='text/event-stream') if __name__ == '__main__': app.run()

In this example, the server sends 10 data chunks and then transmits a special event event: close, which the client can listen for to close the connection.

3. Using Timeout Mechanisms

Another approach is to implement a timeout on the server side. If no data is sent within a specified duration, the connection is automatically closed. This method is suitable for advanced scenarios and requires additional configuration.

Conclusion

In Flask, closing SSE connections typically requires client-side action or indirect implementation on the server side. The choice of method depends on the specific requirements and scenarios of the application. When designing SSE functionality, consider connection management and resource optimization to ensure application performance and stability.

2024年8月15日 20:23 回复

你的答案