Skip to content

Instantly share code, notes, and snippets.

@alisey
Created August 8, 2014 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alisey/a6663a87287a207a6c09 to your computer and use it in GitHub Desktop.
Save alisey/a6663a87287a207a6c09 to your computer and use it in GitHub Desktop.
Quick and dirty HTTP server in Python based on socketserver lib
import socketserver # In Python 2 use "import SocketServer" instead
class RequestHandler(socketserver.StreamRequestHandler):
def handle(self):
command = self.rfile.readline()[5:-11].decode('UTF-8')
print(command)
if command == 'sleep':
self.respond('Going to sleep')
elif command == 'wakeup':
self.respond('Waking up')
else:
self.respond('Unknown command')
def respond(self, body):
headers = '\r\n'.join([
'HTTP/1.1 200 OK',
'Connection: close',
'Content-Type: text/plain; charset=UTF-8',
'Content-Length: %d' % len(body.encode('UTF-8')),
'Access-Control-Allow-Origin: *'
])
self.wfile.write((headers + '\r\n\r\n' + body).encode('UTF-8'))
HOST, PORT = '0.0.0.0', 8000
print("Listening on http://%s:%d" % (HOST, PORT))
socketserver.ThreadingTCPServer((HOST, PORT), RequestHandler).serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment