webserver.py 内容
# coding:utf-8
# 2019/4/3 10:14
import socket
from settings import url_list
from views import ret_404
ip = '10.0.102.245'
port = 9600
s = socket.socket(
socket.AF_INET, # IPV4
socket.SOCK_STREAM
)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind((ip, port))
s.listen(50)
use_agent_list = ["Mozilla",""]
while True:
con, addr = s.accept()
print("--->", addr)
content = con.recv(8192)
content_str = str(content, encoding='utf-8')
try:
request_heat, request_body = content_str.split('\r\n\r\n')
heat_list = request_heat.split('\r\n')
# print(request_heat)
tag = False
for item in heat_list:
if 'User-Agent' in item:
agent = item.split()[1]
if agent.startswith("Mozilla"):
tag = True
req_month, url, host_server = heat_list[0].split()
# print(req_month, url)
if req_month == "GET":
if not tag:
int("p")
con.send(b"HTTP/1.1 500\r\n\r\n''")
con.close()
continue
for web_url, func in url_list:
if url == web_url:
ret = func()
heat = "HTTP/1.1 200 OK\r\n\r\n"
body = ret
ret_content = heat + body
con.send(bytes(ret_content, encoding='utf-8'))
break
# if url == '/':
#
# # 得到首页的内容
# ret = open_index()
# heat = "HTTP/1.1 200 OK\r\n\r\n"
# body = ret
# ret_content = heat + body
# con.send(bytes(ret_content, encoding='utf-8'))
else:
head = "HTTP/1.1 404 error\r\n\r\n"
con.send(bytes(head + ret_404(),encoding='utf-8'))
except Exception as e:
pass
con.close()
s.close()
"""
'GET / HTTP/1.1
Host: 10.0.102.245:9000
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\r\nAccept-Encoding: gzip, deflate\r\nAccept-Language: zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7
'
"""
settings.py 内容
# coding:utf-8
# 2019/4/3 12:04
import views
# 路由系统
url_list = [
('/', views.open_index),
('/student', views.get_student),
]
views.py 内容
# coding:utf-8
# 2019/4/3 12:04
from jinja2 import Template
import pymysql
from models import mymysql_con
# 视图系统
def open_index():
with open('./index.html', 'r', encoding='utf-8') as f:
index = f.read()
return index
def get_student():
with open("./student.html", 'r', encoding='utf-8') as f:
tpl = f.read()
temp_obj = Template(tpl)
conn = mymysql_con()
# 获取到的结果集是字典
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select id,name from student;")
user_list = cursor.fetchall()
# print(user_list)
content = temp_obj.render(user_list=user_list)
return content
def ret_404():
with open("./404.html", 'r', encoding='utf-8') as f:
return f.read()
if __name__ == "__main__":
info = get_student()
print(info)
详细资料 撩我这个钢铁直男 y86000153