Py.Cafe

CNFeffery/

dash-sse-data-stream

Dash SSE Data Stream

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import time
import json
import dash
from dash import html
from flask import Response

app = dash.Dash(__name__)


@app.server.route("/stream")
def stream():
    def _stream():
        for i in range(999):
            time.sleep(1)
            yield "data: {}\n\n".format(json.dumps({"timestamp": time.time()}))

    response = Response(_stream(), mimetype="text/event-stream")
    response.headers.update(
        {
            "Cache-Control": "no-cache",
            "Transfer-Encoding": "chunked",
        }
    )

    return response


app.layout = html.Div(
    ["SSE Example: ", html.A("/stream", href="/stream")], style={"padding": 50}
)

if __name__ == "__main__":
    app.run(debug=True)