0001:Web与Web框架

1、Web本质

众所周知,对于所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端。

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 import socket
 5 
 6 
 7 def hander_request(client):
 8     buf = client.recv(4096)
 9     client.send("HTTP/1.1 200 OK \r\n\r\n".encode("utf-8"))
10     client.send("Hello world!".encode("utf-8"))
11 
12 
13 def main():
14     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
15     sock.bind(("localhost", 8888))
16     sock.listen(5)
17 
18     while True:
19         conn, addr = sock.accept()
20         hander_request(conn)
21         conn.close()
22 
23 
24 if __name__ == "__main__":
25     main()

      上述通过socket来实现了其本质,而对于真实开发中的python web程序来说,一般会分为两部分:服务器程序和应用程序。服务器程序负责对socket服务器进行封装,并在请求到来时,对请求的各种数据进行整理。应用程序则负责具体的逻辑处理。为了方便应用程序的开发,就出现了众多的Web框架,例如:Django、Flask、web.py 等。不同的框架有不同的开发方式,但是无论如何,开发出的应用程序都要和服务器程序配合,才能为用户提供服务。这样,服务器程序就需要为不同的框架提供不同的支持。这样混乱的局面无论对于服务器还是框架,都是不好的。对服务器来说,需要支持各种不同框架,对框架来说,只有支持它的服务器才能被开发出的应用使用。这时候,标准化就变得尤为重要。我们可以设立一个标准,只要服务器程序支持这个标准,框架也支持这个标准,那么他们就可以配合使用。一旦标准确定,双方各自实现。这样,服务器可以支持更多支持标准的框架,框架也可以使用更多支持标准的服务器。

有没有这样的规范呢?答案是肯定的

WSGI(Web Server Gateway Interface)是一种规范,它定义了使用python编写的web app与web server之间接口格式,实现web app与web server间的解耦。

python标准库提供的独立WSGI服务器称为wsgiref。

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 from wsgiref.simple_server import make_server
 5 
 6 
 7 def RunServer(environ,start_response):
 8     # environ 客户端发来的所有数据
 9     # start_response 封装要返回给用户的响应头数据等
10     start_response("200 OK", [('Content-Type', 'text/html')])
11     # 返回的内容
12     # return [bytes('<h1>Hello world!!!</h1>', encoding='utf-8'), ]
13     return [('<h1>Hello world!</h1>'.encode('utf-8')), ]
14 
15 
16 if __name__ == "__main__":
17     httpd = make_server("", 8888, RunServer)
18     print("Httpd is running on port 8888...")
19     httpd.serve_forever()

2、自定义Web框架

通过python标准库提供的wsgiref模块开发一个自己的Web框架,请看下面的简单实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>current_time:@time@</h1>
</body>
</html>

  

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 from wsgiref.simple_server import make_server
 5 import time
 6 
 7 
 8 # def index():
 9 #     return [('<h1>Index</h1>').encode('utf-8'),]
10 def index():
11     f = open('index.html', mode='rb')
12     content = f.read()
13     cur_time = str(time.time())
14     content = content.replace(b'@time@', cur_time.encode('utf-8'))
15     return [content, ]
16 
17 
18 def data():
19     return [('<h1>Data</h1>').encode('utf-8'), ]
20 
21 
22 uri_dict = {
23     "/index": index,
24     "/data": data,
25 }
26 
27 
28 def RunServer(environ, start_response):
29     start_response("200 OK", [('Content-Type', 'text/html')])
30     cur_uri = environ["PATH_INFO"]
31     func = None
32 
33     if cur_uri in uri_dict:
34         func = uri_dict[cur_uri]
35 
36     if func:
37         return func()
38     else:
39         return [('<h1>404!</h1>'.encode('utf-8')), ]
40 
41 
42 if __name__ == "__main__":
43     httpd = make_server("", 8888, RunServer)
44     print("Httpd is running on port 8888...")
45     httpd.serve_forever()

3、WEB框架

上述代码如果将html文件放到view目录中,相关数据库放到model中(这里仅仅使用了个替换函数代表一下——真实环境中是去数据库中取并替换),url判断等业务判断放到control中,就形成了传说中高大山的MVC模型(其实也就那样,是吧)

还有另外一种说法:MTV,其实都一样,下面我把他们都列出来:

MVC
Model  View  Control
数据库 模板文件 业务处理
MTV
Model  Template  View
数据库 模板文件 业务处理

 

猜你喜欢

转载自www.cnblogs.com/zheng-weimin/p/9297564.html