import uuid
class Connection(object):
CLIENTS = {}
APPLICATIONS = {}
def __call__(self, environ, start_response):
self.environ = environ
self.uuid = str(uuid.uuid4())
headers = [('Content-Type', 'text/html')]
k = None
app = environ['PATH_INFO']
try:
for k,data in enumerate(Connection.APPLICATIONS[app](self)):
if k==0:
start_response('200 OK', headers)
Connection.CLIENTS[self.uuid] = self
if isinstance(data,dict):
yield render(self.view,context=data)
elif isinstance(data,str):
yield data
elif isisnatnce(data,file):
# stream data
raise NotImplementedError
else:
raise NotImplementedError
except Exception, e:
if k is None:
start_response('500 INTERNAL ERROR',
[('Content-Type', 'text/html')])
yield str(e)
if self.uuid in Connection.CLIENTS:
del Connection.CLIENTS[self.uuid]
@staticmethod
def register(path):
def __register(f,path=path):
Connection.APPLICATIONS[path] = f
return f
return __register
### USER PROGRAM ####################
@Connection.register(path='/')
def main(connection):
yield '<html><body>'
yield 'Hello %s' % connection.environ['REMOTE_ADDR']
yield '</body></html>'
### END USER PROGRAM #################
if __name__=='__main__':
import gevent.wsgi
gevent.wsgi.WSGIServer(('', 8000),Connection()).serve_forever()