Last active
October 28, 2024 14:54
-
-
Save yuvalif/f4613f60c6e8435e2a2a3b8fa81f2c8c 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
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler | |
import threading | |
from multiprocessing import Process | |
import random | |
import json | |
class HTTPPostHandler(BaseHTTPRequestHandler): | |
"""HTTP POST hanler class storing the received events in its http server""" | |
def do_POST(self): | |
"""implementation of POST handler""" | |
content_length = int(self.headers['Content-Length']) | |
body = self.rfile.read(content_length) | |
print('HTTP Server received event: '+str(body)) | |
self.server.events.append(json.loads(body)) | |
print('http server has '+str(len(self.server.events))+' events') | |
if self.headers.get('Expect') == '100-continue': | |
self.send_response(100) | |
else: | |
self.send_response(200) | |
self.end_headers() | |
class HTTPServerWithEvents(ThreadingHTTPServer): | |
"""multithreaded HTTP server used by the handler to store events""" | |
def __init__(self, addr): | |
super().__init__(addr, HTTPPostHandler) | |
self.events = [] | |
self.addr = addr | |
print('http server created on '+str(addr)) | |
self.proc = Process(target=self.run) | |
self.proc.start() | |
def run(self): | |
print('http server started on '+str(self.addr)) | |
self.serve_forever(poll_interval=0.1) | |
print('http server ended on '+str(self.addr)) | |
def get_and_reset_events(self): | |
print('get_and_reset_events: http server has '+str(len(self.events))+' events') | |
events = self.events | |
self.events = [] | |
return events | |
def close(self): | |
print('http server on '+str(self.addr)+' starting shutdown') | |
p = Process(target=self.shutdown) | |
p.start() | |
p.join(5) | |
if self.proc.is_alive(): | |
print('http server on '+str(self.addr)+' still alive. killing it hard') | |
p.terminate() | |
self.proc.terminate() | |
print('http server on '+str(self.addr)+' shutdown ended') | |
import requests | |
def post_request(url): | |
print(requests.post(url, json={'hello': 'world'})) | |
host = 'localhost' | |
port = random.randint(10000, 20000) | |
# start an http server in a separate thread | |
http_server = HTTPServerWithEvents((host, port)) | |
url_post = 'http://'+host+':'+str(port) | |
client_threads = [] | |
for i in range(100): | |
t = threading.Thread(target=post_request, args=(url_post,)) | |
t.start() | |
client_threads.append(t) | |
[thr.join() for thr in client_threads] | |
for event in http_server.get_and_reset_events(): | |
print(event) | |
http_server.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment