python 使用多进程完成mini_web_框架

这里写自定义目录标题

新建一个迷你web框架
"""
    迷你web框架
        解耦,
"""

import time


def login():
    return "登录,现在的时间是{}".format(time.ctime())


def register():
    return "注册:{}".format(time.ctime())


def profile():
    return "主页面---{}".format(time.ctime())


def application(file_name):
    if file_name == '/login.py':
        return login()
    elif file_name == '/register.py':
        return register()
    elif file_name == '/profile.py':
        return profile()
    else:
        return "NOT FOUND YOU PAGE!"

新建一个主服务器:

"""
    多进程版tcp服务器,动态实现
"""


from socket import *
from multiprocessing import *
import time
import re
from python_mini_web框架 import mini_web_frame


class WSGIServer():
    def __init__(self):
        self.tcp_socket = socket(AF_INET, SOCK_STREAM)
        self.tcp_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.tcp_socket.bind(("", 8082))
        self.tcp_socket.listen(128)  # 使套接字处于监听状态

    def service_client(self, new_socket):`在这里插入代码片`
        req = new_socket.recv(1024).decode('utf8')
        print(req)
        # 'GET / HTTP/1.1'
        client_req = req.splitlines()[0]  # 处理http的请求
        client_req = re.match(r"[^/]+([^ ]*)", client_req).group(1)  # 匹配第一个分组
        print(client_req)  # 测试  re成功

        # 如果请求的资源不是以.py结尾,那么就认为是静态资源。(js/html/css/png/jpg)
        if not client_req.endswith(".py"):
            if client_req == '/':
                client_req = 'index.html'
            elif len(client_req) > 1:
                client_req = client_req[1:]  # 去掉/,直接在当前路径下找文件

            try:
                html = open(client_req, 'rb')  # 用字节流打开文件
            except:
                send_body = b'NOT FOUND!'  # 以字节流的形式发送信息
            else:
                send_body = html.read()  # 读文件

            send_head_part = 'HTTP / 1.1 200 OK\r\n'.encode('gbk')  # 遵从http1.1协议
            send_head = send_head_part + "Content-Length={}\r\n\r\n".format(len(send_body)).encode('gbk')
            new_socket.send(send_head)  # 使用长连接,避免重复使用套接字
            new_socket.send(send_body)
        else:
            # 如果是以.py结尾,那么就认为是动态资源的请求
            header = "HTTP / 1.1 200 OK\r\n"
            header += "\r\n"

            # if client_req == 'login.py':
            #     body = mini_web_frame.login()

            body = mini_web_frame.application(client_req)  # 解耦
            response = header+body

            # 发送response给浏览器
            new_socket.send(response.encode('gbk'))
        # new_socket.close()  # 关闭新的套接字

    def run_server(self):
        while True:
            print("等待客户连接...")
            new_socket, client_addr = self.tcp_socket.accept()  # 等待用户连接
            print("【{}】:【{}】:【{}】连接成功".format(time.ctime(), client_addr[0], client_addr[1]))
            p = Process(target=self.service_client, args=(new_socket,))
            p.start()  # 开启多进程
            new_socket.close()  # 关闭旧的套接字
        self.tcp_socket.close()


def main():
    client = WSGIServer()
    client.run_server()


if __name__ == '__main__':
    main()

你可能感兴趣的:(python,socket,迷你服务器)