import socket, traceback HOST = '' PORT = 51235 CLRF = '\r\n' class InvalidRequest(Exception): pass class Request(object): "A simple http request object" def __init__(self, raw_request): self._raw_request = raw_request self._method, self._path, self._protocol, self._headers = self.parse_request() def parse_request(self): "Turn basic request headers in something we can use" temp = [i.strip() for i in self._raw_request.splitlines()] if -1 == temp[0].find('HTTP'): raise InvalidRequest('Incorrect Protocol') # Figure out our request method, path, and which version of HTTP we're using method, path, protocol = [i.strip() for i in temp[0].split()] # Create the headers, but only if we have a GET reqeust headers = {} if 'GET' == method: for k, v in [i.split(':', 1) for i in temp[1:-1]]: headers[k.strip()] = v.strip() else: raise InvalidRequest('Only accepts GET requests') return method, path, protocol, headers def __repr__(self): return repr({'method': self._method, 'path': self._path, 'protocol': self._protocol, 'headers': self._headers}) # the actual server starts here s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.listen(5) while True: try: clientsock, clientaddress = s.accept() except KeyboardInterrupt: raise except: traceback.print_exc() try: request = clientsock.recv(1024) request = Request(request) clientsock.send(repr(request)) except(KeyboardInterrupt, SystemExit): raise except InvalidRequest, e: clientsock.send('HTTP/1.1 400 Bad Request' + CLRF) clientsock.send('Content-Type: text/html' + CLRF*2) clientsock.send('

Invalid Request: %s

' % e) except: traceback.print_exc() try: clientsock.close() except KeyboardInterrupt: raise except: traceback.print_exc()