python的web框架(1)
1.首先写一个最简单的web服务器,只能给客户回应一个固定的hello world的页面。
from socket import *
from multiprocessing import Process
def deal(conn):
recv_data = conn.recv(1024).decode('gb2312')
print(recv_data)
conn.send('HTTP/1.1 200 OK
<h1>hello world</h1>'.encode('gb2312'))
def main():
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(('',8000))
s.listen(1023)
while 1:
conn, user_info = s.accept()
print(user_info)
p = Process(target=deal, args=(conn,))
p.start()
conn.close()
if __name__ == '__main__':
main()
2.根据用户请求的页面,打开页面文件,读取,并回复给用户,完成多进程web静态页面服务器
#!/usr/bin/env python3
# coding:utf-8
from socket import *
from multiprocessing import Process
def deal(conn):
recv_data = conn.recv(1024).decode('gb2312')
recv_data_head = recv_data.splitlines()[0]
print('------', recv_data_head)
request_method, request_path, http_version = recv_data_head.split()
# 去掉url中的?和之后的参数
request_path = request_path.split('?')[0]
if request_path == '/':
request_path = '/index.html'
file_name = "." + request_path
try:
f = open(file_name, 'rb')
except IOError:
conn.send(b'HTTP/1.1 404 ERROR
<h1>Page is not exsit .</h1>')
return
read_data = f.read()
send_data = b'HTTP/1.1 200 OK
' + read_data
conn.send(send_data)
f.close()
def main():
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(('',8000))
s.listen(1023)
while 1:
conn, user_info = s.accept()
print(user_info)
p = Process(target=deal, args=(conn,))
p.start()
conn.close() # 进程会复制出一个新的conn,所以这里的conn需要关闭
if __name__ == '__main__':
main()
3.为了方便操作,可以将之前的函数式编程改成面向对象编程。将所有的方法集成到一个类中,这样更加方便,也更易于使用者了解和使用。
#!/usr/bin/env python3
# coding:utf-8
from socket import *
from multiprocessing import Process
class MyWebServer(object):
@staticmethod
def deal(conn):
recv_data = conn.recv(1024).decode('gb2312')
recv_data_head = recv_data.splitlines()[0]
print('------', recv_data_head)
request_method, request_path, http_version = recv_data_head.split()
# 去掉url中的?和之后的参数
request_path = request_path.split('?')[0]
if request_path == '/':
request_path = '/index.html'
file_name = "." + request_path
try:
f = open(file_name, 'rb')
except IOError:
conn.send(b'HTTP/1.1 404 ERROR
<h1>Page is not exsit .</h1>')
return
read_data = f.read()
send_data = b'HTTP/1.1 200 OK
' + read_data
conn.send(send_data)
f.close()
def __init__(self):
self.s = socket(AF_INET, SOCK_STREAM)
self.s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.s.bind(('',8000))
self.s.listen(1023)
def start(self):
while 1:
conn, user_info = self.s.accept()
print(user_info)
p = Process(target=self.deal, args=(conn,))
p.start()
conn.close() # 进程会复制出一个新的conn,所以这里的conn需要关闭
s = MyWebServer()
s.start()