forked from mario-gellrich-zhaw/kafka_buslines_zuerich
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
33 lines (25 loc) · 928 Bytes
/
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
from flask import Flask, render_template, Response
from pykafka import KafkaClient
def get_kafka_client():
return KafkaClient(hosts='localhost:9092')
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
# Consumer API
@app.route('/topic/<topicname>')
def get_messages(topicname):
client = get_kafka_client()
# Convert the topic name to a byte string
topicname_bytes = topicname.encode('utf-8')
def events():
for i in client.topics[topicname_bytes].get_simple_consumer():
if i.value is not None:
try:
yield f'data:{i.value.decode("utf-8")}\n\n'
except UnicodeDecodeError as e:
print(f"Error decoding message: {e}")
continue
return Response(events(), mimetype="text/event-stream")
if __name__ == '__main__':
app.run(debug=True, port=5001)