装饰器实现Python web框架路由功能

来源:互联网 发布:超级搜索软件 编辑:程序博客网 时间:2024/06/05 12:04

Python版本:2.7
类似flask路由功能的实现
关键点
(1)__call__方法的使用
(2)装饰器的使用
(3)对WSGI的理解
代码实现

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):        path = environ['PATH_INFO']        if path in self.routes:            status = '200 OK'            response_headers = [('Content-Type','text/plain')]            start_response(status,response_headers)            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 ['index']@app.route('/hello')def hello():    return ['hello world']from wsgiref.simple_server import make_serverhttpd = make_server('',8888,app)httpd.serve_forever()

验证
这里写图片描述

这里写图片描述

这里写图片描述