---恢复内容开始---
#主入口,Python解释器从这开始执行;
if __name__ == '__main__': run()
内部执行过程:
#引用socket模块 import socket def f1(request): """ 处理用户请求,并返回相应的内容 :param request: 用户请求的所有信息 :return: """ f = open('index.fsw','rb') data = f.read() f.close() return data def f2(request): f = open('aricle.tpl','rb') data = f.read() f.close() return data #将url与处理函数映射成对 routers = [ ('/xxx', f1), ('/ooo', f2), ] def run(): #创建socket sock = socket.socket() #绑定端口和IP sock.bind(('127.0.0.1',8080)) #监听端口 sock.listen(5) while True: conn,addr = sock.accept() # hang住 # 有人来连接了 # 获取用户发送的数据 data = conn.recv(8096) #将数据转成字符串处理 data = str(data,encoding='utf-8') #拆分数据头和数据内容 headers,bodys = data.split(' ') temp_list = headers.split(' ') #数据头包含方法、url、协议 method,url,protocal = temp_list[0].split(' ') #返回状态码 conn.send(b"HTTP/1.1 200 OK ") func_name = None #根据接收的url,查询对应的函数名称 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()
在浏览器中输入:http://127.0.0.1:8080/xxx
得到如下数据:
GET /xxx HTTP/1.1
Host: 127.0.0.1:8080
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3642.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
显示的界面如下所示:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>用户登录</h1> <form> <p><input type="text" placeholder="用户名" /></p> <p><input type="password" placeholder="密码" /></p> </form> </body> </html> index.fsw的内容