使用http服务器加载页面的python框架实现股票信息页面的展示

展示的结果如下图:

要使用到数据来加载数据;

 源代码如下:

服务器代码

import re
import socket
import gevent
from gevent import monkey

from application_stock import application

monkey.patch_all()


class MySever(object):
    """服务器类"""

    def __init__(self):
        """服务器初始化"""
        self.sever = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sever.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sever.bind(("", 8082))
        self.sever.listen(128)

    def run_sever(self):
        """启动服务器,与客户端连接"""
        while True:
            client, addr = self.sever.accept()
            # 创建协程
            gevent.spawn(self.client_handle, client)

    def client_handle(self, client):
        """处理客户端请求"""
        # 接收客户端请求
        recv_data = client.recv(1024).decode("utf-8")

        # 如果数据为空,需返回
        if not recv_data:
            client.close()
            return

        # 解析请求,获取请求中的地址
        data = re.match("[^/]+(/[^ ]*)", recv_data)
        if data:
            url_addr = data.group(1)
            if url_addr == "/":
                url_addr = "/index.html"
        else:
            head = "HTTP/1.1 404 NOT FOUND\r\n"
            body = "can not found your request."
            content = head + "\r\n" + body
            client.send(content.encode("utf-8"))
        print(url_addr)

        # 根据不同的请求,给出不同的响应内容

        if url_addr.endswith(".html"):
            body = application(url_addr)

        else:
            try:
                with open("./static%s" % url_addr, "rb") as f:
                    body = f.read()
                    print("----------------------")
            except Exception:
                body = "this content can not be found ".encode("utf-8")
                print(url_addr)
                print("***************")

        # 作出响应
        head = "HTTP/1.1 200 OK\r\n" + "charset=utf-8\r\n"
        content = head + "\r\n"
        client.send(content.encode("utf-8"))
        client.send(body)

        # 关闭套接字
        print("关闭")
        client.close()


def main():
    """http服务器"""
    # 服务器初始化
    tcp_sever = MySever()

    # 运行服务器
    tcp_sever.run_sever()


if __name__ == '__main__':
    main()

页面加载代码:

import re

from pymysql import connect


def application(url_addr):
    try:
        content = url_addr_dict[url_addr]
        body = content()
    except Exception:

        try:
            with open("./templates%s" % url_addr, "r") as f:
                body = f.read()
        except Exception:
            body = "the page you write does not exist"

    body = body.encode("utf-8")

    return body


url_addr_dict = {}


# 闭包装饰器
def route(key):
    def set_fun(func):
        def call_fun(*args, **kwargs):
            return func(*args, **kwargs)

        url_addr_dict[key] = call_fun
        return call_fun

    return set_fun


############################# 上面部分是框架 ################

# 用上面的框架完成股票信息页面展示
@route('/index.html')
def index():
    # 拿到前端页面
    with open("./templates/index.html") as f:
        content = f.read()

    # 拿到数据库数据
    # 连接
    conn = connect(host="127.0.0.1", port=3306, user="root", password="hcs0127", database="stock_db", charset="utf8")
    # 获取游标
    cs = conn.cursor()

    # 执行sql语句
    cs.execute("""select * from info;""")

    # 得到数据
    data = cs.fetchall()

    # 关闭
    cs.close()
    conn.close()

    # print(data)

    # 将数据库内容拼接到前端页面
    row_str = """<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>"""
    show_str = ""
    for temp in data:
        show_str += row_str % (temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7])

    body = re.sub(r'\{%content%\}', show_str, content)
    return body


@route('/center.html')
def center():
    # 前端页面
    with open('./templates/center.html') as f:
        content = f.read()

    # 获取数据库的数据
    # 连接
    conn = connect(host="127.0.0.1", port=3306, user="root", password="hcs0127", database="stock_db", charset="utf8")
    # 获取游标
    cs = conn.cursor()

    # 执行sql语句
    cs.execute(
        """select info.id,info.code,info.short,info.chg,info.turnover,info.price,info.highs,focus.note_info from info inner join focus on info.id = focus.info_id;""")

    # 得到数据
    data = cs.fetchall()

    # 关闭
    cs.close()
    conn.close()

    # 拼接
    row_str = """<tr>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
            <td>
                <a type="button" class="btn btn-default btn-xs" href="/update/300268.html"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> 修改 </a>
            </td>
            <td>
                <input type="button" value="删除" id="toDel" name="toDel" systemidvaule="300268">
            </td>
        </tr>"""

    show_str = ''
    for temp in data:
        show_str += row_str % (temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6],)
    body = re.sub(r'\{%content%\}', show_str, content)
    print('============================')

    return body

猜你喜欢

转载自blog.csdn.net/weixin_42489971/article/details/81415855