python之mini web框架搭建

web.py

# 对象多任务形式自定义web服务器
#     1.动态与静态
import logging
import socket
import sys
import framework

# 设置日志等级和输出日志格式
# logging日志的配置
import threading

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                    filename="log.txt",
                    filemode="a")


class Web:
    def __init__(self, port):
        # 初始化socket
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 设置socket端口不会咬住不放
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        # 设置端口号
        server_socket.bind(('', port))
        # 设置监听个数 最好128
        server_socket.listen(128)
        # 绑定该socket类属性,方便其他方法使用
        self.server_socket = server_socket

    # 启动多任务线程
    def start(self):
        while True:
            # 等待客户端连接 返回 该客户端socket port
            client_socket, client_port = self.server_socket.accept()
            # 一旦接收到请求就创建子线程 目标函数静态方法并将socket传进去方便使用
            # 并且使用守护主线程,防止主线程无法退出的情况
            sub_thread = threading.Thread(target=self.handle_client_quest, args=(client_socket,), daemon=True)
            sub_thread.start()

    @staticmethod
    def handle_client_quest(client_socket):
        # 子线程运行后接收客户端发送的请求数据
        # 并从中获取请求path 若path是.html结尾判定动态请求
        # 不是则视为静态
        recv_client_data = client_socket.recv(4096)
        # 若该请求数据长度未0 视为浏览器请求完毕 断开http请求连接
        if len(recv_client_data) == 0:
            print('浏览器断开连接')
            return
            # b'GET / HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests:
        # 二进制文件转换  并分隔获取 /
        print(recv_client_data)
        request_path = recv_client_data.decode('utf-8').split(' ', 2)[1]
        print(request_path)  # /index.html
        if request_path == '/':
            request_path = '/index.html'
        if request_path.endswith('.html'):
            """这里是动态资源请求,把请求信息交给框架处理 动态的就是通过web渲染数据"""
            logging.info("动态资源请求:" + request_path)
            # web服务器把请求数据传给web框架处理,响应信息以及该动态响应体,完事后并将该信息传递回来
            env={'request_path': request_path}
            status,headers,response_body=framework.handle_request(env)
            # 响应行
            response_line = "HTTP/1.1 %s\r\n" % status
            #响应头
            response_header = "" #Server: PWS1.0\r\n
            for k,v in headers:
                response_header+="%s: %s\r\n" % (k,v)
            response_data=response_line+response_header+'\r\n'+response_body
            client_socket.send(response_data.encode('utf-8'))
            client_socket.close()
        else:
            """这里是静态资源请求 静态的其实就是js css image等文件"""
            logging.info("静态资源请求:" + request_path)
            try:
                with open('../static' + request_path, 'rb') as file:
                    file_data = file.read()
            except Exception as e:
                # 读取try文件报错 视为找不到 发送error页面 和404响应报文
                with open('../static/error.html', 'rb') as file:
                    file_data = file.read()
                # 响应行
                response_line = "HTTP/1.1 404 Not Found\r\n"
                # 响应头
                response_header = "Server: PWS1.0\r\n"
                # 响应体
                response_body = file_data
                response_data = (response_line + response_header + '\r\n').encode('utf-8') + response_body
                client_socket.send(response_data)
            else:
                # 没有报错 发送200响应报文以及对应的页面信息
                # 响应行
                response_line = "HTTP/1.1 200 OK\r\n"
                # 响应头
                response_header = "Server: PWS1.0\r\n"

                # 响应体
                response_body = file_data
                response_data = (response_line + response_header + '\r\n').encode('utf-8') + response_body
                client_socket.send(response_data)
            finally:
                client_socket.close()

def main():
    # # 通过终端形式启动
    # if len(sys.argv) != 2:
    #     logging.warning('用户在命令行启动程序参数个数不正确!')
    #     return
    # if not sys.argv[1].isdigit():
    #     logging.warning('用户在命令行启动程序参数个数不正确! 不是数字字符串')
    #     return
    # port = sys.argv[1]
    # 启动web服务器
    web = Web(8000)
    web.start()


if __name__ == '__main__':
    main()

framework.py

import json

import pymysql

route_list = []


def route(path):
    def decorate(func):
        route_list.append((path, func))

        def inner():
            return func()

        return inner

    return decorate


