Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Created October 24, 2011 03:14
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chrisguitarguy/1308286 to your computer and use it in GitHub Desktop.
Save chrisguitarguy/1308286 to your computer and use it in GitHub Desktop.
Super simple python socket server and HTTP request class.
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