web框架

手写简单的web框架

WebServer

import socket

import pymysql
def index(request): 
    '''
    处理用户请求,并回相应的内容
       request: 用户请求的所有信息
    '''
    return '<img src="https://baidubaike.com/base/dede/swsww237b.jpg"></img>'

def login(request):
    with open('login.html','r',encoding='utf-8') as f:
        data = f.read()
    return data

def time(request):
    import datetime
    now = datetime.datetime.now().strftime('%Y-%m-%d %X')
    with open('time.html','r',encoding='utf-8') as f:
        data = f.read()
    data = data.repalce('@@time@@',now)
    return data 

def user_list(request):
    #连接数据库拿数据  拿到一个数据连接
    conn = pymysql.connect(host='127.0.0.1',port='3306',user='root',database='test',password='')
    #拿到一个游标对象
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    #执行sql
    cursor.execute('select id,name,password from user')
    #把数据拿出来
    user_list = cursor.fetchall()
    print(user_list)
    cursor.close()
    conn.close()
    tr_list = []
    for row in user_list: #每个row数据库里一行数据
        tr = '<tr><td>%s</td><td>%s</td><td>%s</td></tr>'%(row['id'],row['name'],row['password'])
        tr_list.append(tr)
    with open('user_list.html','r',encoding='utf-8') as f:
        data = f.read()
    data = data.replace('@@body@@',''.join(tr_list))
    return data

#使用jinja2
def user_list_new(request):
    #创建连接
    conn = pymysql.connect(host='127.0.0.1',port='3306',user='root',database='test',password='')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute('select * from user')
    user_list = fetchall()
    cursor.close()
    conn.close()
    with open('user_list_new.html','r',encoding='utf-8') as f:
        data = f.read()
    from jinja2 import Template #基于第三方工具实现模板渲染 #模板渲染(模板+数据)
    template = Template(data)
    response = template.render(user_list=user_list) # 数据替换模板指定位置
    return response

urls = [
    ('/index',index),
    ('/login',login),
    ('/time',time),
    ('/user_list',user_list),
    ('/user_list_new',user_list_new),
]

def run ():
    sk = socket.socket()
    sk = socket.bind(('127.0.0.1',8080))
    sk = sockrt.listen(5)
    while True:
        conn,port = sk.accept()
        data = conn.recv(1024)
        print(data)
        data = str(data,encoding='utf-8')
        request_list = data.split('\r\n\r\n')
        head_list = request_list[0].split('\r\n')
        method, url, htt = head_list[0].split(' ')
        conn.send(b'HTTP/1.1 200 OK \r\n\r\n')
        print(url)
        func_name = None
        for u in urls:
            if url == u[0]:
                func_name = u[1]
                break
        if func_name:
            response = func_name(data)
        else:
            response = '404 not found'
           
        conn.send(response.encode("utf-8"))
        conn.close()
        
if __name__ == '__main__':
    run()

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="">
    <p>用户名:<input type="text"></p>
    <p>密码:<input type="password"></p>
</form>
</body>
</html>

time.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
@@time@@
</body>
</html>
user_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>

<table border="1">
    <thead>
        <tr>
            <th>id</th>
            <th>用户名</th>
            <th>密码</th>
        </tr>
    </thead>
    <tbody>
        @@body@@
    </tbody>


</table>

</body>
</html>

user_list_new.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>
<table border="1">
    <thead>
    <tr>
        <th>id</th>
        <th>name</th>
        <th>password</th>
    </tr>
    </thead>
    <tbody>

    {% for user in user_list%}
    <tr>
        <td>{{user.id}}</td>
        <td>{{user.name}}</td>
        <td>{{user.password}}</td>
    </tr>
    {%endfor%}


    </tbody>


</table>

</body>
</html>
posted @ 2018-09-05 18:46  Shinonon  阅读(159)  评论(0编辑  收藏  举报