欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mini_frame获取页面模板数据

程序员文章站 2022-06-27 11:52:22
...

mini_frame获取页面模板数据

# coding:utf-8
import socket
import re
import multiprocessing
import dynamic.mini_frame

class WSGIServer(object):

    def __init__(self):
        # 1.创建套接字
        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # 2.绑定地址
        self.tcp_server_socket.bind(('', 7890))

        # 3.变为监听套接字
        self.tcp_server_socket.listen(128)

    def service_client(self, new_socket):
        # 1.接收浏览器发送过来的请求,即http请求
        # GET / HTTP/1.1
        requset = new_socket.recv(1024).decode('utf-8')
        requset_lines = requset.splitlines()
        print(requset_lines)

        file_name = ''
        ret = re.match(r'[^/]+(/[^ ]*)', requset_lines[0])

        if ret:
            file_name = ret.group(1)
            if file_name == "/":
                file_name = '/index.html'


        # 2.返回http格式的数据给浏览器
        # 2.1 如果请求的资源部署以.py结尾,那么就认为是静态资源(http/css/js/png/jpg等)
        if not file_name.endswith('.py'):
            try:
                f = open('./static' + file_name, 'rb')
            except:
                response = 'HTTP/1.1 404 NOT FOUND\r\n'
                response += '\r\n'
                response += '---------file not found---------'
                new_socket.send(response.encode('utf-8'))
            else:
                html_content = f.read()
                response = 'HTTP/1.1 200 OK\r\n'
                response += '\r\n'
                # header发送给服务器
                new_socket.send(response.encode('utf-8'))
                # body发送给服务器
                new_socket.send(html_content)
        else:
            # 2.2 如果是以.py结尾,那么就认为是动态资源的请求

            env = dict()
            env['PATH_INFO'] = file_name
            body = dynamic.mini_frame.application(env, self.set_response_header)
            header = 'HTTP/1.1 %s\r\n' % self.status

            for temp in self.headers:
                header += '%s:%s\r\n' % (temp[0], temp[1])

            header += '\r\n'

            response = header + body

            # 发送response给浏览器
            new_socket.send(response.encode('utf-8'))
        # 关闭套接字
        new_socket.close()

    def set_response_header(self, status, headers):
        self.status = status
        self.headers = headers

    def run_forever(self):

        while True:
            # 等待客户端连接
            new_socket, client_addr = self.tcp_server_socket.accept()

            p = multiprocessing.Process(target=self.service_client, args=(new_socket,))
            p.start()

            new_socket.close()

        self.tcp_server_socket.close()


def main():
    '''控制整体,创建一个web服务器对象,然后调用这个对象的run_forever方法运行'''
    wsgi_server = WSGIServer()
    wsgi_server.run_forever()


if __name__ == '__main__':
        main()

 

# coding:utf-8

def index():

    with open('./templates/index.html', 'r', encoding='UTF-8') as f:
        return  f.read()


def center():
    with open('./templates/center.html', 'r', encoding='UTF-8') as f:
        return f.read()


def application(env, start_response):
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8'),('server', 'mini_frame v1.0')])

    file_name = env['PATH_INFO']

    if file_name == '/index.py':
        return index()
    elif file_name == '/center.py':
        return center()
    else:
        return 'Hello World!(๑′ᴗ‵๑)I Lᵒᵛᵉᵧₒᵤ❤中国'

 

相关标签: Pyhon高级