Skip to content

Instantly share code, notes, and snippets.

@urban235
Created March 3, 2018 06:44
Show Gist options
  • Save urban235/eb66aefc2082b6f0ff3dd3e34b825c87 to your computer and use it in GitHub Desktop.
Save urban235/eb66aefc2082b6f0ff3dd3e34b825c87 to your computer and use it in GitHub Desktop.
Simple server that runs in the background, collecting POST data, passing them to main service via Queue
# from https://stackoverflow.com/questions/49070708/how-to-pass-queue-to-basehttpserver
import multiprocessing
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
class QueuingHTTPServer(HTTPServer):
# def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True, queue=False):
def __init__(self, server_address, RequestHandlerClass, queue, bind_and_activate=True):
HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
self.queue = queue
class PostHTTPRequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
print("body: {}".format(body))
self.send_response(200)
self.end_headers()
response = BytesIO()
response.write(b'This is POST request. ')
response.write(b'Received: ')
response.write(body)
self.wfile.write(response.getvalue())
self.server.queue.put(body)
def run_server(port, queue):
print('run_server')
httpd = QueuingHTTPServer(('0.0.0.0', port), PostHTTPRequestHandler, queue)
httpd.timeout = 2
while True:
httpd.handle_request()
queue = multiprocessing.Queue()
p = multiprocessing.Process(target=run_server, name='serve', args=(8000, queue))
p.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment