【问题标题】:Passing a Queue to ThreadedHTTPServer将队列传递给 ThreadedHTTPServer
【发布时间】:2014-02-06 20:37:57
【问题描述】:

我想将一个 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...'

【问题讨论】:

    标签: python multithreading http queue


    【解决方案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...'
    

    【讨论】:

    • 谢谢,这看起来就像我想做的那样。在如何将参数传递到此构造中时,我遇到了麻烦。
    • 对此代码的解释会有所帮助。我不确定这段代码中队列在做什么。
    • 我真的很喜欢这个;我遇到了这个问题并使用了一个全局变量。我需要回去应用这个模式。不错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多