Skip to content

Instantly share code, notes, and snippets.

Created March 27, 2014 16:37
Show Gist options
  • 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))
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
for data in app(environ, start_response):
print 'sending data'
#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__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment