Created
March 20, 2023 23:19
-
-
Save slotrans/c55be6e971afa761db9e47836b5a5e4a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import random | |
import threading | |
import time | |
from queue import Queue | |
from collections import Counter | |
from flask import Flask | |
from gevent.pywsgi import WSGIServer | |
from loguru import logger as log | |
class Producer: | |
def __init__(self, msg_queue): | |
self.msg_queue = msg_queue | |
self.rng = random.Random() | |
self.send_count = 0 | |
def run(self): | |
while True: | |
num = self.rng.randrange(0, 10) | |
log.info(f"sending {num}") | |
self.msg_queue.put(num) | |
self.send_count += 1 | |
time.sleep(0.25) | |
class Consumer: | |
def __init__(self, msg_queue): | |
self.msg_queue = msg_queue | |
self.counter = Counter() | |
self.recv_count = 0 | |
def run(self): | |
while True: | |
num = self.msg_queue.get() | |
log.info(f"received {num}") | |
self.counter.update({num: 1}) | |
self.recv_count += 1 | |
self.msg_queue.task_done() | |
def build_app(producer, consumer): | |
app = Flask(__name__) | |
@app.get("/hello") | |
def hello(): | |
return "<html><body><h1>hello, world!</h1></body></html>" | |
@app.get("/stats") | |
def stats(): | |
send_count = producer.send_count | |
recv_count = consumer.recv_count | |
counter = consumer.counter | |
return f""" | |
<html> | |
<head><title>Stats!</title></head> | |
<body> | |
<p> | |
The producer has sent {send_count} messages. | |
</p> | |
<p> | |
The consumer has received {recv_count} messages, with the following distribution: | |
<table> | |
<tr><th>Number</th><th>Count</th></tr> | |
<tr><td>0</td><td>{counter[0]}</td></tr> | |
<tr><td>1</td><td>{counter[1]}</td></tr> | |
<tr><td>2</td><td>{counter[2]}</td></tr> | |
<tr><td>3</td><td>{counter[3]}</td></tr> | |
<tr><td>4</td><td>{counter[4]}</td></tr> | |
<tr><td>5</td><td>{counter[5]}</td></tr> | |
<tr><td>6</td><td>{counter[6]}</td></tr> | |
<tr><td>7</td><td>{counter[7]}</td></tr> | |
<tr><td>8</td><td>{counter[8]}</td></tr> | |
<tr><td>9</td><td>{counter[9]}</td></tr> | |
</table> | |
</p> | |
</body> | |
</html> | |
""" | |
return app | |
def main() -> int: | |
queue = Queue() | |
producer = Producer(queue) | |
consumer = Consumer(queue) | |
producer_thread = threading.Thread(target=producer.run).start() | |
consumer_thread = threading.Thread(target=consumer.run).start() | |
http_server = WSGIServer(("127.0.0.1", 5050), build_app(producer, consumer)) | |
http_server.serve_forever() | |
return 0 | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment