Created
October 24, 2011 03:14
-
-
Save chrisguitarguy/1308286 to your computer and use it in GitHub Desktop.
Super simple python socket server and HTTP request class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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('<h1>Invalid Request: %s</h1>' % e) | |
except: | |
traceback.print_exc() | |
try: | |
clientsock.close() | |
except KeyboardInterrupt: | |
raise | |
except: | |
traceback.print_exc() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment