Skip to content

Instantly share code, notes, and snippets.

@razius
Created September 24, 2014 14:45
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 razius/4c54c81fab74d9118fd1 to your computer and use it in GitHub Desktop.
Save razius/4c54c81fab74d9118fd1 to your computer and use it in GitHub Desktop.
A very simple web framework and application
import re
import traceback
class wsgiapplication(object):
"""Base class for wsgiapplication."""
def __init__(self, environ, start_response):
self.environ = environ
self.start = start_response
self.status = '200 OK'
self._headers = []
def __iter__(self):
try:
x = self.delegate()
self.start(self.status, self._headers)
except:
headers = [('Content-Type', 'text/plain')]
self.start('500 Internal Error', headers)
x = 'Internal Error:\n\n' + traceback.format_exc()
if isinstance(x, str):
return iter([x])
else:
return iter(x)
def header(self, name, value):
self._headers.append((name, value))
def delegate(self):
path = self.environ.get('PATH_INFO')
method = self.environ.get('REQUEST_METHOD')
for pattern, name in urls:
m = re.match('^' + pattern + '$', path)
if m:
args = m.groups()
funcname = '%s_%s' % (method.upper(), name)
func = getattr(self, funcname)
return func(*args)
return self.notfound()
def notfound(self):
self.status = '404 Not Found'
self.header('Content-type', 'text/plain')
return 'Not Found\n'
urls = [
('/', 'index'),
('/(.*)', 'names'),
]
class application(wsgiapplication):
def GET_index(self):
self.header('Content-type', 'text/plain')
return 'Hello world!\n'
def GET_name(self, name):
self.header('Content-type', 'text/plain')
return 'Hello %s!\n' % name
if __name__ == '__main__':
from wsgiref.simple_server import make_server
srv = make_server('localhost', 8080, application)
srv.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment