main函数
import socket
def f1(request):
"""
处理用户请求,并返回相应的内容
:param request:用户请求的所有信息
:return:
"""
f = open('bilibili.html', 'rb')
data = f.read()
f.close()
return data
def f2(request):
f = open('article.tpl', 'r', encoding='utf-8')
data = f.read()
f.close()
import time
ctime = time.time()
data = data.replace('@@sw@@', str(ctime))
return bytes(data, encoding='utf-8')
def f3(_):
import pymysql
conn = pymysql.connect(host="127.0.0.1", port=3305, user='root', passwd='020804', db='s8day127db')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select user_id,user_email,email_code from mail")
user_list = cursor.fetchall()
cursor.close()
conn.close()
content_list = []
for row in user_list:
tp = "<tr><td>%s</td><td>%s</td><td>%s</td></tr>" % (row['user_id'], row['user_email'], row['email_code'])
content_list.append(tp)
content = "".join(content_list)
f = open('userlist.html', 'r', encoding='utf-8')
template = f.read()
f.close()
data = template.replace("@@content@@", content)
return bytes(data, encoding='utf-8')
def f4(request):
import pymysql
conn = pymysql.connect(host="127.0.0.1", port=3305, user='root', passwd='020804', db='s8day127db')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select user_id,user_email,email_code from mail")
user_list = cursor.fetchall()
cursor.close()
conn.close()
f = open('hostlist.html', 'r', encoding='utf-8')
data = f.read()
f.close()
from jinja2 import Template
template = Template(data)
data = template.render(user_list = user_list)
return data.encode('utf-8')
routers = [
('/xxx', f1),
('/ooo', f2),
('/userlist.htm', f3),
('/host', f4),
]
def run():
sock = socket.socket()
sock.bind(('127.0.0.1', 8080))
sock.listen(5)
while True:
conn, addr = sock.accept()
data = conn.recv(8096)
data = str(data, encoding='utf-8')
headers, bodys = data.split("\r\n\r\n")
temp_list = headers.split("\r\n")
method, url, protocal = temp_list[0].split(' ')
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")
func_name = None
for item in routers:
if item[0] == url:
func_name = item[1]
break
if func_name:
response = func_name(data)
else:
response = b'404'
conn.send(response)
conn.close()
if __name__ == '__main__':
run()
hostlist.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>艹</title>
</head>
<body>
<table border='1'>
<thead>
<tr>
<th>user_id</th>
<th>user_email</th>
<th>email_code</th>
</tr>
</thead>
<tbody>
{% for row in user_list %}
<tr>
<td>{{row.user_id}}</td>
<td>{{row.user_email}}</td>
<td>{{row.email_code}}</td>
</tr>
{%endfor%}
</tbody>
</table>
</body>
</html>
userlist.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>艹</title>
</head>
<body>
<table border='1'>
<thead>
<tr>
<th>user_id</th>
<th>user_email</th>
<th>email_code</th>
</tr>
</thead>
<tbody>
@@content@@
</tbody>
</table>
</body>
</html>