装饰器实现路由控制

来源:互联网 发布:激光打标机做图软件 编辑:程序博客网 时间:2024/05/29 09:55

part 1

def application(env, start_response):    print(env['PATH_INFO'])    status = '200 OK'    response_headers = [('Content-Type', 'text/html')]    start_response(status, response_headers)    return ['您请求的路径为:{}'.format(env['PATH_INFO']).encode('utf8')]
from webapplication import application as appfrom wsgiref.simple_server import make_serverserver = make_server('', 8080, app)server.serve_forever()

请求: http://localhost:8080/home

/home路径

请求: http://localhost:8080

网站根目录

part 2

先前博主的那个装饰器实现的路由控制只能在Python2.7上运行,到了3就不好使了。然后本人又修改了一下,实现可以在Python3上运行。

# coding: utf8import sysfrom wsgiref.simple_server import make_serverclass Router(object):    def __init__(self):        self.routes = {}    def route(self, path):        def decorator(func):            self.routes[path] = func            print(self.routes)            return func        return decorator    def __call__(self, env, start_response):        path = env['PATH_INFO']        if path in self.routes:            status = '200 OK'            headers = [('Content-Type', 'text/html;charset=UTF-8')]            start_response(status, headers)            # 然后可以通过route绑定的函数来处理相关的星球,然后返回给客户端            # return ['您请求的路径为:{}'.format(path).encode('utf8')]            return self.routes[path]()        else:            status = '404 Not Found'            headers = [('Content-Type', 'text/html;charset=UTF-8')]            start_response(status, headers)            return [b'Bad Request']app = Router()@app.route('/')def index():    print('首页内容')    yield 'root path'.encode('utf8')@app.route('/home')def home():    print('home页面内容')    yield 'home页面内容'.encode('utf8')server = make_server('', 8080, app)server.serve_forever()
  • 访问根目录: http://localhost:8080
    访问根目录

  • 访问home目录: http://localhost:8080/home
    访问home目录

  • 访问没有路由跟踪的目录: http://localhost:8080/balabala

访问没有路由跟踪的路径

易错点

总的来说,实现一个带有路由跟踪的web服务还是挺方便的。但是到目前为止,这点知识还远远不够。headers的控制可谓是耗时耗力的一个操作。

  • 路由更新:通过装饰器可以方便的进行添加
  • handler函数(被装饰器修饰的处理函数)的返回值应该是可迭代的。与Python2不同(返回一个列表即可),Python3中最好是使用yield来实现。
  • __call__方法每次对象被调用都会触发一次,牢记这点。

下一步,尝试着写出一个自己的web框架,当然是在开发环境下了。


参考链接:

  • wsgiref: http://blog.csdn.net/on_1y/article/details/18818081
  • WSGI简介:http://blog.csdn.net/on_1y/article/details/18803563
  • 装饰器实现:http://blog.csdn.net/yz764127031/article/details/72723118

然后是针对WSGI标准实现的不同的web application.

原创粉丝点击