I am trying to run a python script from within a python plugin. The script runs a CGIHTTPServer in a separate thread. It works as expected when executed from the command line and i can issue requests from the browser but when run from the plugin as an import the browser never loads the issued request. Any advice?
Here is my server code:
"""
A stoppable, threadable version of Jurgen's origin server
"""
import CGIHTTPServer
import BaseHTTPServer
import httplib
import threading
import sys
class RequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ['/scripts']
def do_QUIT (self):
"""Send 200 OK response, and set server.stop to True"""
self.send_response(200)
self.end_headers()
self.server.stop = True
class StoppableHttpServer(BaseHTTPServer.HTTPServer):
"""A http server that reacts to self.stop flag"""
def serve_forever (self):
"""Handle one request at a time until stopped."""
self.stop = False
while not self.stop:
sys.stdout.flush()
self.handle_request()
class ServerInThread(threading.Thread):
"""A class designed to start a stoppable HttpServer in a separate thread."""
def __init__(self):
"""Initialize the port to use for the server and start the thread"""
self.port = 3030
threading.Thread.__init__(self)
def run(self):
"""Method that is called when the start() method of an instance is called"""
server = StoppableHttpServer(("", self.port), RequestHandler)
server.serve_forever()
def stop_server(port):
"""send QUIT request to http server"""
conn = httplib.HTTPConnection("localhost:%d" % port)
conn.request("QUIT", "/")
conn.getresponse()
And this is what my qgis plugin does. It has 2 button with the following methods:
from syncServer import *
# other initialization code
# Method to start the server
def startServer(self):
"""Start sync server in a seperate thread"""
# check if server instance exists
if not hasattr(self, 'threaded_server') or self.threaded_server is None:
self.logger.info("Starting new server thread")
self.threaded_server = ServerInThread()
self.logger.info("Starting server")
self.threaded_server.start()
self.logger.info("Serving at port %d", self.threaded_server.port)
else:
self.logger.info("A server thread already exists")
# Method to stop the server
def stopServer(self):
"""Stop sync server via http request"""
# check if server instance exists
if hasattr(self, 'threaded_server') and self.threaded_server is not None:
self.logger.info("Stopping server")
stop_server(self.threaded_server.port)
self.logger.info("Stopped server")
self.threaded_server = None
else:
self.logger.info("No server thread exists")
Thanks in advance.