Created
September 24, 2014 14:45
-
-
Save razius/4c54c81fab74d9118fd1 to your computer and use it in GitHub Desktop.
A very simple web framework and application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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