我的第一个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()
相关推荐
技术无疆5 分钟前
【Python】Anaconda插件:Sublime Text中的Python开发利器
ide·python·编辑器·pip·pygame·sublime text·python3.11
加油=^_^=13 分钟前
MySQL基础篇的补充
数据库·python·mysql
鸽芷咕35 分钟前
【Python报错已解决】ModuleNotFoundError: No module named ‘tensorflow‘
python·机器学习·tensorflow·bug·neo4j
李元豪38 分钟前
python 自动化 win11 编程 实现 一键 启动多个软件,QQ浏览器,snipaste,pycharm软件
python·pycharm·自动化
痛&快乐着38 分钟前
python-在PyCharm中使用PyQt5
python·qt·pycharm
fydw_7151 小时前
PyTorch 激活函数及非线性变换详解
人工智能·pytorch·python
Rverdoser1 小时前
在 PyCharm 中配置 Anaconda 环境
ide·python·pycharm
IT小辉同学1 小时前
用 Pygame 实现一个乒乓球游戏
python·游戏·pygame
虚假程序设计2 小时前
pythonnet python图像 C# .NET图像 互转
开发语言·人工智能·python·opencv·c#·.net
测试老哥2 小时前
功能测试干了三年,快要废了。。。
自动化测试·软件测试·python·功能测试·面试·职场和发展·压力测试