Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python webserver

作者:月冷清   发布日期:2026-02-05   浏览:96

# 这是一个简单的 Python Web 服务器示例,使用内置的 `http.server` 模块。

# 导入必要的模块
import http.server
import socketserver

# 定义端口号
PORT = 8000

# 创建一个简单的请求处理类,继承自 `http.server.SimpleHTTPRequestHandler`
class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # 当接收到 GET 请求时,返回一个简单的 HTML 页面
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        html = f"<html><head></head><body><h1>Hello, World! This is a simple web server using Python.</h1></body></html>"
        self.wfile.write(bytes(html, "utf8"))

# 设置端口和处理器
with socketserver.TCPServer(("", PORT), MyHttpRequestHandler) as httpd:
    print(f"Serving on port {PORT}")
    # 启动服务器,持续监听请求
    httpd.serve_forever()

# 解释说明:
# 1. 我们导入了 `http.server` 和 `socketserver` 模块,用于创建一个简单的 HTTP 服务器。
# 2. 定义了一个端口号 `PORT`,这里设置为 8000。
# 3. 创建了一个自定义的请求处理类 `MyHttpRequestHandler`,它继承自 `SimpleHTTPRequestHandler`,并重写了 `do_GET` 方法来处理 GET 请求。
# 4. 在 `do_GET` 方法中,我们发送了一个简单的 HTML 页面作为响应。
# 5. 使用 `socketserver.TCPServer` 绑定端口和请求处理类,并启动服务器,使其持续监听请求。

上一篇:python爬取网页数据代码

下一篇:python filenotfounderror

大家都在看

python excel 库

python时间格式

pythoneval函数用法

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

python ord和chr

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站