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

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_server
httpd = make_server('',8888,app)
httpd.serve_forever()

验证
装饰器实现Python web框架路由功能_第1张图片

装饰器实现Python web框架路由功能_第2张图片

装饰器实现Python web框架路由功能_第3张图片

你可能感兴趣的:(python,web)