函数 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()