我的第一个python web 网站

复制代码
# -*- coding: utf-8 -*-

import http.server
import socketserver
from datetime import datetime

PORT = 8000

import 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网页<br>当前时间:{}".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()
相关推荐
自由随风飘2 小时前
python 题目练习1~5
开发语言·python
fl1768314 小时前
基于python的天气预报系统设计和可视化数据分析源码+报告
开发语言·python·数据分析
闲人编程5 小时前
Python与区块链:如何用Web3.py与以太坊交互
python·安全·区块链·web3.py·以太坊·codecapsule
Want5955 小时前
Python汤姆猫
开发语言·python
花姐夫Jun5 小时前
基于Vue+Python+Orange Pi Zero3的完整视频监控方案
vue.js·python·音视频
像风一样自由20207 小时前
Rust与Python完全指南:从零开始理解两门语言的区别与关系
开发语言·python·rust
房开民7 小时前
RKNN-Toolkit2入门
python
岁岁岁平安8 小时前
本机 MongoDB 注册系统服务、启用security认证
数据库·python·mongodb
程序员大雄学编程8 小时前
用Python来学微积分30-微分方程初步
开发语言·python·线性代数·数学·微积分