# -*- coding: utf-8 -*-import http.serverimport socketserverfrom datetime import datetimePORT = 8000import sys# ...class MyHandler(http.server.SimpleHTTPRequestHandler):def do_GET(self):if self.path == '/':# 如果路径是根路径,返回页面内容self.send_response(200)self.send_header('Content-type', 'text/html')self.end_headers()try:now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")response_content = "我的第一个Python网页
当前时间:{}".format(now)self.wfile.write(response_content.encode())self.send_header('Content-type', 'text/html; charset=utf-8')# 添加打印语句print(f"GET request received. Path: {self.path}, Time: {now}")sys.stdout.flush()# 刷新输出缓冲区except Exception as e:# 捕获并打印异常print(f"Error processing GET request: {e}")sys.stdout.flush()# 刷新输出缓冲区else:# 否则按照默认的 SimpleHTTPRequestHandler 处理super().do_GET()with socketserver.TCPServer(("0.0.0.0", PORT), MyHandler) as httpd:print("Serving at port", PORT)sys.stdout.flush()# 刷新输出缓冲区httpd.serve_forever()