用python实现一个miniweb框架

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()

 

 

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值