Using Python to Setup a Simple Server


For Votizen.com 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 webserver.py:

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

class MyRequestHandler(BaseHTTPRequestHandler):
	def do_GET(self):
		try:
			if self.path.endswith(/postwebhook):
				self.send_response(200)
				self.send_header(Content-type, text/html)
				self.end_headers()
				self.wfile.write(ok)

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

				return

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

				return

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

		except:
			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():
	try:
		# you can specify any port you want by changing 81
		server = HTTPServer((, 81), MyRequestHandler)
		print starting httpserver…
		server.serve_forever()
	except KeyboardInterrupt:
		print ^C received, shutting down server
		server.socket.close()

if __name__ == __main__:
	main()

To start the server:

python /pathToServer/webserver.py

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 http://fragments.turtlemeat.com/pythonwebserver.php.