-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathapplication.py
58 lines (45 loc) · 1.68 KB
/
application.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import json
import logging
import random
import sys
import time
from datetime import datetime
from typing import Iterator
from flask import Flask, Response, render_template, request, stream_with_context
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
application = Flask(__name__)
random.seed() # Initialize the random number generator
@application.route("/")
def index() -> str:
return render_template("index.html")
def generate_random_data() -> Iterator[str]:
"""
Generates random value between 0 and 100
:return: String containing current timestamp (YYYY-mm-dd HH:MM:SS) and randomly generated data.
"""
if request.headers.getlist("X-Forwarded-For"):
client_ip = request.headers.getlist("X-Forwarded-For")[0]
else:
client_ip = request.remote_addr or ""
try:
logger.info("Client %s connected", client_ip)
while True:
json_data = json.dumps(
{
"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"value": random.random() * 100,
}
)
yield f"data:{json_data}\n\n"
time.sleep(1)
except GeneratorExit:
logger.info("Client %s disconnected", client_ip)
@application.route("/chart-data")
def chart_data() -> Response:
response = Response(stream_with_context(generate_random_data()), mimetype="text/event-stream")
response.headers["Cache-Control"] = "no-cache"
response.headers["X-Accel-Buffering"] = "no"
return response
if __name__ == "__main__":
application.run(host="0.0.0.0", threaded=True)