接上篇:python3 web框架(一、web框架---本质)
我们在浏览网站不同页面的时候后面url也会变,不是我们这样不管谁来访问都是“ hello web”
那我们想要实现这样的功能呢?看代码:
app.py
from wsgiref.simple_server import make_server
def handle_request(env, res):#这里env等价于文章'https://blog.csdn.net/Rayn_Zhu/article/details/83413239'中server端的client_msg表示客户端发送过来的消息
res("200 OK",[("Content-Type","text/html")])
acqu_url = env['PATH_INFO']#这样就获取到了用户输入的url
body = "<h1>127.0.0.1:8000%s</h1>"%str(acqu_url)
return [body.encode('utf-8')]
if __name__ == "__main__":
httpd = make_server("127.0.0.1",8000,handle_request)
print("Serving http on port 8000")
httpd.serve_forever()
这里我们获取到用户输入的url就可以针对不同的url返回不同的内容了,可以把上面的body注释掉,写成这样
from wsgiref.simple_server import make_server
def handle_index():
return ["<h1>hello web</h1>".encode('utf-8')]
def handle_hello():
return ["<h1>here is hello</h1>".encode('utf-8')]
def handle_data():
return ["<h1>here is data</h1>".encode('utf-8')]
def handle_request(env, res):#这里env等价于文章'https://blog.csdn.net/Rayn_Zhu/article/details/83413239'中server端的client_msg表示客户端发送过来的消息
res("200 OK",[("Content-Type","text/html")])
acqu_url = env['PATH_INFO']#这样就获取到了用户输入的url
#body = "<h1>127.0.0.1:8000%s</h1>"%str(acqu_url)
if acqu_url == '/':
return handle_index()
elif acqu_url =='/hello':
return handle_hello()
elif acqu_url =='/data':
return handle_data()
else:
return ["<h1>404</h1>".encode('utf-8')]
# return [body.encode('utf-8')]
if __name__ == "__main__":
httpd = make_server("127.0.0.1",8000,handle_request)
print("Serving http on port 8000")
httpd.serve_forever()
那这里判断部分也是可以优化的,可以写成字典。这样:
app.py
from wsgiref.simple_server import make_server
def handle_index():
return ["<h1>hello web</h1>".encode('utf-8')]
def handle_hello():
return ["<h1>here is hello</h1>".encode('utf-8')]
def handle_data():
return ["<h1>here is data</h1>".encode('utf-8')]
#对应关系
URL_DICT = {
'/':handle_index,
'/hello':handle_hello,
'/data':handle_data,
}
def handle_request(env, res):
res("200 OK",[("Content-Type","text/html")])
acqu_url = env['PATH_INFO']#
#body = "<h1>127.0.0.1:8000%s</h1>"%str(acqu_url)
func = None
if acqu_url in URL_DICT:
func = URL_DICT[acqu_url]
if func:
return func()
else:
return ["<h1>404</h1>".encode('utf-8')]
# return [body.encode('utf-8')]
if __name__ == "__main__":
httpd = make_server("127.0.0.1",8000,handle_request)
print("Serving http on port 8000")
httpd.serve_forever()
这样就写完了一个简单的web框架。