【python socket编程】—— 3.响应
前文:【python socket编程】—— 2.解析http请求头
web的框架和解析请求的Request类我们都写好了,现在唯一要做的就是处理相应。编写一个route_dict字典,key是url路径,value是对应这个url的相应函数,并使用response_for_request作为唯一的接口接受请求,并从route_dict获取对应的函数,如下:
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响应的格式返回字节数据,例如:
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。
回复响应的原理就是这样,后续每增加一个路径,就在字典中增加一条item及增加一个对应的响应函数。当用户请求的路径不在route_dict中时,就返回error_handle这个函数,我们只要让它返回类似404 NOT FOUND之类的内容就可以了。
下一篇文章:【python socket编程】—— 4.实现redirect函数