1. 程式人生 > >python3 web框架之Django(二、關於web框架理解)

python3 web框架之Django(二、關於web框架理解)

我們在瀏覽網站不同頁面的時候後面url也會變,不是我們這樣不管誰來訪問都是“ hello web”

那我們想要實現這樣的功能呢?看程式碼:

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

那這裡判斷部分也是可以優化的,可以寫成字典。這樣:

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框架。