Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Created March 27, 2014 16:37
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 thomasballinger/9811898 to your computer and use it in GitHub Desktop.
Save thomasballinger/9811898 to your computer and use it in GitHub Desktop.
import socket
# see wsgiref.simple_server for a real implementation of a WSGI server
def serve(app):
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(('', 8080))
listener.listen(5)
while True:
s, addr = listener.accept()
print 'server received connection from', addr
request = s.recv(10000)
print 'request we received:', request
method, rest = request.split(' ', 1)
path, rest = rest.split(None, 1)
environ = {'REQUEST_METHOD': method, "PATH_INFO":path}
def start_response(status, headers):
print 'sending headers'
stuff = '\r\n'.join(['HTTP/0.9 '+status] + [k+': '+v for k, v in headers])
print stuff
s.send(stuff)
s.send('\r\n\r\n')
for data in app(environ, start_response):
print 'sending data'
s.send(data)
s.close()
#WSGI: give me a function, I will call it with two things: the environment (a big dict of stuff you want)
# and a function that you should call with two arguments: the response code and the headers you want to send
class Request(object):
"""A fancy object to represent the request so we don't have to understand the ENVIRON dictionary"""
def __init__(self, environ):
self.path = environ['PATH_INFO']
self.mathod = environ['REQUEST_METHOD']
def get_split_path(self):
import os; return os.path.split(self.path)
def wsgihandler(environ, start_response):
start_response("200 OK", [('Content-Type','text/plain')])
r = Request(environ)
return [('You asked to '+r.method+' '+r.path), 'asdf']
if __name__ == '__main__':
serve(wsgihandler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment