socket服务端功能划分:
a.负责与浏览器收发消息(socket通信) --> wsgiref / uWsgi / gunicorn…
b.根据用户访问不同的路径执行不同的函数
c.从HTML读取出内容, 并且完成字符串的替换 --> jinja2(模板语言)
Django实现了b、c两部分,a借助了第三方库实现。以下为Django框架的大致流程。
import socket
server = socket.socket() #创建套接字,实现socket服务端功能
server.bind(("127.0.0.1", 8888))
server.listen()
def xm(url):
# result = "hello {}".format(url)
with open('xiaoming.html', 'r', encoding='utf8') as f:
result = f.read()
result = result.replace('xxoo', '文明你我他') #实现了字符串替换
return bytes(result, encoding='utf8')
def wrong_page(url):
with open('wrongpage.html', 'r', encoding='utf8') as f:
result = f.read()
# result.replace('xxoo', '文明你我他')
return bytes(result, encoding='utf8')
def xh(url):
with open('小红.html', 'r', encoding='utf8') as f:
result = f.read()
result = result.replace('xxoo', '文明你我他')
return bytes(result, encoding='utf8')
url_view = [('/xiaoming', xm), ('/xiaohong', xh)] #路由与函数的映射
while True:
con, ip = server.accept()
data = con.recv(8096)
# print(data)
request_header = str(data, encoding='utf-8').split('\r\n')
request_url = request_header[0].split()[1]
# print(request_url)
con.send(b"http/1.1 200 ok\r\ncontent-type: text/html; charset=utf-8\r\n\r\n")
# if request_url == '/xiaoming':
# response = "<h1>hello {}!</h1>".format('xiaoming')
# con.send(bytes(response, encoding='utf8'))
# else:
# con.send(b'<h1>404</h1>')
for current_url, f in url_view:
if current_url == request_url:
func = f
break
else:
func = wrong_page
con.send(func(current_url))
con.close()