装饰器实现路由控制
2017-05-30 19:51
489 查看
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 app from wsgiref.simple_server import make_server server = make_server('', 8080, app) server.serve_forever()
请求: http://localhost:8080/home
请求: http://localhost:8080
part 2
先前博主的那个装饰器实现的路由控制只能在Python2.7上运行,到了3就不好使了。然后本人又修改了一下,实现可以在Python3上运行。# coding: utf8 import sys from wsgiref.simple_server import make_server class 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
访问没有路由跟踪的目录: http://localhost:8080/balabala
易错点
总的来说,实现一个带有路由跟踪的web服务还是挺方便的。但是到目前为止,这点知识还远远不够。headers的控制可谓是耗时耗力的一个操作。路由更新:通过装饰器可以方便的进行添加
handler函数(被装饰器修饰的处理函数)的返回值应该是可迭代的。与Python2不同(返回一个列表即可),Python3中最好是使用yield来实现。
[b]__call__[/b]方法每次对象被调用都会触发一次,牢记这点。
下一步,尝试着写出一个自己的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.
相关文章推荐
- 图层控制界面实现记录-单图层控制实现和事件路由问题解决
- MVC 自定义过滤器(Filter)实现路由控制、异常处理、授权处理(获取客户端信息)
- golang自定义路由控制实现(一)
- gnugk代码解读之二:H.245控制信令路由的实现
- Linux路由应用-使用策略路由实现访问控制
- Linux路由应用-使用策略路由实现访问控制
- react router4+redux实现路由权限控制的方法
- 路由控制的实现
- vue利用路由控制实现登录功能
- 使用Filter-policy Route-policy ACL 实现对RIP路由发布的控制
- 装饰器实现Python web框架路由功能
- angular基于路由控制ui-router实现系统权限控制
- 如何用 Vue 实现前端权限控制(路由权限 + 视图权限 + 请求权限)
- golang自定义路由控制实现(二)-流式注册接口以及支持RESTFUL
- Linux路由应用-使用策略路由实现访问控制
- 在GridView里实现用CheckBox来控制TextBox控件的编辑功能
- Asp.net中如何实现后台控制前台的跳转
- 数据库的连接以及实现控制台对对数据的增删查改
- ASP.NET实现匿名访问控制