Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import threading
import SocketServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import httplib2
class QuietSimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
"""Quiet http request handler
Subclasses SimpleHTTPRequestHandler in order to overwrite the log_message
method, letting us reduce output generated by the handler. Only standard
messages are overwritten, so errors will still be displayed.
"""
def log_message(self, *args):
"""Drops messages intended to be printed
"""
pass
class ThreadedHTTPServer(object):
"""Runs SimpleHTTPServer in a thread
Lets you start and stop an instance of SimpleHTTPServer.
"""
def __init__(self, host, port, request_handler=SimpleHTTPRequestHandler):
"""Prepare thread and socket server
Creates the socket server that will use the HTTP request handler. Also
prepares the thread to run the serve_forever method of the socket
server as a daemon once it is started
"""
SocketServer.TCPServer.allow_reuse_address = True
self.server = SocketServer.TCPServer((host, port), request_handler)
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.daemon = True
def __enter__(self):
self.start()
return self
def __exit__(self, type, value, traceback):
self.stop()
def start(self):
"""Start the HTTP server
Starts the serve_forever method of Socket running the request handler
as a daemon thread
"""
self.server_thread.start()
def stop(self):
"""Stop the HTTP server
Stops the server and cleans up the port assigned to the socket
"""
self.server.shutdown()
self.server.server_close()
if __name__ == "__main__":
# Start the threaded server
handler = QuietSimpleHTTPRequestHandler
with ThreadedHTTPServer("localhost", 8000, request_handler= handler) as server:
# Make the request
http_session = httplib2.Http()
response = http_session.request("http://localhost:8000/")
print response[0]["status"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment