04 返回静态文件的函数web框架
服务器server端python程序(函数版):
1 import socket 2 server = socket.socket() 3 server.bind(("127.0.0.1", 8888)) 4 server.listen() 5 def func_html(conn): 6 with open("index.html", "rb")as f: 7 conn.send(f.read()) 8 def func_js(conn): 9 with open("index.js", "rb")as f: 10 conn.send(f.read()) 11 def func_css(conn): 12 with open("index.css", "rb")as f: 13 conn.send(f.read()) 14 def func_img(conn): 15 with open("index.png", "rb")as f: 16 conn.send(f.read()) 17 def func_ico(conn): 18 with open("favicon.ico","rb")as f: 19 conn.send(f.read()) 20 def respones_back(conn,path): 21 conn.send("HTTP/1.1 200 ok ".encode("utf-8")) 22 if path == "/": 23 func_html(conn) 24 elif path == "/index.js": 25 func_js(conn) 26 elif path == "/index.css": 27 func_css(conn) 28 elif path == "/index.png": 29 func_img(conn) 30 elif path == "/favicon.ico": 31 func_ico(conn) 32 conn.close() 33 34 35 if __name__ == '__main__': 36 while 1: 37 conn, client_addr = server.accept() 38 http_request=conn.recv(1024).decode("utf-8") 39 path=http_request.split(" ")[0].split(" ")[1] 40 print("path>>>",path) 41 respones_back(conn,path)
客户端浏览器访问:
在浏览器地址栏直接输入地址端口:127.0.0.1:8888
index.html:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <link rel="stylesheet" href="index.css"> 6 <link rel="icon" href="favicon.ico"> 7 <title>函数版</title> 8 </head> 9 <body> 10 <div id="d1"> 11 <h1>函数版的页面:本html页面引用了外部本地css样式和js代码(本地图片)</h1> 12 </div> 13 <img src="index.png" alt="本地图片" title="本地图片"> 14 </body> 15 <script src="index.js"></script> 16 </html>