前文:【python socket編程】—— 2.解析http請求頭html
web
的框架和解析請求的Request
類咱們都寫好了,如今惟一要作的就是處理相應。編寫一個route_dict
字典,key
是url
路徑,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/html
是header
中的key: value
形式的內容,這裏只有一行,常見的還有Set-Cookie
、Content-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 Page
。segmentfault
回覆響應的原理就是這樣,後續每增長一個路徑,就在字典中增長一條item
及增長一個對應的響應函數。當用戶請求的路徑不在route_dict
中時,就返回error_handle
這個函數,咱們只要讓它返回相似404 NOT FOUND
之類的內容就能夠了。瀏覽器