Created
February 25, 2012 02:47
-
-
Save mpapierski/1905456 to your computer and use it in GitHub Desktop.
Yet another very general open source python web framework
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 sys | |
import re | |
from StringIO import StringIO | |
import BaseHTTPServer | |
def home_page(): | |
''' Home page ''' | |
import random | |
print 'Hello world' | |
print 'This is a random number for you', random.randint(1, 1000), '<br/>' | |
print 'Bottles of beer: <a href="/bottles">click here</a><br/>' | |
def bottles(): | |
''' Bottles of beer ''' | |
print '<br/>'.join('%(pre)s%(num)s %(bot)s on the wall, %(nul)s %(bot)s,\n<br/>%(tak)s<br/>\n' % (lambda c,b: | |
{'pre':['','%s %s on the wall.\n<br/>\n<br/>' % (c,b)][abs(cmp(c,'Ninety-nine'))], | |
'num':c, 'nul':c.lower(), 'bot':b, | |
'tak':['Go to the store and buy some more... Ninety-nine %s.' % b,'Take one down, pass it around,'][abs(cmp(x,0))] | |
})((lambda x,o: [(['Twenty','Thirty','Forty','Fifty', | |
'Sixty','Seventy','Eighty','Ninety'][x/10-2]+'-'+o.lower()).replace('-no more',''), o][int(x<20)])(x, ['No more','One','Two', | |
'Three','Four','Five','Six','Seven','Eight', | |
'Nine','Ten','Eleven','Twelve','Thirteen','Fourteen', | |
'Fifteen','Sixteen','Seventeen','Eighteen','Nineteen'][[x,x%10][int(x>=20)]]),'bottle%s of beer' % ['','s'][abs(cmp(x,1))]) | |
for x in xrange(99,-1,-1)) | |
def run_view(view): | |
old_stdout = sys.stdout | |
sys.stdout = StringIO() | |
view() | |
data = sys.stdout.getvalue() | |
sys.stdout = old_stdout | |
return data | |
class VeryGeneralOpenSourcePythonFrameworkHandler(BaseHTTPServer.BaseHTTPRequestHandler): | |
server_version = "VeryGeneralPythonFramework/1.1" | |
def do_GET(self): | |
for url, view in self.urlpatterns: | |
if re.match(url, self.path) is None: | |
continue | |
body = run_view(view) | |
self.send_response( 200 ) | |
self.send_header('Content-type', 'text/html') | |
self.send_header('Content-length', str(len(body))) | |
self.end_headers() | |
self.wfile.write(body) | |
class Web(VeryGeneralOpenSourcePythonFrameworkHandler): | |
urlpatterns = ( | |
('^/$', home_page), | |
('^/bottles$', bottles), | |
) | |
if __name__ == '__main__': | |
srvr = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), Web) | |
srvr.serve_forever() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment