python3 web框架(二、关于web框架理解)

接上篇: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框架。

下篇:python3 web框架(三、MVC与MTV)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值