我的第一个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()
相关推荐
卷无止境1 小时前
Python能做嵌入式开发吗?一份写给动手派的生态与硬件全景图
后端·python
月光船幽幽5 小时前
检测用户意图复杂性的关键方法
人工智能·python
威联通网络存储8 小时前
TS-h3087XU-RP 汽车零部件质检追溯部署
python·汽车
你驴我8 小时前
WhatsApp 多账号场景下的会话归档与历史消息检索优化实践
后端·python
IT毕设实战小研8 小时前
基于安卓的空气质量查询系统
android·大数据·vue.js·爬虫·python·django·课程设计
harmful_sheep9 小时前
java group by常见用法
java·开发语言·python
whcyhhh9 小时前
头歌实践教学平台:数据科学与大数据技术导论(十六)
大数据·开发语言·python
宸津-代码粉碎机9 小时前
AI工程化高阶实战|从Demo到生产落地核心架构、全套源码与避坑指南
java·大数据·开发语言·人工智能·python·架构
郝学胜-神的一滴10 小时前
Effective Python 条款4:字符串格式化大乱斗
开发语言·网络·python·程序人生·软件工程
ynchyong11 小时前
Python 字符组合生成器:product 与 permutations 的实战对比
python·工具·字符串生产