Using Python to Setup a Simple Server

For we are trying to setup continous deployment. Our first attempt to make it work was to leverage the post web hooks provided by our repository manager. For webhooks you need to have a URL that is not powered by any service you wish to restart. Originally, I setup this URL using various off-the-shelf webservers, but they all seemed overkill for what I wanted to do. Instead I leveraged built in features of Python to create a very simple webserver that handles only the URIs the developer specifies.

How do it…

Here is the code that should be saved to

import string, cgi, time, os
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class MyRequestHandler(BaseHTTPRequestHandler):
	def do_GET(self):
			if self.path.endswith(/postwebhook):
				self.send_header(Content-type, text/html)

				# your logic for this URL here, such as executing a bash script
				rs = os.popen(python /pathToFile/ &)


			if self.path.endswith(anotherURI):
				# do something else


				self.send_error(404, File Not Found %s % self.path)

			self.send_error(404, File Not Found %s % self.path)

	def do_POST(self):
		self.do_GET() # currently same as post, but can be anything

def main():
		# you can specify any port you want by changing 81
		server = HTTPServer((, 81), MyRequestHandler)
		print starting httpserver…
	except KeyboardInterrupt:
		print ^C received, shutting down server

if __name__ == __main__:

To start the server:

python /pathToServer/

How it works…

Python comes equipped with the ability to run an HTTP server, and a request handler. The main function of this snippet starts the server at a given port and delegates requests to the MyRequestHandler. It keeps the server running indefinitely, until control C is pressed. When extending the BaseHTTPRequestHandler the do_GET and do_POST function need to be defined to handle GET and POST requests.

In this example the POST request handler just delegates to the GET request handler. The GET request handler evaluates the PATH for a couple of URLs that you want to support. You need to define the request headers, but you can write anything out, such as HTML, JSON, XML, or in this case, just the word OK. When there is an error, use the send_error function to return an error and message.

There’s more…

This code was originally based on work by Jon Berg at