Python learning-compile a simple web Framework (2)
A bottle. A simple example of py to see how bottle is used. The code is from http://www.bottlepy.org/docs/0.12/index.html: copy the code from bottle import route, run, template @ route ('/hello/<name> ') def index (name): return template ('<B> Hello {name }}</B>! ', Name = name) run (host = 'localhost', port = 8080) copy the code. It is clear that the bottle is routed using the decorator. According to the bottle design, I will write a simple framework. The Python modifier, as its name implies, encapsulates a function. While the function is not changed, the function is dynamically added. More details are not discussed here. According to the definition of WSGI, a wsgi application must be callable. So the following is a general framework of a WSGI application: class WSGIapp (object): def _ init _ (self): pass def route (self, path = None ): pass def _ call _ (self, environ, start_response): return self. wsgi (environ, start_response) def wsgi (self, environ, start_response): pass where the route method is used to save the url-> target. For convenience, save url-> target in the dictionary: def route (self, path = None): def decorator (func): self. routes [path] = func return decorator here return func can also be commented out. Please explain it !! Then every method of WSGIapp is implemented: copy the code class WSGIapp (object): def _ init _ (self): self. routes = {} def route (self, path = None): def decorator (func): self. routes [path] = func return decorator def _ call _ (self, environ, start_response): print 'call' return self. wsgi (environ, start_response) def wsgi (self, environ, start_response): path = environ ['path _ info'] print PATH if path in self. routes: status = '20180101' OK 'response_headers = [('content-type', 'text/plain ')] start_response (status, response_headers) print self. routes [path] () return self. routes [path] () else: status = '2014 Not Found 'response_headers = [('content-type', 'text/plain')] start_response (status, response_headers) return '2014 Not Found! 'App = WSGIapp () @ app. route ('/') def index (): return ['this is Index'] @ app. route ('/hello') def hello (): return ['hello'] from wsgiref. simple_server import make_serverhttpd = make_server ('', 8000, app) print 'start .... 'httpd. serve_forever ()