如何将Queue传递给baseHTTPServer

时间:2018-03-02 14:02:33

标签: python basehttpserver

我在下面使用Thread的示例,一个简单的http服务器来监听post请求并收集主进程的数据。 我想将它转换为使用多处理并传递队列以收集POST数据,但我不知道如何传递它,任何想法如何这样做?

from threading import Thread
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO

KEEP_RUNNING = True
COLLECT_POST_DATA = []

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        print("body: {}".format(body))
        COLLECT_POST_DATA.append(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())

def run_server(port):
    httpd = HTTPServer(('0.0.0.0', port), SimpleHTTPRequestHandler)
    httpd.timeout = 1
    while KEEP_RUNNING:
        httpd.handle_request()
    # httpd.serve_forever()

t = Thread(target = run_server, args=(8000,))
t.start()

# to kill
KEEP_RUNNING = False

1 个答案:

答案 0 :(得分:1)

所以我解决了这个问题:

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()
    # httpd.serve_forever()

queue = multiprocessing.Queue()
p = multiprocessing.Process(target=run_server, name='serve', args=(8000, queue))
p.start()

尝试:

curl hostip:8000 -m 5 -d"12.12.12.12"

然后从剧本:

data = queue.get(timeout=2)

杀死:

p.terminate()