python 练习 simple_server 判断路径及返回函数

函数 routers 返回一个 urlpatterns 元组,里面包含了路径名和函数名;在 函数 application 中遍历 urlpatterns 元组,路径存在则返回函数名,不存在则返回 404

from wsgiref.simple_server import make_server

def routers():
urlpatterns = (
('/book', f1),
('/web', f2),
)
return urlpatterns def f1(x):
return [b'<h1>Hello, book</h1>'] def f2(x):
return [b'<h1>Hello, web</h1>'] def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')]) urlpatterns = routers()
path = environ["PATH_INFO"]
func = None
for item in urlpatterns:
if item[0] == path:
func = item[1]
break
if func:
return func(environ)
else:
return ["<h1>404</h1>".encode("utf8")] httpd = make_server('', 8888, application) print('Serving HTTP on port 8888...')
httpd.serve_forever()
上一篇:玩转Windows服务系列——Windows服务小技巧


下一篇:自定义容器启动脚本报错:exec user process caused "no such file or directory"