day85-Django初识-自己开发的web框架

#以下是自己开发的web框架:
# 1.
#   Http,无状态,短连接
# 2.
#   浏览器(socket客户端)
#   网站(socket服务端)
# 3.
#   自己写网站
#       a.socket服务端
#       b.路由系统:
#               根据URL不同返回不同的内容
#               URL -> 函数
#       c.字符串返回给用户
#               模板引擎渲染(替换):
#               HTML充当模板(特殊字符)
#               自己创造任意数据
# 4.
# Web框架种类:
#        - a, b, c --> Tornado
#        - [第三方a -->wsgiref], b, c --> Django
#        - [第三方a -->wsgiref], b, [第三方c -->jinja2] --> flask,

import socket
import pymysql
def f1(request):
    with open('form.html','r',encoding='utf-8') as f:#rb操作时不支持指定encoding参数
        content = f.read()
    return content

def f2(request):
    with open('table.html','r',encoding='utf-8') as f:
        content = f.read()
    import random
    age = random.randint(1,100)
    content = content.replace('@@age@@',str(age))
    return content

def f3(request):
    #1.获取数据库的数据
    conn = pymysql.connect(host='localhost',port=3306,user='root',password='123',database='db1',charset='utf8')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#获取的结果是字典
    cursor.execute('select id,username,password from userinfo')
    user_list = cursor.fetchall()#获取全部数据,列表里面的元素是字典
    print(user_list)#[{'id': 1, 'username': 'tom', 'password': '111'}, {'id': 2, 'username': 'marry', 'password': '222'}, {'id': 3, 'username': 'jack', 'password': '333'}, {'id': 10, 'username': 'alex', 'password': '555'}, {'id': 11, 'username': 'tommy', 'password': '777'}]
    cursor.close()
    conn.close()

    #2.将数据放在row里面,得到row_list,它是一个列表,里面的元素都是字符串
    row_list = []
    for dict in user_list:
        row = '<tr><td>%s</td><td>%s</td><td>%s</td></tr>'%(dict['id'],dict['username'],dict['password'])
        row_list.append(row)
    print(row_list)

    #3.列表跟空字符拼接,得到一个字符串row_str
    row_str = ''.join(row_list)
    print(row_str)

    #4.打开table1.html,读取内容,把tbody的@@row@@替换成row_str,最后返回给浏览器。
    with open('table1.html','r',encoding='utf-8') as f:
        content = f.read()
    content = content.replace('@@row@@',row_str)
    print(content)
    return content

def f4(request):
    conn = pymysql.connect(host='localhost',port=3306,user='root',password='123',database='db1',charset='utf8')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#获取的结果是字典
    cursor.execute('select id,username,password from userinfo')
    user_list = cursor.fetchall()
    cursor.close()
    conn.close()

    with open('table2.html','r',encoding='utf-8') as f:
        content = f.read()

    #基于第三方工具实现的模板渲染(替换)
    from jinja2 import Template
    template = Template(content)#把读取的html内容传参,得到实例化对象
    content = template.render(user_list=user_list)
    return content

url_list = [('/form.html',f1),('/table.html',f2),('/table1.html',f3),('/table2.html',f4)]#可请求的url
def run():
    sk = socket.socket()
    sk.bind(('127.0.0.1',8999))
    sk.listen(10)

    while True:
        conn,addr = sk.accept()
        data = conn.recv(1024).decode('utf-8')#接收请求。如果不解码,得到的data有很多换行符\r\n,可清晰的看到结构
        # print(data)
        header,body = data.split('\r\n\r\n')#请求头和响应体是用两个换行符隔开
        header_item = header.split('\r\n')#请求头里面的内容是用一个换行符隔开,得到一个列表
        # print(header_item)
        get,url,http = header_item[0].split(' ')#请求头的第一个元素是用一个空格隔开

        conn.send(b'HTTP/1.1 200 ok\r\n\r\n')#http协议
        #路由系统:url跟函数有关系,根据url不同,返回不同的内容
        for item in url_list:
            if item[0] == url:#如果url是对的
                ret = item[1](data)#就把请求传参给函数,拿到返回值
                conn.send(ret.encode('utf-8'))
                break
        else:
            conn.send(b'404 not found')

        conn.close()
if __name__ == '__main__':
    run()

猜你喜欢

转载自www.cnblogs.com/python-daxiong/p/12597540.html
今日推荐