我的第一个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()
相关推荐
狐狐生风7 分钟前
LangChain RAG 基础
人工智能·python·学习·langchain·rag·agentai
老前端的功夫40 分钟前
【Java从入门到入土】28:Stream API:告别for循环的新时代
java·开发语言·python
yaoxin5211231 小时前
397. Java 文件操作基础 - 创建常规文件与临时文件
java·开发语言·python
dFObBIMmai1 小时前
MySQL主从同步中大事务导致的延迟_如何拆分大事务优化同步
jvm·数据库·python
szccyw01 小时前
mysql如何限制特定存储过程执行权限_MySQL存储过程安全访问
jvm·数据库·python
小白学大数据1 小时前
Python 自动化爬取网易云音乐歌手歌词实战教程
爬虫·python·okhttp·自动化
风之所往_3 小时前
Python 3.0 新特性全面总结
python
2401_882273723 小时前
如何在 CSS 中正确加载本地 JPG 背景图片
jvm·数据库·python
Lucas_coding3 小时前
【Claude Code Router】 Claude Code 兼容 OpenAI 格式 API, Claude code 接入本地部署模型
人工智能·python
测试员周周3 小时前
【AI测试系统】第5篇:从 Archon 看 AI 工程化落地:为什么"确定性编排+AI 弹性智能"是终局?
人工智能·python·测试