传递一个队列以ThreadedHTTPServer(Passing a Queue to Threa

2019-10-19 07:57发布

我想队列对象传递到基座ThreadedHTTPServer实现。 我现有的代码工作得很好,但我想以安全的方式发送,并从我的HTTP请求调用。 通常,这可能会通过一个Web框架来处理,但是这是一个有限的硬件环境。

我的主要困惑来自于如何通过队列(或)对象,以允许访问其他模块在我的环境。

我已经正在运行的基本代码模板:

import base64,threading,urlparse,urllib2,os,re,cgi,sys,time
import Queue

class DemoHttpHandler(BaseHTTPRequestHandler):       
    def __init__(self, request, client_address, server,qu):
        BaseHTTPRequestHandler.__init__(self, request, client_address, server)
    def do_GET(self):
        ...
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

def main():
    listen_interface = "localhost"
    listen_port = 2323  
    server = startLocalServer.ThreadedHTTPServer((listen_interface, listen_port), startLocalServer.DemoHttpHandler)
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.daemon = True
    server_thread.start()
    print 'started httpserver thread...'

Answer 1:

您的代码不运行,但我修改它,这样它会运行:

import base64,threading,urlparse,urllib2,os,re,cgi,sys,time
import Queue

class DemoHttpHandler(BaseHTTPRequestHandler):       
    def __init__(self, request, client_address, server):
        BaseHTTPRequestHandler.__init__(self, request, client_address, server)
        self.qu = server.qu # save the queue here.
    def do_GET(self):
        ...
        self.qu # access the queue self.server.qu
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

def main():
    listen_interface = "localhost"
    listen_port = 2323  
    qu = Queue.Queue()
    server = startLocalServer.ThreadedHTTPServer((listen_interface, listen_port), startLocalServer.DemoHttpHandler)
    server.qu = qu # store the queue in the server
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.daemon = True
    server_thread.start()
    print 'started httpserver thread...'


文章来源: Passing a Queue to ThreadedHTTPServer