08 返回动态页面web框架

匿名 (未验证) 提交于 2019-12-02 23:48:02

08 web

 1 import socket  2   3 import time  4   5 server=socket.socket()  6   7 server.bind(("127.0.0.1",8888))  8   9 server.listen() 10  11 # 返回页面显示每次访问时间,这是一个动态的,主要在返回内容是替换某些特定内容 12  13 def func_html(conn): 14  15     with open("index.html","rb")as f: 16  17         data=f.read().decode("utf-8") 18  19     # 将网页中的#time#时间占位字符串进行替换后再返回(每次请求响应返回的结果都不一样) 20  21     t=time.strftime("%Y-%m-%d %X") 22  23     data=data.replace("#time#",str(t)) 24  25     conn.send(data.encode("utf-8")) 26  27   28  29 def func_ico(conn): 30  31     with open("favicon.ico","rb")as f: 32  33         conn.send(f.read()) 34  35   36  37 def response_back(conn,path,func_mappers): 38  39     conn.send(b"HTTP/1.1 200 ok \r\n\r\n") 40  41     for mapper in func_mappers: 42  43         if path==mapper[0]: 44  45             mapper[1](conn) 46  47     conn.close() 48  49   50  51 func_mappers=[ 52  53     ("/",func_html), 54  55     ("/favicon.ico",func_ico) 56  57 ] 58  59    60  61 if __name__ == '__main__': 62  63     while 1: 64  65         conn,client_addr=server.accept() 66  67         http_request=conn.recv(1024).decode("utf-8") 68  69         path=http_request.split("\r\n")[0].split(" ")[1] 70  71         print("parh>>>",path) 72  73         74  75         response_back(conn,path,func_mappers)
服务器server端python程序(动态页面版本)

127.0.0.18888

index.html


 1 <!DOCTYPE html>  2   3 <html lang="en">  4   5 <head>  6   7     <meta charset="UTF-8">  8   9     <link rel="icon" href="favicon.ico"> 10  11     <style> 12  13         span{ 14  15             background-color: yellow; 16  17             color: red; 18  19             font-size: 20px 20  21         } 22  23     </style> 24  25     <title>动态页面</title> 26  27 </head> 28  29 <body> 30  31     <div> 32  33         <h1>本次访问时间为: 34  35             <span>#time#</span> 36  37         </h1> 38  39     </div> 40  41 </body> 42  43 </html>
index.html

    

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!