当前位置: 首页 > 工具软件 > MiniWeb > 使用案例 >

用python实现一个miniweb框架

羊舌勇
2023-12-01

miniFrame.py

from pymysql import connect


url2path_list = {}

#路由装饰器
def router(data):
    def func_out(func):
        url2path_list[data] = func
        def func_in():
            return func
        return func_in
    return func_out


@router("/index.py")
def index():
    with open("./templates/index.html") as f:
        content = f.read()
    con = connect(host = "localhost",port = 3306,user = "root",password = "mysql",database = "gupiao",charset="utf8")
    cr = con.cursor()
    cr.execute("select * from info")
    rs  = cr.fetchall()
    data = ""
    for r in rs:
        data += """
            <tr>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
            </tr>
        
        """%r
    cr.close()
    con.close()
    return content%data


@router("/center.py")
def center():
    with open("./templates/center.html") as f:
        content = f.read()
    con = connect(host = "localhost",port = 3306,user = "root",password = "mysql",database = "gupiao",charset = "utf8")
    cr = con.cursor()
    cr.execute("select code,short,chg,turnover,price,highs,focus.note_info from info inner join focus where info.id=focus.id")
    rs = cr.fetchall()
    data = ""
    for r in rs:
        data += """
            <tr>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
            </tr>

        """%r
    cr.close()
    con.close()
    return content%data



def application(file_name):
    try:
        func = url2path_list[file_name]
        return func()
    except Exception:
        return "Not Found"

miniweb.py

import socket
import re
import gevent
import miniFrame
from gevent import monkey
monkey.patch_all()


class HttpServer(object):
    def __init__(self):
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_socket.bind(('', 80))
        server_socket.listen(128)
        self.server_socket = server_socket

    def client_handler(self, client_socket):
        client_data = client_socket.recv(1024)
        print(client_data.decode())
        request_path = re.match("GET\s(?P<path>\S+)", client_data.decode())
        if request_path:
            path = request_path.group('path')
            print("客户端请求的路径:" + path)
            if path.endswith(".py"):
                response_line = "HTTP/1.1 200 OK\r\n"
                response_header = "Server: MiniWeb 1.0\r\ncharset=utf8\r\n"
                response_content = miniFrame.application(path)    
                response_data = (response_line + response_header +
                                 "\r\n" + response_content).encode()
                client_socket.send(response_data)
                client_socket.close()
            else:
                try:
                    response_line = "HTTP/1.1 200 OK\r\n"
                    response_header = "Server: MiniWeb 1.0\r\ncharset=utf8\r\n"
                    if path == "/":
                        path = "/index.html"
                    with open("./static" + path, "rb") as f:
                        response_content = f.read()
                    response_data = (response_line + response_header +
                                     "\r\n").encode() + response_content
                except Exception as e:
                    response_line = "HTTP/1.1 404\r\n"
                    response_header = "Server: MiniWeb 1.0\r\ncharset=utf8\r\n"
                    response_content = "你访问的资源不存在"
                    response_data = (response_line + response_header +
                                     "\r\n" + response_content).encode()
                finally:
                    client_socket.send(response_data)
                    client_socket.close()
        else:
            response_line = "HTTP/1.1 403 \r\n"
            response_header = "Server: MiniWeb 1.0\r\ncharset=utf8\r\n"
            response_content = "<h1>路径错误</h1>\r\n"
            response_data = (response_line + response_header +
                             "\r\n" + response_content).encode()
            print("客户端请求的路径错误")
            client_socket.send(response_data)
            client_socket.close()

    def start(self):
        while 1:
            client_socket, client_adder = self.server_socket.accept()
            print("接收到一个来自%s的请求" % str(client_adder))
            gevent.spawn(self.client_handler, client_socket)


def main():
    http_server = HttpServer()
    http_server.start()


if __name__ == "__main__":
    main()

 

 

 

 

 

 类似资料: