Nemo

关注TA

路漫漫其修远兮,吾将上下而求索。

  • 深圳市
  • 菜鸟工程师

最近留言

用Python写一个简易的静态文件 web容器

2019年07月08 19:12 53 1 复制链接




import socket
import re
from multiprocessing import Process

HOME_DIR = '.\html'


class MyWeb(object):
"""创建web类"""

def __init__(self):
"""创建server对象"""
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 重复使用绑定的信息
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

def bind(self, port):
"""邦定端口号"""
self.server.bind(('127.0.0.1', port))

def start(self):
"""开始监听客户端的链接"""
self.server.listen(10)
while True:
conn, address = self.server.accept()
print("客户端[%s]连接进来了" % str(address))
p = Process(target=self.receive_request, args=(conn,))
p.start()
# (1)创建子进程的时候,子进程已经从父进程中复制过了conn,所以可以关闭父进程中的conn了
conn.close()

def receive_request(self, conn):
"""接收客户端的链接"""
request_info = conn.recv(1024).decode()
# print(request_info)
self.handle_request(request_info, conn)

def handle_request(self, request, conn):
"""处理客户端的请求信息"""
relative_path = request.splitlines()[0].split()[1]
print(request)
# (2)
path = re.sub('/', r'\\', relative_path)
self.response_info(conn, path)

def response_info(self, conn, relative_path):
"""将页面返回给浏览器"""
filename = HOME_DIR + relative_path
if '\\' == relative_path:
filename = HOME_DIR + '\index.html'
print(filename)

try:
f = open(filename, 'rb') # (3)有可能是图片,图片为二进制数据
response_body = f.read()
f.close()
except IOError as e:
response_start = b'HTTP/1.1 400 Not Found\r\n'
response_head = b'server: localhost\r\n'
response_body = b'No found the file'
else:
response_start = b'HTTP/1.1 200 OK\r\n'
response_head = b'server: localhost\r\n'
response_info = response_start + response_head + b'\r\n' + response_body
conn.send(response_info)
conn.close()


if __name__ == '__main__':
my_web = MyWeb()
my_web.bind(8888)
my_web.start()



点赞(0)
本文标签python web容器
点了个评