Python learning, python
In the previous log, we discussed and implemented the corresponding application based on the url, and read the bottle. the official py document was rewritten according to the bottle design. It mainly draws on the design ideas of the experts.
A simple bottle. py instance
Let's take a look at how bottle is used. The code is from http://www.bottlepy.org/docs/0.12/index.html:
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)
Obviously, the bottle is routed using the decorator. According to the bottle design, I will write a simple framework.
Python decorator
As the name suggests, the decorator encapsulates a function. While the function is not changed, the function is dynamically added. More details are not discussed here.
General framework
According to WSGI, a wsgi application must be callable. The following is a general WSGI application framework:
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
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 func return decorator
Here, return func can be commented out. Please explain it !!
Then every method of WSGIapp is implemented:
class WSGIapp(object): def __init__(self): self.routes = {} def route(self,path=None): def decorator(func): self.routes[path] = func return 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 = '200 OK' response_headers = [('Content-Type','text/plain')] start_response(status,response_headers) print self.routes[path]() return self.routes[path]() else: status = '404 Not Found' response_headers = [('Content-Type','text/plain')] start_response(status,response_headers) return '404 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()
In this way, the prototype of a simple web framework is implemented. If you add a regular expression to the path in the decorator, you can easily cope with the URL. The next log is added to the template engine jinja2.