2

I would like to pass a Queue object to a base ThreadedHTTPServer implementation. My existing code works just fine, but I would like a safe way to send calls to and from my HTTP requests. Normally this would probably be handled by a web framework, but this is a HW limited environment.

My main confusion comes on how to pass the Queue (or any) object to allow access to other modules in my environment.

The base code template I have currently running:

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...'
radix07
  • 1,506
  • 1
  • 17
  • 22

1 Answers1

3

Your code does not run but I modified it so that it will run:

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...'
Superdooperhero
  • 7,584
  • 19
  • 83
  • 138
User
  • 14,131
  • 2
  • 40
  • 59
  • Thank you, that looks like it does what I was looking to do. I was having troubles following how to pass an argument into this construct. – radix07 Feb 06 '14 at 21:33
  • An explanation of this code would help. I'm not sure what the queue is doing in this code. – Superdooperhero Jan 22 '19 at 22:10
  • I really like this; I met this problem and used a global variable. I need to go back and apply this pattern. Nice one. – S Meaden Aug 26 '19 at 10:21