代码部分如下:
# coding=utf-8
from http.server import BaseHTTPRequestHandler, HTTPServer
PORT_NUMBER = 8080
# This class will handles any incoming request from
# the browser
class myHandler(BaseHTTPRequestHandler):
# Handler for the GET requests
def do_GET(self):
if self.path == "/":
self.path = "./html/from.html"
if self.path == "/index.html":
self.path = "./html/to.html"
try:
# Check the file extension required and
# set the right mime type
sendReply = False
if self.path.endswith(".html"):
mimetype = 'text/html' # mimetype用来指示文件类型的字符串
sendReply = True
if self.path.endswith(".jpg"):
mimetype = 'image/jpg'
sendReply = True
if self.path.endswith(".gif"):
mimetype = 'image/gif'
sendReply = True
if self.path.endswith(".js"):
mimetype = 'application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype = 'text/css'
sendReply = True
if sendReply:
# Open the static file requested and send it
f = open(self.path)
self.send_response(200)
self.send_header('Content-type', mimetype)
self.end_headers()
self.wfile.write(f.read().encode('utf-8'))
f.close()
return
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
try:
# Create a web server and define the handler to manage the
# incoming request
server = HTTPServer(('127.0.0.1', PORT_NUMBER), myHandler)
print('Started httpserver on port ', PORT_NUMBER)
# Wait forever for incoming http requests
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down the web server')
server.socket.close()
代码分析:
本次实验通过Python程序实现web服务器的功能,其中代码的前半段是对于程序文件目录中的HTML文件进行相对路径到绝对路径的调整和修正,确保程序可以正确的找到我们指定的和HTML文件以及图片等网页资源。
代码的后半段,则是整个程序实现web功能的主要部分,主要为以下几个函数,共同实现get请求的处理。
self.send_response(200)
self.send_header('Content-type', mimetype)
self.end_headers()
self.wfile.write(f.read().encode('utf-8'))
代码实现效果:运行Python程序后进入localhost8080出现一下界面:
点击next_page之后,出现另一个界面:
实验心得与体会
通过这次实验,我对html协议有了更深刻的了解。知道了怎么用Python搭建一个web服务器。并进行简单的网页跳转和8080页面编写。对于HTTP 协议下客户/服务器模式中信息交换的实现原理、流程(建立连接、发送请求、发送响应、关闭连接),相比于理论知识,在动手实践后能更好地掌握和理解。