将队列传递给ThreadedHTTPServer

时间:2014-02-06 20:37:58

标签: python multithreading http queue

我想将Queue对象传递给基本的ThreadedHTTPServer实现。我现有的代码工作得很好,但我想要一种安全的方式来发送和来自我的HTTP请求。通常,这可能由Web框架处理,但这是一个硬件有限的环境。

我的主要困惑在于如何传递Queue(或任何)对象以允许访问我环境中的其他模块。

我目前正在运行的基本代码模板:

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...'

1 个答案:

答案 0 :(得分:2)

您的代码未运行,但我对其进行了修改以便运行:

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...'
相关问题