【python socket編程】—— 3.響應

前文:【python socket編程】—— 2.解析http請求頭html


web的框架和解析請求的Request類咱們都寫好了,如今惟一要作的就是處理相應。編寫一個route_dict字典,keyurl路徑,value是對應這個url的相應函數,並使用response_for_request做爲惟一的接口接受請求,並從route_dict獲取對應的函數,以下:python

route_dict = {
    '/': route_index,
}


def response_for_request(request):
    path = request.parse_path()[0]
    return route_dict.get(path, error_handle)(request)

當請求'/'時,response_for_request根據request解析到'/'這個path,而後從route_dict獲得route_index這個函數,最後返回route_index(request)的結果。route_index須要按照http響應的格式返回字節數據,例如:web

HTTP/1.1 200 OK 
Content-Type: text/html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>INDEX</title>
</head>
<body>
<h1>Index Page</h1>
</body>
</html>

與請求的格式相似,第一行HTTP/1.1 200 OK分別表示協議、狀態碼和狀態,Content-Type: text/htmlheader中的key: value形式的內容,這裏只有一行,常見的還有Set-CookieContent-Length等;而後是空行;最後就是html頁面的內容。假設以上內容都以str的形式放在response變量中,那麼route_index能夠寫成:編程

def route_index(request):
    print('Request: ', request.content)
    response = '...' # 上文的內容,省略 
    print('Response: ', response)
    return response.encode(encoding='utf-8')

此時運行runserver,在瀏覽器輸入url,就能夠看到內容Index Pagesegmentfault


回覆響應的原理就是這樣,後續每增長一個路徑,就在字典中增長一條item及增長一個對應的響應函數。當用戶請求的路徑不在route_dict中時,就返回error_handle這個函數,咱們只要讓它返回相似404 NOT FOUND之類的內容就能夠了。瀏覽器


下一篇文章:【python socket編程】—— 4.實現redirect函數框架

相關文章
相關標籤/搜索