@route('/index.html')
def index():
    status = '200 ok'
    response_header = [('Server', 'PW2.0')]
    with open('template/index.html', encoding='utf-8') as file:
        response_data = file.read()
    # 读取数据库中的数据
    conn = pymysql.connect(host="localhost",
                           port=3306,
                           user="root",
                           password="123456",
                           database="stock_db",
                           charset="utf8")
    cursor = conn.cursor()
    sql = 'select * from info;'
    cursor.execute(sql)
    # 读取的数据格式元组 表中的每一行又是元组((xxx),(xxx))
    info_result = cursor.fetchall()
    # 遍历数据
    data = ''
    for row in info_result:
        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>
                       <td><input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="000007"></td>
                      </tr>
                   ''' % row
    cursor.close()
    conn.close()

    # 读取HTML文件并渲染数据到该页面的{%content%}中
    result = response_data.replace('{%content%}', data)
    return status, response_header, result


@route('/center.html')
def center():
    status = '200 ok'
    response_header = [('Server', 'PW2.0')]
    with open('template/center.html', mode='r', encoding='utf-8') as file:
        response_data = file.read()
    conn = pymysql.connect(host="localhost",
                           port=3306,
                           user="root",
                           password="123456",
                           database="stock_db",
                           charset="utf8")
    cursor = conn.cursor()
    sql = '''select i.code, i.short, i.chg, 
             i.turnover, i.price, i.highs, f.note_info 
             from info as i inner join focus as f on i.id = f.info_id;'''
    cursor.execute(sql)
    # 读取的数据格式元组 表中的每一行又是元组((xxx),(xxx))
    info_result = cursor.fetchall()
    print('data:', len(info_result))
    data = ''
    for row in info_result:
        print(row)
        data += '''
               <tr>
                           <td>%s</td>
                           <td>%s</td>
                           <td>%s</td>
                           <td>%s</td>
                           <td>%d</td>
                           <td>%d</td>
                           <td>%s</td>
                           <td><input type="button" value="修改" id="toAdd" name="toAdd" systemidvaule="000007"></td>
                           <td><input type="button" value="删除" id="toAdd" name="toAdd" systemidvaule="000007"></td>
                          </tr>
                       ''' % row
    cursor.close()
    conn.close()
    result = response_data.replace('{%content%}', data)
    return status, response_header, result


@route('/center_data.html')
def center_data():
    status = '200 ok'
    #('Content-Type', 'text/html;charset=utf-8') 返回json字符串数据需要告知浏览器解析编码格式 不然中文会乱码
    response_header = [('Server', 'PW2.0'), ('Content-Type', 'text/html;charset=utf-8')]
    conn = pymysql.connect(host="localhost",
                           port=3306,
                           user="root",
                           password="123456",
                           database="stock_db",
                           charset="utf8")
    cursor = conn.cursor()
    sql = '''select i.code, i.short, i.chg, 
                i.turnover, i.price, i.highs, f.note_info 
                from info as i inner join focus as f on i.id = f.info_id;'''
    cursor.execute(sql)
    # 读取的数据格式元组 表中的每一行又是元组((xxx),(xxx))
    info_result = cursor.fetchall()
    # 将数据改为json[{}]格式并且转换成字符串
    json_arr = [{"code": row[0],
                 "short": row[1],
                 "chg": row[2],
                 "turnover": row[3],
                 "price": str(row[4]), #Decimal('31.77')
                 "highs": str(row[5]),#Decimal('31.77') 此时转换成str类型
                 "note_info": row[6]} for row in info_result]
    json_str = json.dumps(json_arr, ensure_ascii=False)#转换字符串类型的json数据 ensure_ascii=False确保终端显示中文,
    print(json_str)
    cursor.close()
    conn.close()
    return status, response_header, json_str


def not_found():
    status = '404 Not Found'
    response_header = [('Server', 'PW2.0')]
    data = 'not found'
    return status, response_header, data


# 处理响应报文
def handle_request(env):
    request_path = env['request_path']
    print('接收到的请求路径是:', request_path)

    # 依据不同的动态请求路径设置不同的响应
    # if request_path=='/index.html':
    #     return index()
    # else:
    #     return not_found()

    # 以上方式不好 定义一个路由映射列表 路径映射对应的处理函数
    # route_list=[('/index.html',index)]

    # 以上方式每次增加路由都要去手动添加,麻烦
    # 使用装饰器装饰一个路由 装饰器一旦运行就添加该path和函数
    # 因为需要传递不同的path 使用外层包裹函数方式定义装饰器

    # 定义该结构的原因 遍历该列表后得到元组 使用拆包方式得到path和函数
    for path, func in route_list:
        # 如path和请求的一致返回该函数
        if path == request_path:
            return func()
    else:
        return not_found()

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值