zoukankan      html  css  js  c++  java
  • 简单搭建WEB框架及原理

    一、web框架搭建分一下几步

    1、首先搭建一个服务器接收客户端发来的请求数据包

    2、对客户端发来的数据包进行分析与拆分得到想要的数据

    header = data.split(' ')[0].split(' ')[0]
    url = header.split(' ')[1]

    3、创建一个路由关系映射,将不同的请求映射到不同的方法种

    4、在方法使用mysql中连接数据库,并将得到的数据进行循环拼接成html中的表格的形式

    5、将拼接后的数据和html文件中的@@content@@进行替换

    6、换回替换后的数据给客户端

    二、代码

    .py的代码

    import socket


    def f1():
    fp = open('index.html', 'rb')
    data = fp.read()
    fp.close()

    return data

    def f2():
    import pymysql
    conn = pymysql.connect(host='127.0.0.1',user='root',password='456',db='db1',charset='utf8')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

    sql = 'select sid,sname,gender,class_id from student'
    cursor.execute(sql)
    res = cursor.fetchall()
    print(res)
    res_list = []
    for user in res:
    res_str = '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (user['sid'],user['sname'],user['gender'],user['class_id'])
    res_list.append(res_str)
    s = ' '.join(res_list)
    fp = open('index.html', 'r',encoding='utf-8')
    data = fp.read()
    data = data.replace('@@content@@',s)
    fp.close()

    return bytes(data,encoding='utf-8')



    router = [
    ('/index', f1),
    ('/xxx', f2),
    ]

    def run():
    server = socket.socket()
    server.bind(('127.0.0.1',9999))
    server.listen(5)

    while True:
    cli,add = server.accept()
    buf = cli.recv(1024)
    if not buf:
    print('断开连接')
    cli.close()
    data = str(buf,encoding='utf-8')
    header = data.split(' ')[0].split(' ')[0]
    url = header.split(' ')[1]

    func_name = None
    for i in router:
    if i[0] == url:
    func_name = i[1]
    break
    if func_name:
    res = func_name()
    else:
    res = b'404'

    cli.send(bytes('HTTP/1.1 200 OK ',encoding='utf-8'))
    cli.send(res)
    cli.close()


    if __name__ == '__main__':
    run()

    .html的代码
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>登录</title>
    </head>
    <body>
    <table border="1px">
    <thead>
    <tr>
    <th>SID</th>
    <th>Name</th>
    <th>Gender</th>
    <th>Class_id</th>
    </tr>
    </thead>
    <tbody>
    @@content@@
    </tbody>
    </table>
    </body>
    </html>
  • 相关阅读:
    Linux系统下安装jdk1.8并配置java环境
    linux常用命令
    intelliJ IDEA 中快速定位当前文件路径
    Intellij IDEA 入门之java “Hello word”
    常用SQL语句
    PictureBox的内存问题
    MDI窗体设计
    实现多态的方法三——接口
    css清除浮动方法
    三栏式布局(下)
  • 原文地址:https://www.cnblogs.com/huanghongzheng/p/11158699.html
Copyright © 2011-2022 走看看